Making Python Requests Without Timeout

Feb 3, 2024 ยท 2 min read

When making HTTP requests in Python using the requests library, timeouts are set by default to prevent requests from running indefinitely. However, sometimes you may want to intentionally make a request without any timeout.

Why Remove the Timeout?

There are a few reasons why you may want to remove the timeout on a request:

  • You are interacting with an API that is known to be slow to respond in some cases.
  • You want to let a long report generation process or file download complete without timing out.
  • You want to keep a long-lived connection open to a server without data actively being sent.
  • Removing the timeout introduces the risk of requests getting stuck, so only do this if you understand the tradeoffs.

    Setting timeout=None

    To make a request without timeout, you simply need to set the timeout parameter to None when creating the request:

    import requests
    
    response = requests.get('http://example.com/report', timeout=None)
    print(response.status_code)

    You can also set this at the session level to apply the setting to all requests made with that session:

    session = requests.Session()
    session.timeout = None 
    
    response = session.get('http://example.com/report')

    Other Considerations

  • Be careful about removing timeouts for requests going over the public internet, as you may end up with resources tied up waiting indefinitely.
  • For long requests, periodically check if the task completed and break out of the wait if needed.
  • In some cases, rather than waiting indefinitely, it may be better to retry timed out requests.
  • By understanding the tradeoffs and being careful about where you remove timeouts, you can use this approach to let long requests run to completion when needed in Python.

    Browse by tags:

    Browse by language:

    Tired of getting blocked while scraping the web?

    ProxiesAPI handles headless browsers and rotates proxies for you.
    Get access to 1,000 free API credits, no credit card required!