我对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()
这是实现我的目标的好方式吗?我想尽量减少服务器阻塞时间。还是应该使用gevent或其他东西?通过从Tornado和线程访问UserData,我会遇到问题吗?只要没有服务器崩溃,数据一致性并不那么重要。