Skip to content

Add timeout support when calling into python web app #1451

Closed

Description

@falkben

Checklist

  • There are no similar issues or pull requests for this yet.
  • I discussed this idea on the community chat and feedback is positive.

Is your feature related to a problem? Please describe.

I would like to be able to set a timeout when calling into a python web app.

My specific use case is to safe-guard against calls my app makes to external API's or databases which would, without a timeout, can cause the test suite to hang.

I would like to be able to set a timeout in the Client instantiation or request and for that timeout to cancel it's request to the python app if it runs over the timeout.

e.g.:

httpx.AsyncClient(
        app=app, timeout=5
    ) as client:
    response = await client.get("/test_url")

or

response = await client.get("/test_url", timeout=)

for a 5 second timeout

Describe the solution you would like.

I think that using asyncio.wait_for with the timeout would do the trick. However, not sure how to make this compatible with trio as well.

A WIP is located here: master...falkben:falkben/app_timeout

Essentially the following, but with the backend support for trio and asyncio.

- await self.app(scope, receive, send)
+ await asyncio.wait_for(self.app(scope, receive, send), timeout.get("connect"))

Describe alternatives you considered

I've tried adding a middleware to my test app using asyncio.wait_for, but it does not cancel routes that are not async (called by run_in_executor by FastAPI):

class TimeoutMiddleware:
    def __init__(self, app, timeout):
        self._app = app
        self._timeout = timeout

    async def __call__(self, scope, receive, send):
        print("timeout", self._timeout)
        await asyncio.wait_for(self._app(scope, receive, send), self._timeout)

Additional context

Activity

  1. added
    user-experience
    on Jan 15, 2021
  2. julianogv commented on Jan 19, 2021

    @julianogv

    Be careful when using wait_for + http requests.

    I was trying to use "wait_for" to force an specific timeout for my requests and whenever it reaches the timeout it raises an
    exception and the connection status stays as ACTIVE forever - forcing a new connection to be created every time and keeping invalid connections at the pool.

    You should use "asyncio.wait" instead of "asyncio.wait_for - that way it won't cancel the task and httpx will properly release the connection"

    e.g.:

    import httpx
    import asyncio
    
    
    async def test():
        async with httpx.AsyncClient() as client:
            # just to open the first connection and reuse it when calling with wait_for
            r = await client.get('https://github.com/encode/httpx')
            assert r.status_code == 200
            try:
                # it must raise a timeout exception
                await asyncio.wait_for(client.get('https://github.com/encode/httpx'), timeout=0.1)
            except asyncio.exceptions.TimeoutError:
                ...
            finally:
                print(client._transport._connections)
                #>> {(b'https', b'github.com', 443): {<AsyncHTTPConnection http_version=HTTP/1.1 state=2>}}
                # state 2 = ACTIVE
                # as you can see, the connection will stay on the pool and won't be reused
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(test())
    
  3. lovelydinosaur commented on Mar 23, 2021

    @lovelydinosaur
    Member

    I can't see us doing this, no.

    Calling into python web apps directly should generally be deterministic (and backing services typically ought to be mocked, or locally available). For instance, the Django test client, wouldn't provide this kind of timeout configuration, and I'm not keen on us doing so either.

    It sounds like you probably want timeouts around the places you're calling into backing services (rather than around the request itself).

    You could alternately customize the behaviour of httpx.ASGITransport (eg. through subclassing it, and wrapping the request up in an overall timeout, then using client = httpx.Client(transport=MyCustomAppTransport(app))

  4. patrickkwang commented on Aug 27, 2021

    @patrickkwang

    If we're not going to enforce timeouts when using an app, can we raise some sort of exception when a timeout is requested? Silently ignoring the requested timeout seems rather unintuitive to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    user-experience

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions