[英]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.