Asynchronous context manager

前端 未结 3 415
旧巷少年郎
旧巷少年郎 2020-12-08 10:01

I have an asynchronous API which I\'m using to connect and send mail to an SMTP server which has some setup and tear down to it. So it fits nicely into using a context

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 10:35

    The asyncio_extras package has a nice solution for this:

    import asyncio_extras
    
    @asyncio_extras.async_contextmanager
    async def smtp_connection():
        client = SMTPAsync()
        ...
    

    For Python < 3.6, you'd also need the async_generator package and replace yield client with await yield_(client).

提交回复
热议问题