python-aiohttpHow to make async requests with Python Aiohttp?
Using Aiohttp, you can make asynchronous requests in Python. To do this, you need to create an async function and use the aiohttp.ClientSession object to make the request.
Example code
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://python.org')
print(html)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Output example
<!doctype html>
<!--[if lt IE 7]> <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9"> <![endif]-->
<!--[if IE 7]> <html class="no-js ie7 lt-ie8 lt-ie9"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie8 lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en" dir="ltr"> <!--<![endif]-->
<head>
...
The code consists of the following parts:
import aiohttp- imports the aiohttp library.async def fetch(session, url)- defines an asynchronous function that takes a session and a URL as parameters and returns the response text.async def main()- defines an asynchronous function that creates a session and calls thefetchfunction.if __name__ == '__main__'- checks if the script is being run directly and creates an event loop.loop.run_until_complete(main())- runs themainfunction until it is complete.
Helpful links
Related
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to get response code with Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to use HTTP2 with Python Aiohttp?
- How to disable SSL verification in Python Aiohttp?
- How to check if a session is closed with Python Aiohttp?
- How to create a server with Python Aiohttp?
- How to get a response with Python Aiohttp?
- How to get response text with Python Aiohttp?
- How to make parallel requests with Python Aiohttp?
More of Python Aiohttp
- How to get response text with Python Aiohttp?
- How to set headers in Python Aiohttp?
- How to set query parameters with Python Aiohttp?
- How to use HTTP2 with Python Aiohttp?
- How to disable SSL verification in Python Aiohttp?
- How to get JSON data using Python Aiohttp?
- How to get request parameters using Python Aiohttp?
- Setting CORS with Python Aiohttp?
- How to use keepalive with Python Aiohttp?
- How to handle x-www-form-urlencoded with Python Aiohttp?
See more codes...