How can you efficiently make a synchronous request with requests in an asynchronous application?
Asked at
AI answer
If there are many requests or the application makes extensive use of asyncio, an asynchronous HTTP client such as httpx.AsyncClient or aiohttp is preferable. If you need to keep using requests, move the call out of the event loop and into a thread—for example, with asyncio.to_thread:
import asyncio
import requests
async def fetch(url):
response = await asyncio.to_thread(requests.get, url, timeout=10)
response.raise_for_status()
return response.json()
This prevents the event loop from being blocked while waiting for a response. For a series of requests, account for the thread limit and reuse the client/connections if the library supports it.
Also asked at Циан
- Tell us about your experience: on which projects you worked at [company] and [company], what technologies you used, and what you were responsible for?
- Tell me about the product/project you worked on and your main tasks.
- Why are you looking for a new job now?
- What ORM do you know?
- In what order does Python search for methods during multiple (horizontal) inheritance?
Similar questions
- Conceptually, how is the Event Loop in asyncio structured?
- What happens if you call time.sleep inside a coroutine?
- Give two examples of tasks: when is it better to use asyncio, and when threading?
- Does asyncio have an advantage over multithreading for 10,000 I/O requests?
- What is asyncio? When is it better to use asyncio, and when should you use threads (threading)? How can you speed up heavy mathematical computations (CPU-bound) in Python?