aiohttp服务器全局请求
项目描述
- info:
aiohttp服务器全局请求
安装
pip install aiohttp_request
使用
import asyncio
from aiohttp import web
from aiohttp_request import ThreadContext, middleware_factory, grequest, get_request
def thread():
assert grequest['sense'] == 42
async def task():
# grequest is `lazy` version of request
assert grequest['sense'] == 42
loop = asyncio.get_event_loop()
# works for threads as well with ThreadContext
await loop.run_in_executor(None, ThreadContext(thread))
async def hello(request):
# get_request is on-demand function to get current request
assert get_request() is request
request['sense'] = 42
# asyncio.Task is supported
await asyncio.ensure_future(task())
return web.Response(text="Hello, world")
app = web.Application(middlewares=[middleware_factory()])
app.add_routes([web.get('/', hello)])
web.run_app(app)
需要Python 3.7+,无法支持旧版本的Python!!!
注意
aiohttp-request通过contextvars_executor与线程配合良好,无需ThreadContext
import asyncio
from aiohttp import web
from aiohttp_request import middleware_factory, grequest
from contextvars_executor import ContextVarExecutor
def thread():
assert grequest['sense'] == 42
async def hello(request):
request['sense'] = 42
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, thread)
return web.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)
项目详情
关闭
aiohttp_request-0.0.2.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | e17701b995fccb036971bd82e7616e809ccb776bf61084c24f4f3bfbf54fdfbf |
|
MD5 | 5c9799878916c88510fc8caf10bcb62e |
|
BLAKE2b-256 | eea4754f0aed1dccf724de3c593c441e9497ec2590ab8f523eba5ad188a307c7 |