tips: 需要有 aiohttp client and server 基础。
aiohttp 共享 session:
aiohttp:
github address
client persistent_session
import aiohttp
from aiohttp import web
async def my_request_handler(request):
session = request.app['persistent_session']
# async with session.get("http://python.org") as resp:
# print(resp.status)
async with session.post(url='http://localhost:30080/v1/login/username',
json={'username': 'wph', 'password': '123123'}) as resp:
# print(resp.status)
# print(resp.text())
print(await resp.text())
return await resp.json()
async def method(request):
await my_request_handler(request)
return web.Response(text='success')
async def method2(request):
await my_request_handler(request)
return web.Response(text='success')
async def persistent_session(app):
print('session starting ......')
app['persistent_session'] = session = aiohttp.ClientSession()
yield
print('session closing ......')
await session.close()
if __name__ == '__main__':
app = web.Application()
app.cleanup_ctx.append(persistent_session)
app.router.add_route('get', "/", method)
app.router.add_route('get', "/2", method2)
web.run_app(app, host='localhost', port=8080)