Flask 跑在 Tornado 上,使用 requests 库导致阻塞的问题

2016-12-05 10:28:28 +08:00
 woostundy

服务是 Flask 写的,外面套了层 Tornado ,该怎么让 requests 变成非阻塞?

3309 次点击
所在节点    问与答
18 条回复
DozySun
2016-12-05 10:36:19 +08:00
tornado 换成 gunicorn+gevent
woostundy
2016-12-05 10:40:27 +08:00
@DozySun ……改造规模有点大啊
ericls
2016-12-05 10:58:44 +08:00
啊? 还可以这么神奇直接改?
julyclyde
2016-12-05 11:34:54 +08:00
你外边套的是 tornado web server 而不是 tornado web framework 吧?那就直接改 gevent monkey patch 就得了
woostundy
2016-12-05 11:49:17 +08:00
@julyclyde 嗯,其实改起来也快。
loalj
2016-12-05 11:51:41 +08:00
requests 库换成 tornado 自带的 async httpclient 试一试?
DozySun
2016-12-05 11:52:05 +08:00
如果不重度依赖 requests 可以用 tornado 的异步 httpclient
否则就是 concurrent.futures
woostundy
2016-12-05 11:55:34 +08:00
@loalj @DozySun
需要立刻返回 request 的结果,用异步 httpclient 的话,很难写吧?
回调怎么返回给 flask 的 response
timonwong
2016-12-05 12:05:24 +08:00
我不知道在 tornado 上跑 flask 有什么意义,跟用单个进程,什么 threading, gevent, eventlet 都不用跑有多大区别,有没有老司机出来指点一下?
loalj
2016-12-05 12:08:33 +08:00
@woostundy 大概像这样

```
@gen.coroutine
def async_response():
http_client = AsyncHTTPClient()
res = yield http_client.fetch(url)
return res
```
woostundy
2016-12-05 12:11:25 +08:00
@loalj 多谢,完了我试试
Livid
2016-12-05 12:23:06 +08:00
耗时可能会超过半秒的函数一律放进 rq 或者 celery 做异步处理。
woostundy
2016-12-05 12:27:09 +08:00
@loalj 不过 2.7 里没法在有 yield 的方法里再写 return ,应该是 yield res 吧?
woostundy
2016-12-05 12:27:51 +08:00
@Livid 需要即时返回 request 的结果, celery 没法解决吧?
wwqgtxx
2016-12-05 13:28:10 +08:00
你这种需求还是用 gunicorn 或者 uwsgi 包装一下吧
loalj
2016-12-05 14:12:43 +08:00
@woostundy raise gen.Return(res)
woostundy
2016-12-05 14:14:51 +08:00
@loalj 用 yield 也 OK~ 刚试了可行
cloverstd
2016-12-05 15:55:26 +08:00
@woostundy

@gen.coroutine
def long_time_function():
task_id = task_function.delay()
while True:
gen.sleep(0.1)
res = get_res_from(task_id)
if res:
raise gen.Return(res)

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

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

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

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

© 2021 V2EX