-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在tornado中使用会不会出现你说的与asyncio自有协程不兼容的问题? #1
Comments
这个 如果你想在 那个 我的文档里面提到了个暂时的解决方案就是将协程函数返回的协程转换为Future或者Task,现在看来还是转换成Future更加干净。
#!/usr/bin/env python3
# coding: utf-8
import asyncio
import functools
import aioqiniu
import tornado.web
from tornado.platform.asyncio import AsyncIOMainLoop
QINIU_ACCESS_KEY = "QINIU_ACCESS_KEY"
QINIU_SECRET_KEY = "QINIU_SECRET_KEY"
def convert_asyncio_future(method):
"""解决tornado中使用aiohttp的ClientSession的不兼容问题"""
@functools.wraps(method)
async def wrapper(self, *args, **kwargs):
coro = method(self, *args, **kwargs)
return await asyncio.ensure_future(coro)
return wrapper
class QueryFileStatHandler(tornado.web.RequestHandler):
"""查询七牛云文件对象数据的请求处理器"""
def initialize(self, qiniuclient):
self.qiniuclient = qiniuclient
@convert_asyncio_future
async def get(self, bucket: str, key: str):
res = await self.qiniuclient.get_file_stat(bucket, key)
self.write(res)
pass
async def create_qiniu_client(*args, **kwargs):
"""在协程中创建七牛客户端
避免七牛客户端自动创建aiohttp的ClientSession因不在协程中创建而发出提示信息。
"""
return aioqiniu.QiniuClient(*args, **kwargs)
def main():
# tornado使用asyncio的主IO循环,即`asyncio.get_event_loop()`
AsyncIOMainLoop().install()
loop = asyncio.get_event_loop()
qiniuclient = loop.run_until_complete(
create_qiniu_client(QINIU_ACCESS_KEY, QINIU_SECRET_KEY))
params = {"qiniuclient": qiniuclient}
app = tornado.web.Application([
(r"/query/(.*?)/(.*?)", QueryFileStatHandler, params),
])
app.listen(8888)
loop.run_forever()
if __name__ == "__main__":
main() 我在Linux下试验这个代码是没有问题的。 |
忘了说我的Python版本是3.5, 你在你那边自己测一测看看吧。 另外, |
非常感谢,之前没注意 Ps. 用了你的SDK后,七牛这部分的 Ps2. 看源码在本场景下 Ps3. 装饰器定义成这样,可能有些微小的性能提升。
|
|
Ps. 使用时发现图片处理场景需要访问 |
好的,等我整理之后准备下一版本 |
七牛官方没有提供async的SDK,在pip上找到的。学习一个。
观察到使用了aiohttp,在你的另一篇文章中提到,由于使用了asyncio特有的协程,会出现一定的问题。「我自己在python3.6 + tornado4.5.1下复现了该问题」因此,该SDK是否不能直接在tornado中使用?
ps. 此前我在处理run_on_executor的时候碰到过类似的问题,run_on_executor的协程不能直接await,需要使用asyncio.futures.wrap_future装饰一层。与你的文章提到的用装饰器解决方案很类似。
The text was updated successfully, but these errors were encountered: