The recommended way to use asyncio for a socket server is:
import asyncio
async def handle_client(reader, writer):
request = (await reader.read(100)).decode()
response = "Data received."
writer.write(response.encode())
async def main():
loop.create_task(asyncio.start_server(handle_client, 'localhost', 15555))
loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()
This works fine, but now I need to receive appropriate client request and then use aiohttp library to fetch data from a 3rd party restful API.
This requires creating a session variable as follows:
from aiohttp import ClientSession
session = ClientSession()
But this also should be inside a coroutine itself, so I'll put it inside main:
async def main():
session = ClientSession()
loop.create_task(asyncio.start_server(handle_client, '', 55555))
Now I need to pass the session variable to the aiohttp get coroutine to fetch the rest API data:
async with session.get(url, params=params) as r:
try:
return await r.json(content_type='application/json')
except aiohttp.client_exceptions.ClientResponseError:
....
My question is how can I pass the session variable to handle_client coroutine, if it insists on only having reader,writer parameters, and globals don't help me because sessions must exist inside coroutines?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…