Sling Academy
Home/Python/How to set timeouts when using aiohttp in Python

How to set timeouts when using aiohttp in Python

Last updated: August 19, 2023

aiohttp is an open-source Python library that can be used to make HTTP requests asynchronously (with the async/await syntax). A timeout is a limit on how much time a request can take before it is canceled and an exception is raised.

This concise, example-based article will walk you through three different ways to specify a timeout for your requests when using aiohttp to prevent your program from hanging or wasting resources when the server is slow or unresponsive (the default timeout set by the library is 300 seconds seems too long for most network operations).

Using the timeout parameter of the session.get() method and the like

You can use the timeout parameter of the session.get()session.post(), session.head(), session.put(), session.patch(), session.options(), and session.delete() methods to set a timeout for a single request (set it to 0 or None for an unlimited timeout).

Example:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio
import aiohttp


async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(
            "https://api.slingacademy.com/v1/sample-data/blog-posts",
            # set timeout to 1 second
            timeout=1,
        ) as response:
            print(response.status)
            print(await response.json())


asyncio.run(main())

If the time taken by a request is longer than the timeout specified, then an exception will be raised, and the request will be canceled. You can use a try-except block to gracefully handle the exception and perform some actions, such as retrying the request, logging the error, or returning a default value.

Example:

try:
    async with session.get(
       "https://api.slingacademy.com/v1/sample-data/blog-posts",
        # set timeout to 1 second
        timeout=1,
    ) as response:
        print(response.status)
        print(await response.json())
except asyncio.TimeoutError:
    print("The request took too long to complete.")

See also: Sample Blog Posts – Public REST API for Practice.

Using the ClientTimeout class

You can use the ClientTimeout class to create a timeout object that specifies different types of timeouts, such as connectsock_connectsock_read, or total. You can then pass this object to the timeout parameter of the ClientSession constructor to apply it to all requests made by that session.

In the example below, we’ll create a session with a connect timeout of 5 seconds and a read timeout of 15 seconds:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio
import aiohttp


async def main():
    # create a client timeout object
    client_timeout = aiohttp.ClientTimeout(connect=5, sock_read=15)

    async with aiohttp.ClientSession(timeout=client_timeout) as session:
        # make your requests here


asyncio.run(main())

This way is convenient if you want to set the same timeout for multiple requests.

Using the timeout parameter of the session.request() method

This approach uses the timeout parameter of the ClientSession.request() method to set a timeout for any HTTP method, such as GET, POST, PUT, DELETE, etc. 

Example:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio
import aiohttp


async def main():
    async with aiohttp.ClientSession() as session:
        async with session.request(
            "POST",
            "https://api.slingacademy.com/v1/sample-data/products",
            # set timeout to 5 seconds
            timeout=5,
            json={
                "name": "Example T-Shirt",
                "price": 19.99,
                "description": "A T-Shirt with the Sling Academy logo on it.",
            },
        ) as response:
            print(response.status)
            print(await response.text())


asyncio.run(main())

See also: Sample Products – Mock REST API for Practice.

Next Article: Python Requests Module: How to Set Timeouts

Previous Article: Using aiohttp to make POST requests in Python (with examples)

Series: Python: Network & JSON tutorials

Python

You May Also Like

  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots
  • Monitoring Order Book Imbalances for Trading Signals via cryptofeed
  • Detecting Arbitrage Opportunities Across Exchanges with cryptofeed