multiple non-blocking tasks using asyncio and aiohttp

I am trying to perform several non-blocking tasks using asyncio and aiohttp and I don't think the way I do this is effective. I think it would be better to use expectation instead of harvest. can anyone help?

def_init__(self):
    self.event_loop = asyncio.get_event_loop()

def run(self):
    tasks = [
        asyncio.ensure_future(self.subscribe()),
        asyncio.ensure_future(self.getServer()),]
    self.event_loop.run_until_complete(asyncio.gather(*tasks))
    try:
       self.event_loop.run_forever()

@asyncio.coroutine
def getServer(self):
    server = yield from self.event_loop.create_server(handler, ip, port)
    return server

@asyncio.coroutine
def sunbscribe(self):
    while True:
        yield from asyncio.sleep(10)
        self.sendNotification(self.sub.recieve())

def sendNotification(msg):
    # send message as a client

I need to listen to the server and subscribe to listen to the broadcasts and depending on the transmitted POST message to another server.

+4
source share
2 answers

According to PEP 492 :

waiting, like yield from, pauses read_data coroutine until db.fetch completes and returns a data result.

. , :

, .

, , server, .

, , , :

self.event_loop.run_until_complete(asyncio.gather(*tasks))
try:
   self.event_loop.run_forever()

, , run_forever()

:

asyncio , , .

try:
    loop.run_until_complete(asyncio.gather(*tasks))
finally:  # close the loop no matter what or you leak FDs
    loop.close()

Uvloop , , .

import uvloop
...
    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
+2

, . pythonic,

async def foo():
    await some_future

@asyncio.coroutine
def foo()
    yield from some_future

. , , . , . ( , )

, . , , , , .

0

Source: https://habr.com/ru/post/1677009/


All Articles