For example, suppose you want to continue detecting objects on an edge terminal and send the processing results to the server. If HTTP POST processing is inserted during the detection loop processing, the processing will stop until a response is returned. Asynchronous communication can be realized by using python standard async / await. I will summarize how to use it.
import asyncio
import aiohttp
def say_something(future): # 5
print(future.result())
return 'hello!'
async def nested(counter):
return counter
async def test():
await asyncio.sleep(2) # 3
return'aaaaaaaaaaaaaaaaaaaa'
async def main():
rep = 0
counter = 0
while True:
if (counter % 100 == 0) and (counter != 0):
http_req = asyncio.create_task(test()) # 2
http_req.add_done_callback(say_something) # 4
counter = 0
print(f'rep: {rep}')
rep += 1
task = asyncio.create_task(nested(counter))
print(await task)
counter += 1
asyncio.run(main()) # 1
Declaration for defining a coroutine. Coroutines are a more general form of subroutines that can have multiple entry points. That is, the process can be interrupted and restarted from that location.
An image like a task scheduler is fine. By registering a coroutine for the event loop, it automatically executes, stops, and reprocesses.
http requests did not use the requests library, but used a library called aiohttp.
$ pip install aiohttp
HTTP requests can be registered as coroutines in the following form.
async def process_http_request(data):
async with aiohttp.ClientSession() as session:
async with session.post(URL, json=data) as response:
return await response.text()
Recommended Posts