When making requests with the Python aiohttp library, you may want to set cookies to handle sessions, authorization, or preferences. Cookies allow the server to store small pieces of data in the client and retrieve it later to recognize the client or maintain state.
To set a cookie in an aiohttp request, you need to create a cookie jar and attach it to the request. Here is an example:
import aiohttp
cookie_jar = aiohttp.CookieJar(unsafe=True)
async with aiohttp.ClientSession(cookie_jar=cookie_jar) as session:
session.cookie_jar.update_cookies({'user': 'john'})
async with session.get('http://example.com') as response:
print(response.cookies['user']) # 'john'
The key steps are:
- Create a
CookieJar object and setunsafe=True to allow insecure cookies over HTTP (default is HTTPS only) - When creating the
ClientSession , pass the cookie jar to attach it - Update the cookie jar directly using
update_cookies() and pass a dict of key/values - The cookies are automatically sent in requests and can be accessed on the response
Some tips when working with cookies:
Here is an example fetching a site that requires cookie login:
jar.update_cookies({'sessionid': 'abcdef12345'})
async with session.get('http://example.com/private') as resp:
if resp.status == 200:
print("Login succeeded!")
else:
print("Cookie authentication failed")
This allows easy automation and scripting for sites using cookie based sessions.
Setting cookies appropriately is important for testing sites that rely on them for user tracking or access control. aiohttp handles cookies seamlessly so you can focus on using the right values for your use case.