“async with” in Python 3.4

前端 未结 2 898
时光取名叫无心
时光取名叫无心 2021-02-05 04:36

The Getting Started docs for aiohttp give the following client example:

import asyncio
import aiohttp

async def fetch_page(session, url):
    with aiohttp.Timeo         


        
2条回答
  •  独厮守ぢ
    2021-02-05 04:57

    Just don't use the result of session.get() as a context manager; use it as a coroutine directly instead. The request context manager that session.get() produces would normally release the request on exit, but so does using response.text(), so you could ignore that here:

    @asyncio.coroutine
    def fetch(session, url):
        with aiohttp.Timeout(10):
            response = yield from session.get(url)
            return (yield from response.text())
    

    The request wrapper returned here doesn't have the required asynchronous methods (__aenter__ and __aexit__), they omitted entirely when not using Python 3.5 (see the relevant source code).

    If you have more statements between the session.get() call and accessing the response.text() awaitable, you probably want to use a try:..finally: anyway to release the connection; the Python 3.5 release context manager also closes the response if an exception occurred. Because a yield from response.release() is needed here, this can't be encapsulated in a context manager before Python 3.4:

    import sys
    
    @asyncio.coroutine
    def fetch(session, url):
        with aiohttp.Timeout(10):
            response = yield from session.get(url)
            try:
                # other statements
                return (yield from response.text())
            finally:
                if sys.exc_info()[0] is not None:
                    # on exceptions, close the connection altogether
                    response.close()
                else:
                    yield from response.release()
    

提交回复
热议问题