7

I am trying to get cookies from the browser using aiohttp. From the docs and googling I have only found articles about setting cookies in aiohttp.

In flask I would get the cookies as simply as

cookie = request.cookies.get('name_of_cookie') # do something with cookie 

Is there a simple way to fetch the cookie from browser using aiohttp?

3 Answers 3

9

Is there a simple way to fetch the cookie from the browser using aiohttp?

Not sure about whether this is simple but there is a way:

import asyncio import aiohttp async def main(): urls = [ 'http://httpbin.org/cookies/set?test=ok', ] for url in urls: async with aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar()) as s: async with s.get(url) as r: print('JSON', await r.json()) cookies = s.cookie_jar.filter_cookies('http://httpbin.org') for key, cookie in cookies.items(): print('Key: "%s", Value: "%s"' % (cookie.key, cookie.value)) loop = asyncio.get_event_loop() loop.run_until_complete(main()) 

The program generates the following output:

JSON: {'cookies': {'test': 'ok'}} Key: "test", Value: "ok" 

Example adapted from https://aiohttp.readthedocs.io/en/stable/client_advanced.html#custom-cookies + https://docs.aiohttp.org/en/stable/client_advanced.html#cookie-jar

Now if you want to do a request using a previously set cookie:

import asyncio import aiohttp url = 'http://example.com' # Filtering for the cookie, saving it into a varibale async with aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar()) as s: cookies = s.cookie_jar.filter_cookies('http://example.com') for key, cookie in cookies.items(): if key == 'test': cookie_value = cookie.value # Using the cookie value to do anything you want: # e.g. sending a weird request containing the cookie in the header instead. headers = {"Authorization": "Basic f'{cookie_value}'"} async with s.get(url, headers=headers) as r: print(await r.json()) loop = asyncio.get_event_loop() loop.run_until_complete(main()) 

For testing urls containing a host part made up by an IP address use aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar(unsafe=True)), according to https://github.com/aio-libs/aiohttp/issues/1183#issuecomment-247788489

Sign up to request clarification or add additional context in comments.

Comments

4

Yes, the cookies are stored in request.cookies as a dict, just like in flask, so request.cookies.get('name_of_cookie') works the same.

In the examples section of the aiohttp repository there is a file, web_cookies.py that shows how to retrieve, set, and delete a cookie. Here's the section from that script that reads the cookies and returns it to the template as a preformatted string:

from pprint import pformat from aiohttp import web tmpl = '''\ <html> <body> <a href="/login">Login</a><br/> <a href="/logout">Logout</a><br/> <pre>{}</pre> </body> </html>''' async def root(request): resp = web.Response(content_type='text/html') resp.text = tmpl.format(pformat(request.cookies)) return resp 

Comments

1

You can get the cookie value, domain, path etc, without having to loop thru all cookies.

s.cookie_jar._cookies 

gives you all the cookies in a defaultdict with the domains as keys and their respective cookies as values. aiohttp uses SimpleCookie

So, to get the value of a cookie

s.cookie_jar._cookies.get("https://httpbin.org")["cookie_name"].value 

for domain, path:

s.cookie_jar._cookies.get("https://httpbin.org")["cookie_name"]["domain"] s.cookie_jar._cookies.get("https://httpbin.org")["cookie_name"]["path"] 

more info can be found here: https://docs.python.org/3/library/http.cookies.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.