Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 龙卷风网和线_Python_Tornado - Fatal编程技术网

Python 龙卷风网和线

Python 龙卷风网和线,python,tornado,Python,Tornado,我不熟悉Tornado和Python线程。我希望达到以下目标: 我有一个Tornado web服务器,它接收用户的请求。我想在本地存储一些数据,并定期将其作为批量插入写入数据库 import tornado.ioloop import tornado.web import threading # Keep userData locally in memory UserData = {} def background(f): """ a threading decorator

我不熟悉Tornado和Python线程。我希望达到以下目标: 我有一个Tornado web服务器,它接收用户的请求。我想在本地存储一些数据,并定期将其作为批量插入写入数据库

import tornado.ioloop
import tornado.web
import threading

# Keep userData locally in memory
UserData = {}

def background(f):
    """
    a threading decorator
    use @background above the function you want to thread
    (run in the background)
    """
    def bg_f(*a, **kw):
        threading.Thread(target=f, args=a, kwargs=kw).start()
    return bg_f

@background
def PostRecentDataToDBThread(iter = -1):
    i = 0
    while iter == -1 or i < iter: 
        #send data to DB
        UserData = {}
        time.sleep(5*60)
        i = i + 1

class AddHandler(tornado.web.RequestHandler):
    def post(self):
        userID = self.get_argument('ui')
        Data = self.get_argument('data')

        UserData[userID] = Data 


if __name__ == "__main__":
    tornado.options.parse_command_line()

    print("start PostRecentDataToDBThread")
    ### Here we start a thread that periodically sends data to the data base.
    ### The thread is called every 5min. 
    PostRecentDataToDBThread(-1)

    print("Started tornado on port: %d" % options.port)

    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/add", AddHandler)
    ])
    application.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()
导入tornado.ioloop
导入tornado.web
导入线程
#将用户数据本地保存在内存中
用户数据={}
def背景(f):
"""
线程装饰器
在要线程化的函数上方使用@background
(在后台运行)
"""
def bg_f(*a,**kw):
threading.Thread(target=f,args=a,kwargs=kw).start()
返回bg\u f
@背景
def PostRecentDataToDBThread(iter=-1):
i=0
而iter==-1或i

这是实现我目标的好方法吗?我想尽量减少服务器阻塞时间。还是我应该用gevent或其他什么?通过访问Tornado和线程中的用户数据,我会遇到问题吗?只要没有服务器崩溃,数据一致性在这里就不那么重要了

Tornado不打算与多线程一起使用。它基于epoll在代码的不同部分之间切换上下文

一般来说,我建议通过消息队列将数据发送到单独的工作进程(比如+RabbitMQ,它与Tornado集成得非常好)。工作进程可以使用数据累积消息并将其批量写入数据库,或者您可以使用此设置实现任何其他数据处理逻辑

或者,您可以使用(例如)Redis with将传入数据异步写入内存中的数据库,然后根据Redis配置将其异步转储到磁盘