各位大仙们,看看下面的这段代码是否是 tornado 异步的代码?

2014-11-26 10:08:36 +08:00
 p8p8
#!/usr/bin/env python3

import os
import urllib.parse

import tornado.gen
import tornado.escape
import tornado.httpclient
import tornado.ioloop
import tornado.web
from base import BaseHandler

from config import web as config
import db
import rs
import qntoken
from auth import auth_required

from lib.utils import Validators
import random
from lib.desdec import *

class MainHandler(BaseHandler):
    #@auth_required
    @tornado.gen.coroutine
    def get(self):
        user_rows = yield self.db.get_userlist()
        self.set_header('Content-Type', 'application/json')
        self.write(tornado.escape.json_encode(user_rows))

这样的代码是tornado异步成功了吗?

2918 次点击
所在节点    Python
8 条回复
fasling
2014-11-26 10:23:41 +08:00
daniel7725
2014-11-26 10:32:22 +08:00
这要看你的"db.get_userlist()"是不是支持异步的。如果它只是阻塞的 那么这么写是木有用的。
geew
2014-11-26 10:44:10 +08:00
以前发过一个讨论的 你可以看看
http://www.v2ex.com/t/88797
然后有人提到了用celery和线程池, 有些资料可以参考下:
http://segmentfault.com/blog/houxiyang/1190000000729575
http://segmentfault.com/q/1010000000759709
zenliver
2014-11-26 13:29:33 +08:00
@geew https://github.com/mayflaver/tornado-celery 简单易懂, 一看就明白
p8p8
2014-11-26 15:07:09 +08:00
@daniel7725 数据用的是postgresql 异步的方法,应该就是了?
tonghuashuai
2014-11-26 18:14:52 +08:00
class GenAsyncHandler(RequestHandler):
@gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch("http://example.com")
do_something_with_response(response)
self.render("template.html")
tonghuashuai
2014-11-26 18:15:37 +08:00
刚发的全乱了,看官方文档吧: http://tornado.readthedocs.org/en/latest/gen.html
p8p8
2014-11-27 16:29:33 +08:00
@tonghuashuai 嗯,谢谢你,我后来明白了,我的那段代码,就是异步的,关键在于数据库那个部分,而postgresql我也已经用异步处理了,所以整个代码是异步执行的。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/149333

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX