简体   繁体   English

使用python瓶框架进行多线程

[英]Multithreading using python bottle framework

New to python and threading, so i'm not sure if threading is happening as mentioned below -- python和线程处理的新手,所以我不确定线程​​是否正在发生,如下所述-

Here, I'm trying to deploy an individual thread for each event. 在这里,我正在尝试为每个事件部署一个单独的线程。 A new thread should be created when user presses "submit button" every time, then execute it. 当用户每次按下“提交按钮”,然后执行它时,应该创建一个新线程。

a.py file : 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 : 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: 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>

Both ins.tpl and result.tpl are stored in views folder('cause i'm using bottle). ins.tpl和result.tpl都存储在views文件夹中(因为我正在使用bottle)。 I'm not sure if a new thread is generated every time. 我不确定是否每次都会生成一个新线程。 Or is there a better way to do it? 还是有更好的方法呢?

The code looks like it does indeed kick-off a new thread with every submit. 该代码看起来确实确实在每次提交时启动了一个新线程。 This is easy to verify using threading.enumerate() . 使用threading.enumerate()很容易验证。

It looks like there is a race condition in calc() with multiple threads competing for access to stdout via the print() function. 看起来calc()中存在竞争条件,其中多个线程竞争通过print()函数访问stdout You can fix that by combining all output lines into a single string and printing all at once (or better, create a print queue and do the printing in a separate thread). 您可以通过将所有输出行组合为单个字符串并一次打印所有内容来解决此问题(或者更好的做法是,创建打印队列并在单独的线程中进行打印)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM