[英]Enable multithreading of my web app using python Bottle framework
[英]Multithreading using python bottle framework
python和线程处理的新手,所以我不确定线程是否正在发生,如下所述-
在这里,我正在尝试为每个事件部署一个单独的线程。 当用户每次按下“提交按钮”,然后执行它时,应该创建一个新线程。
a.py文件:
from bottle import request, template,route,run,get,post
import sqlite3
import threading
import datetime
@route('/')
def index():
return template('ins')
@post('/result')
def result():
# print(request.body.read()) gives raw data
result = request.forms
usr_time = request.forms['usr_time'] #get all the values using keys
A = request.forms.get('A')
B = request.forms.get('B')
C = request.forms.get('C')
usr_hour,usr_mins = usr_time.split(":")
with sqlite3.connect("database.db") as conn:
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS bottable(hour TEXT, minutes TEXT, A TEXT, B TEXT, C TEXT)")
cur.execute("INSERT INTO bottable(hour,minutes,A,B,C) VALUES (?,?,?,?,?)", (usr_hour,usr_mins,A,B,C))
cur.execute("select * from bottable")
data = cur.fetchall() #get the whole table
conn.commit()
t1=threading.Thread(target=calc, args=(data,))
t1.start()
return template("result",result = result)
def calc(data):
print(data) #prints the whole table
match_not_found=True
while match_not_found:
h=datetime.datetime.today().strftime("%H")
mi=datetime.datetime.today().strftime("%M")
# z=[(i[2],i[3],i[4]) for i in data if i[0] == h and i[1]==mi]
for i in data:
if i[0] == h and i[1]==mi:
print ([j for j in i[2:5] if j != None])
match_not_found=False
break
if __name__ == '__main__':
run(host='localhost',port=8080,debug='True',reloader='True')
ins.tpl:
<!DOCTYPE html>
<html>
<body>
<form action="http://localhost:8080/result" method = "POST">
Select a time:
<input type="time" name="usr_time">
<br> <br>
<input type="checkbox" name="A" value="A is on" >A </input>
<br>
<input type="checkbox" name="B" value="B is on" >B </input>
<br>
<input type="checkbox" name="C" value="C is on" >C </input>
<br><br>
<input type="submit"> </input>
</form>
</body>
</html>
result.tpl:
<!doctype html>
<html>
<body>
<table border = 1>
%for key, value in result.items():
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
%end
</table>
</body>
</html>
ins.tpl和result.tpl都存储在views文件夹中(因为我正在使用bottle)。 我不确定是否每次都会生成一个新线程。 还是有更好的方法呢?
该代码看起来确实确实在每次提交时启动了一个新线程。 使用threading.enumerate()很容易验证。
看起来calc()中存在竞争条件,其中多个线程竞争通过print()函数访问stdout 。 您可以通过将所有输出行组合为单个字符串并一次打印所有内容来解决此问题(或者更好的做法是,创建打印队列并在单独的线程中进行打印)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.