python-aiohttpHow to set headers in Python Aiohttp?
Headers can be set in Python Aiohttp using the add_headers
method. This method takes a dictionary of headers as an argument.
import aiohttp
headers = {
'User-Agent': 'My User Agent 1.0',
'From': '[email protected]'
}
async with aiohttp.ClientSession() as session:
async with session.get('https://www.example.com', headers=headers) as resp:
print(resp.status)
print(resp.headers)
Output example
200
{'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': '1256', 'Connection': 'close', 'Date': 'Sun, 21 Jun 2020 11:45:45 GMT', 'Server': 'Apache', 'Last-Modified': 'Wed, 09 Jul 2003 23:32:50 GMT', 'ETag': '"3f80f-1b6-3e1cb03b"', 'Accept-Ranges': 'bytes', 'User-Agent': 'My User Agent 1.0', 'From': '[email protected]'}
Code explanation
import aiohttp
- imports the aiohttp libraryheaders = {...}
- creates a dictionary of headersasync with aiohttp.ClientSession() as session
- creates a client sessionasync with session.get('https://www.example.com', headers=headers) as resp
- sends a GET request to the specified URL with the headersprint(resp.status)
- prints the response statusprint(resp.headers)
- prints the response headers
Helpful links
Related
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to create a server with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to check if a session is closed with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to disable SSL verification in Python Aiohttp?
- How to create a connection pool with Python Aiohttp?
- How to close a Python Aiohttp session?
- How to use HTTP2 with Python Aiohttp?
More of Python Aiohttp
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to rate limit with Python Aiohttp?
- How to retry a request with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to use HTTP2 with Python Aiohttp?
- How to get a response with Python Aiohttp?
- How to get response text with Python Aiohttp?
See more codes...