【发布时间】:2018-02-26 22:15:18
【问题描述】:
Aiohttp 提供了一个上下文管理器来创建客户端会话。建议每个 http 查询使用一个会话(在大多数情况下每个应用程序)https://aiohttp.readthedocs.io/en/stable/client_quickstart.html#make-a-request
但是石墨烯使用解析器需要声明为类方法:
http://docs.graphene-python.org/en/latest/execution/execute/
对于石墨烯也存在异步执行器https://github.com/graphql-python/aiohttp-graphql
有什么方法可以与上下文异步执行所有解析器?
示例:
async def get_task(session, api_url, id):
""" Function to resolve task from rest API"""
async with session.get(api_url+id) as response:
return await response.json()
class Query(graphene.ObjectType):
task = graphene.Field(Task)
async def resolve_task(self, info, session, id=1):
"""This method needs to be run
in async with aiohttp.ClientSession() as session:
context"""
return await get_task(session, url, id)
我想到了带有全局变量的装饰器或中间件,但它看起来很难看。有更多的房地产和pythonic方式吗?
【问题讨论】:
标签: python python-asyncio aiohttp contextmanager graphene-python