aiohttp服务器的全局请求
aiohttp-request的Python项目详细描述
info: | Global request for aiohttp server |
---|
安装
pip install aiohttp_request
用法
importasynciofromaiohttpimportwebfromaiohttp_requestimportThreadContext,middleware_factory,grequest,get_requestdefthread():assertgrequest['sense']==42asyncdeftask():# grequest is `lazy` version of requestassertgrequest['sense']==42loop=asyncio.get_event_loop()# works for threads as well with ThreadContextawaitloop.run_in_executor(None,ThreadContext(thread))asyncdefhello(request):# get_request is on-demand function to get current requestassertget_request()isrequestrequest['sense']=42# asyncio.Task is supportedawaitasyncio.ensure_future(task())returnweb.Response(text="Hello, world")app=web.Application(middlewares=[middleware_factory()])app.add_routes([web.get('/',hello)])web.run_app(app)
python 3.7+是必需的,没有办法支持旧的python版本!!!
注释
库依赖于PEP 567及其asyncio support
aiohttp请求通过contextvars_executor与线程很好地协同工作,不需要threadcontext
importasynciofromaiohttpimportwebfromaiohttp_requestimportmiddleware_factory,grequestfromcontextvars_executorimportContextVarExecutordefthread():assertgrequest['sense']==42asyncdefhello(request):request['sense']=42loop=asyncio.get_event_loop()awaitloop.run_in_executor(None,thread)returnweb.Response(text="Hello, world")loop=asyncio.get_event_loop()loop.set_default_executor(ContextVarExecutor())app=web.Application(middlewares=[middleware_factory()])app.add_routes([web.get('/',hello)])web.run_app(app)