{"id":134822,"date":"2023-09-17T14:22:00","date_gmt":"2023-09-17T14:22:00","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=1651606"},"modified":"2023-09-17T14:22:00","modified_gmt":"2023-09-17T14:22:00","slug":"python-async-requests-getting-urls-concurrently-via-https","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2023\/09\/17\/python-async-requests-getting-urls-concurrently-via-https\/","title":{"rendered":"Python Async Requests: Getting URLS Concurrently via HTTP(S)"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1651606&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;title&quot;:&quot;Python Async Requests: Getting URLS Concurrently via HTTP(S)&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/p><\/div>\n<p>As a <a href=\"https:\/\/blog.finxter.com\/python-developer-income-and-opportunity\/\">Python developer<\/a>, you may often deal with <strong>making HTTP requests to interact with APIs or to retrieve information from web pages<\/strong>. By default, these requests can be slow and block your program&#8217;s execution, making your code less efficient. <\/p>\n<p>This is where <strong>Python&#8217;s async requests<\/strong> come to the rescue. Asynchronous HTTP requests allow your program to continue executing other tasks while waiting for the slower request operations to complete, improving your code&#8217;s overall performance and response time significantly.<\/p>\n<p>The core of this non-blocking approach in Python relies on the <code><a href=\"https:\/\/blog.finxter.com\/how-to-check-asyncio-package-version-in-python\/\">asyncio<\/a><\/code> and <code><a href=\"https:\/\/blog.finxter.com\/how-to-install-aiohttp-in-python\/\">aiohttp<\/a><\/code> libraries, which provide the necessary tools to perform efficiently and asynchronously. Using these libraries, you can build powerful async HTTP clients to handle multiple requests concurrently without stalling your program&#8217;s main thread.<\/p>\n<p>Incorporating Python async requests into your projects can help you tackle complex web scraping scenarios, handling tasks like <a href=\"https:\/\/blog.finxter.com\/fix-rate-limit-error-in-openai-codex\/\">rate limiting<\/a> and error recovery. <\/p>\n<h2 class=\"wp-block-heading\">First Things First: Understanding Asynchronous Requests<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" fetchpriority=\"high\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709285-1024x683.webp\" alt=\"\" class=\"wp-image-1651623\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709285-1024x683.webp 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709285-300x200.webp 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709285-768x512.webp 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709285.webp 1125w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">Basic Principles of Asynchronous Requests<\/h3>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Asynchronous requests<\/strong> play a crucial role in improving the efficiency of your code when dealing with network tasks. <\/p>\n<p>When you send an asynchronous request, your program can continue executing other tasks without waiting for the request to complete. <\/p>\n<p>This is possible because of the <code>async\/await<\/code> syntax in Python, which allows you to write asynchronous code more easily. In essence, this keyword pair breaks down asynchronous code into smaller, manageable pieces to provide better readability and maintainability.<\/p>\n<p>Here&#8217;s a brief explanation of <code>async<\/code> and <code>await<\/code>:<\/p>\n<ul>\n<li><code>async<\/code>: This keyword is used to <a href=\"https:\/\/blog.finxter.com\/python-async-function\/\">define a function as asynchronous<\/a>, which means it&#8217;s able to run concurrently with other tasks in your code.<\/li>\n<li><code>await<\/code>: This keyword is used within an <code>async<\/code> function to <a href=\"https:\/\/blog.finxter.com\/python-async-await-mastering-concurrent-programming\/\">wait for the async function&#8217;s result<\/a>, allowing other tasks to proceed in the meantime.<\/li>\n<\/ul>\n<p>Here&#8217;s a simple example showcasing the <code>async\/await<\/code> syntax:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio async def example_async_function(): print(\"Task is starting\") await asyncio.sleep(1) print(\"Task is complete\") async def main(): task = asyncio.create_task(example_async_function()) await task asyncio.run(main())\n<\/pre>\n<h3 class=\"wp-block-heading\">Synchronous vs Asynchronous Requests<\/h3>\n<p>When working with network requests, it&#8217;s important to understand the difference between synchronous and asynchronous requests.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f449.png\" alt=\"\ud83d\udc49\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Synchronous requests<\/strong> involve waiting for the response of each request before proceeding, and it&#8217;s a typical way to handle requests in Python. However, this can lead to slower execution times, especially when dealing with numerous requests or slow network responses.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f449.png\" alt=\"\ud83d\udc49\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Asynchronous requests<\/strong> allow you to send multiple requests at the same time, without waiting for their individual responses. This means your program can continue with other tasks while the requests are being processed, significantly improving performance in network-intensive scenarios.<\/p>\n<p>Here&#8217;s a basic comparison between synchronous and asynchronous requests:<\/p>\n<ul>\n<li><strong>Synchronous Requests:<\/strong>\n<ul>\n<li>Send a request and wait for its response<\/li>\n<li>Block the execution of other tasks while waiting<\/li>\n<li>Can cause delays if there are many requests or slow network responses<\/li>\n<\/ul>\n<\/li>\n<li><strong>Asynchronous Requests:<\/strong>\n<ul>\n<li>Send multiple requests concurrently<\/li>\n<li>Don&#8217;t block the execution of other tasks while waiting for responses<\/li>\n<li>Improve performance in network-heavy scenarios<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>For example, the popular <a href=\"https:\/\/blog.finxter.com\/python-requests-library\/\"><code>requests<\/code> library<\/a> in Python handles synchronous requests, while libraries like <code>aiohttp<\/code> handle asynchronous requests. If you&#8217;re working with multiple network requests in your code, it&#8217;s highly recommended to implement async\/await for optimal efficiency and performance.<\/p>\n<h2 class=\"wp-block-heading\">Python and Asyncio<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-3771091-1024x683.jpeg\" alt=\"\" class=\"wp-image-1651624\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-3771091-1024x683.jpeg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-3771091-300x200.jpeg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-3771091-768x512.jpeg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-3771091.jpeg 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">Understanding Asyncio<\/h3>\n<p>Asyncio is a library introduced in Python 3.4 and has evolved rapidly, especially till Python 3.7. It provides a foundation for writing asynchronous code using the <code>async<\/code>\/<code>await<\/code> syntax. With asyncio, you can execute concurrent programming in Python, making your code more efficient and responsive. <\/p>\n<p>The library is structured around <strong>coroutines<\/strong>, an approach that allows concurrent execution of multiple tasks within an <strong>event loop<\/strong>. A coroutine is a specialized version of a <a href=\"https:\/\/blog.finxter.com\/python-return-generator-from-function\/\">Python generator function<\/a> that can suspend and resume its execution. By leveraging coroutines, you can execute multiple tasks concurrently without threading or multiprocessing.<\/p>\n<p>Asyncio makes use of <strong>futures<\/strong> to represent the results of computations that may not have completed yet. Using asyncio&#8217;s <strong>coroutine function<\/strong>, you can create coroutines that perform asynchronous tasks, like making HTTP requests or handling I\/O operations.<\/p>\n<h3 class=\"wp-block-heading\">Using Asyncio in Python<\/h3>\n<p>To utilize <code>asyncio<\/code> in your Python projects, your code must incorporate the <strong><code>asyncio<\/code> library<\/strong>. The primary method of executing asynchronous tasks is by using an <strong>event loop<\/strong>. In <a href=\"https:\/\/blog.finxter.com\/check-python-version-from-command-line-and-in-script\/\">Python 3.7 and later<\/a>, you can use <code>asyncio.run()<\/code> to create and manage the event loop for you. <\/p>\n<p>With asyncio, you can declare a function as a coroutine by using the <code>async<\/code> keyword. To call a coroutine, use the <code>await<\/code> keyword, which allows the coroutine to yield control back to the event loop and continue with other tasks.<\/p>\n<p>Here&#8217;s an example of using asyncio:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio async def greet(name, delay): await asyncio.sleep(delay) print(f\"Hello, {name}!\") async def main(): task1 = asyncio.ensure_future(greet(\"Alice\", 1)) task2 = asyncio.ensure_future(greet(\"Bob\", 2)) await task1 await task2 asyncio.run(main())\n<\/pre>\n<p>In the example above, we created two <strong>asyncio tasks<\/strong> and added them to the event loop using <code>asyncio.ensure_future()<\/code>. When <code>await<\/code> is encountered, the coroutine is suspended, and the event loop can switch to another task. This continues until all tasks in the event loop are complete.<\/p>\n<p>Now let&#8217;s get to the meat. <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f969.png\" alt=\"\ud83e\udd69\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f447.png\" alt=\"\ud83d\udc47\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<h2 class=\"wp-block-heading\">Using the Requests Library for Synchronous HTTP Requests<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-5935794-1024x683.webp\" alt=\"\" class=\"wp-image-1651625\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-5935794-1024x683.webp 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-5935794-300x200.webp 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-5935794-768x512.webp 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-5935794.webp 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<p class=\"has-global-color-8-background-color has-background\">The <a href=\"https:\/\/docs.python-requests.org\/en\/latest\/\"><code>requests<\/code><\/a> library is a popular choice for making HTTP requests in Python. However, it&#8217;s primarily designed for synchronous operations, which means it may not be the best choice for handling asynchronous requests.<\/p>\n<p>To make a simple synchronous GET request using the requests library, you would do the following:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import requests response = requests.get('https:\/\/api.example.com\/data')\nprint(response.content)\n<\/pre>\n<p>While the requests library is powerful and easy to use, it doesn&#8217;t natively support asynchronous requests. This can be a limitation when you have to make multiple requests concurrently to improve performance and reduce waiting time.<\/p>\n<h2 class=\"wp-block-heading\">Asynchronous HTTP Requests with HTTPX<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709366-1024x683.webp\" alt=\"\" class=\"wp-image-1651626\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709366-1024x683.webp 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709366-300x200.webp 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709366-768x512.webp 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709366.webp 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<p>HTTPX is a fully featured HTTP client for Python, providing both synchronous and asynchronous APIs. With support for HTTP\/1.1 and HTTP\/2, it is a modern alternative to the popular Python <code>requests<\/code> library.<\/p>\n<h3 class=\"wp-block-heading\">Why Use HTTPX?<\/h3>\n<p>HTTPX offers improved efficiency, performance, and additional features compared to other HTTP clients. Its interface is similar to <code>requests<\/code>, making it easy to switch between the two libraries. Moreover, HTTPX supports asynchronous HTTP requests, allowing your application to perform better in scenarios with numerous concurrent tasks.<\/p>\n<h3 class=\"wp-block-heading\">HTTPX Asynchronous Requests<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">To leverage the asynchronous features of HTTPX, you can use the <code>httpx.AsyncClient<\/code> class. This enables you to make non-blocking HTTP requests using Python&#8217;s <code>asyncio<\/code> library. Asynchronous requests can provide significant performance benefits and enable the use of long-lived network connections, such as WebSockets.<\/p>\n<p>Here is an example to demonstrate how async requests can be made using <code>httpx.AsyncClient<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import httpx\nimport asyncio async def fetch(url): async with httpx.AsyncClient() as client: response = await client.get(url) return response.text async def main(): urls = ['https:\/\/www.google.com', 'https:\/\/www.example.com'] tasks = [fetch(url) for url in urls] contents = await asyncio.gather(*tasks) for content in contents: print(content[:1000]) # Print the first 1000 characters of each response asyncio.run(main())\n<\/pre>\n<p>Here&#8217;s a breakdown of the code:<\/p>\n<ol>\n<li><code>fetch<\/code>: This asynchronous function fetches the content of a given URL.<\/li>\n<li><code>main<\/code>: This asynchronous function initializes the tasks to fetch content from a list of URLs and then gathers the results.<\/li>\n<li><code>asyncio.run(main())<\/code>: This runs the main asynchronous function.<\/li>\n<\/ol>\n<p>The code will fetch the content of the URLs in <code>urls<\/code> concurrently and print the first 1000 characters of each response. Adjust as needed for your use case!<\/p>\n<\/p>\n<h2 class=\"wp-block-heading\">Managing Sessions and Connections<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709291-1024x683.webp\" alt=\"\" class=\"wp-image-1651627\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709291-1024x683.webp 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709291-300x200.webp 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709291-768x512.webp 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709291.webp 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">Session Management in Async Requests<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">When working with asynchronous requests in Python, you can use sessions to manage connections. The <code>aiohttp.ClientSession<\/code> class is designed to handle multiple requests and maintain connection <a href=\"https:\/\/blog.finxter.com\/python-multiprocessing-pool-ultimate-guide\/\">pools<\/a>.<\/p>\n<p>To get started, create an instance of the <code>aiohttp.ClientSession<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import aiohttp async with aiohttp.ClientSession() as session: # Your asynchronous requests go here\n<\/pre>\n<p>Using the <a href=\"https:\/\/blog.finxter.com\/python-one-line-with-statement\/\"><code>with<\/code> statement<\/a> ensures that the session is properly closed when the block is exited. Within the <code><a href=\"https:\/\/blog.finxter.com\/python-async-with-statement-simplifying-asynchronous-code\/\">async with<\/a><\/code> block, you can send multiple requests using the same session object. This is beneficial if you are interacting with the same server or service, as it can reuse connections and reduce overhead.<\/p>\n<h3 class=\"wp-block-heading\">Connection Management with TCPConnector<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">Besides sessions, one way to manage connections is by using the <code>aiohttp.TCPConnector<\/code> class. The <code>TCPConnector<\/code> class helps in controlling the behavior of connections, such as limiting the number of simultaneous connections, setting connection timeouts, and configuring SSL settings.<\/p>\n<p>Here is how you can create a custom <code>TCPConnector<\/code> and use it with your <code>ClientSession<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import aiohttp connector = aiohttp.TCPConnector(limit=10, ssl=True)\nasync with aiohttp.ClientSession(connector=connector) as session: # Your asynchronous requests go here\n<\/pre>\n<p>In this example, the <code>TCPConnector<\/code> is set to limit the number of concurrent connections to 10 and enforce SSL connections to ensure secure communication.<\/p>\n<h2 class=\"wp-block-heading\">Implementing Concurrency and Threading<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4705612-1024x683.jpeg\" alt=\"\" class=\"wp-image-1651628\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4705612-1024x683.jpeg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4705612-300x200.jpeg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4705612-768x512.jpeg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4705612.jpeg 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">Concurrency in Async Requests<\/h3>\n<p>Concurrency for efficient and fast execution of your Python programs involves overlapping the execution of multiple tasks, which is especially useful for I\/O-bound tasks, where waiting for external resources can slow down your program. <\/p>\n<p>One way to achieve concurrency in Python is by using <code>asyncio<\/code>. This module, built specifically for asynchronous I\/O operations, allows you to use <code>async<\/code> and <code>await<\/code> keywords to manage concurrent execution of tasks without the need for threads or processes.<\/p>\n<p>For example, to make multiple HTTP requests concurrently, you can use an asynchronous library like <code>aiohttp<\/code>. Combined with <code>asyncio<\/code>, your code might look like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import aiohttp\nimport asyncio async def fetch(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text() async def main(): urls = ['https:\/\/example.com', 'https:\/\/another.example.com'] tasks = [fetch(url) for url in urls] responses = await asyncio.gather(*tasks) asyncio.run(main())\n<\/pre>\n<h3 class=\"wp-block-heading\">Threading in Async Requests<\/h3>\n<p>Another way to implement concurrency in Python is by using threads. Threading is a technique that allows your code to run concurrently by splitting it into multiple lightweight threads of execution. The <code>threading<\/code> module provides features to create and manage threads easily.<\/p>\n<p>For instance, if you want to use threads to make multiple HTTP requests simultaneously, you can employ the <code>ThreadPoolExecutor<\/code> from the <code>concurrent.futures<\/code> module combined with the <code>requests<\/code> library:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import requests\nfrom concurrent.futures import ThreadPoolExecutor def fetch(url): response = requests.get(url) return response.text def main(): urls = ['https:\/\/example.com', 'https:\/\/another.example.com'] with ThreadPoolExecutor(max_workers=len(urls)) as executor: responses = list(executor.map(fetch, urls)) main()\n<\/pre>\n<p>In this example, the <code>ThreadPoolExecutor<\/code> creates a pool of worker threads that execute the <code>fetch<\/code> function concurrently. The number of threads is determined by the length of the <code>urls<\/code> list, ensuring that all requests are handled in parallel.<\/p>\n<\/p>\n<h2 class=\"wp-block-heading\">Working with URLs in Async Requests<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">When managing and manipulating URLs in async requests, you might need to handle various tasks such as encoding parameters, handling redirects, and constructing URLs properly. Thankfully, Python provides the <code>urllib.parse<\/code> module for handling URL manipulations.<\/p>\n<p>For instance, you may want to add query parameters to a URL. To do this, you can use the <code>urllib.parse.urlencode<\/code> function:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from urllib.parse import urlencode, urljoin base_url = \"https:\/\/api.example.com\/data?\"\nparams = {\"key1\": \"value1\", \"key2\": \"value2\"} url = urljoin(base_url, urlencode(params))\n<\/pre>\n<p>After constructing the URL with query parameters, you can pass it to your async request function:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">async def main(): url = urljoin(base_url, urlencode(params)) data = await fetch_data(url) print(data) loop = asyncio.get_event_loop()\nloop.run_until_complete(main())\n<\/pre>\n<p>By properly handling URLs and leveraging async requests, you can efficiently fetch data in Python while maintaining a clear and organized code structure.<\/p>\n<h2 class=\"wp-block-heading\">Handling Errors and Timeouts<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709374-1024x683.webp\" alt=\"\" class=\"wp-image-1651629\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709374-1024x683.webp 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709374-300x200.webp 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709374-768x512.webp 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4709374.webp 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">Error Handling in Async Requests<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">When working with asynchronous requests in Python, it&#8217;s important to properly handle errors and exceptions that might occur. To do this, you can use the <code>try<\/code> and <code>except<\/code> statements. When a request fails or encounters an error, the exception will be caught in the <code>except<\/code> block, allowing you to handle the error gracefully.<\/p>\n<p>For example, when using the <code>asyncio<\/code> and <code>aiohttp<\/code> libraries, you might structure your request and error handling like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio\nimport aiohttp async def fetch_url(url): try: async with aiohttp.ClientSession() as session: async with session.get(url) as response: data = await response.text() return data except Exception as e: print(f\"An error occurred while fetching {url}: {str(e)}\") return None results = await asyncio.gather(*[fetch_url(url) for url in urls])\n<\/pre>\n<p>In this example, if an exception is encountered during the request, the error message will be printed and the function will return <code>None<\/code>, allowing your program to continue processing other URLs.<\/p>\n<h3 class=\"wp-block-heading\">Managing Timeouts in Async Requests<\/h3>\n<p>Managing timeouts in async requests is crucial to ensure requests don&#8217;t run indefinitely, consuming resources and blocking progress in your program. Setting timeouts can help prevent long waits for unresponsive servers or slow connections.<\/p>\n<p>To set a timeout for your async requests, you can use the <code>asyncio.wait_for()<\/code> function. This function takes a coroutine object and a timeout value as its arguments and will raise <code>asyncio.TimeoutError<\/code> if the timeout is reached.<\/p>\n<p>Here&#8217;s an example using the <code>asyncio<\/code> and <code>aiohttp<\/code> libraries:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio\nimport aiohttp async def fetch_url(url, timeout): try: async with aiohttp.ClientSession() as session: async with session.get(url) as response: data = await asyncio.wait_for(response.text(), timeout=timeout) return data except asyncio.TimeoutError: print(f\"Timeout reached while fetching {url}\") return None except Exception as e: print(f\"An error occurred while fetching {url}: {str(e)}\") return None results = await asyncio.gather(*[fetch_url(url, 5) for url in urls])\n<\/pre>\n<p>In this example, the requests will time out after 5 seconds, and the function will print a message indicating a timeout, then return <code>None<\/code>. This way, your program can continue processing other URLs after encountering a timeout without getting stuck in an endless wait.<\/p>\n<h2 class=\"wp-block-heading\">Frequently Asked Questions<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"683\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4855375-1024x683.webp\" alt=\"\" class=\"wp-image-1651630\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4855375-1024x683.webp 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4855375-300x200.webp 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4855375-768x512.webp 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/pexels-photo-4855375.webp 1125w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">How do I send async HTTP requests in Python?<\/h3>\n<p>To send asynchronous HTTP requests in Python, you can use a library like <a href=\"https:\/\/www.twilio.com\/blog\/asynchronous-http-requests-in-python-with-aiohttp\">aiohttp<\/a>. This library allows you to make HTTP requests using the <code>async<\/code> and <code>await<\/code> keywords, which are built into Python 3.7 and later versions. To start, you&#8217;ll need to install aiohttp and then use it to write asynchronous functions for sending HTTP requests.<\/p>\n<h3 class=\"wp-block-heading\">Which library should I use for asyncio in Python requests?<\/h3>\n<p>While the popular <a href=\"http:\/\/docs.python-requests.org\/en\/master\/community\/faq\/\">Requests library<\/a> doesn&#8217;t support asyncio natively, you can use alternatives like <a href=\"https:\/\/www.twilio.com\/blog\/asynchronous-http-requests-in-python-with-aiohttp\">aiohttp<\/a> or <a href=\"https:\/\/www.python-httpx.org\/\">httpx<\/a> that were designed specifically for asynchronous programming. Both aiohttp and httpx allow you to utilize Python&#8217;s asyncio capabilities while providing a simple and familiar API similar to Requests.<\/p>\n<h3 class=\"wp-block-heading\">What are the differences between aiohttp and requests?<\/h3>\n<p>The main differences between aiohttp and Requests lie in their approach to concurrency. aiohttp was built to work with Python&#8217;s asyncio library and uses asynchronous programming to allow for concurrent requests. On the other hand, Requests is a regular, synchronous HTTP library, which means it doesn&#8217;t inherently support concurrent requests or asynchronous programming.<\/p>\n<h3 class=\"wp-block-heading\">How can I call multiple APIs asynchronously in Python?<\/h3>\n<p>By using an async-enabled HTTP library like <a href=\"https:\/\/www.twilio.com\/blog\/asynchronous-http-requests-in-python-with-aiohttp\">aiohttp<\/a>, you can call multiple APIs asynchronously in your Python code. First, define separate async functions for the API calls you want to make, and then use the <code>asyncio.gather()<\/code> function to combine and execute these functions concurrently. This allows you to perform several API calls at once, reducing the overall time to process the requests.<\/p>\n<h3 class=\"wp-block-heading\">What is the use of async with statement in Python?<\/h3>\n<p>The <code>async with<\/code> statement in Python is an asynchronous version of the regular <code>with<\/code> statement, which is used for managing resources such as file I\/O or network connections. In an async context, the <code>async with<\/code> statement allows you to enter a context manager that expects an asynchronous exit, clean up resources upon exit, and use the <code>await<\/code> keyword to work with asynchronous operations.<\/p>\n<h3 class=\"wp-block-heading\">When should I use asynchronous programming in Python?<\/h3>\n<p>Asynchronous programming in Python is beneficial when you&#8217;re working with I\/O-bound tasks, such as network requests, web scraping, or file operations. By using async techniques, you can execute these tasks concurrently, thus reducing the overall execution time and improving performance. However, for CPU-bound tasks, using Python&#8217;s built-in <code>multiprocessing<\/code> module or regular multi-threading might be more suitable.<\/p>\n<p class=\"has-base-2-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f40d.png\" alt=\"\ud83d\udc0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-async-function\/\">Python Async Function<\/a><\/p>\n<p>The post <a rel=\"nofollow\" href=\"https:\/\/blog.finxter.com\/python-async-requests-getting-urls-concurrently-via-https\/\">Python Async Requests: Getting URLS Concurrently via HTTP(S)<\/a> appeared first on <a rel=\"nofollow\" href=\"https:\/\/blog.finxter.com\">Be on the Right Side of Change<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) As a Python developer, you may often deal with making HTTP requests to interact with APIs or to retrieve information from web pages. By default, these requests can be slow and block your program&#8217;s execution, making your code less efficient. This is where Python&#8217;s async requests come to the rescue. Asynchronous [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-134822","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/134822","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=134822"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/134822\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=134822"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=134822"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=134822"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}