analitics

Pages

Tuesday, April 16, 2024

Python 3.12.1 : aiohttp python package - part 001.

This python package named aiohttp provides asynchronous HTTP client and server functionality.
You can find more about this pytho package on the GitHub repo and the official page.
The last time I wrote about this python package was on Thursday, July 9, 2020 in this source code tutorial titled Python 3.8.3 : About aiohttp python package.
A few days ago I tested two python scripts that use this python packet.
One script makes a benchmark and the other uses cookie technology as a test.
Here is the script that makes the benchmark...
import timeit
from http import cookies

from yarl import URL

from aiohttp import CookieJar

def filter_large_cookie_jar():
    """Filter out large cookies from the cookie jar."""
    jar = CookieJar()
    c = cookies.SimpleCookie()
    domain_url = URL("http://maxagetest.com/")
    other_url = URL("http://otherurl.com/")

    for i in range(5000):
        cookie_name = f"max-age-cookie{i}"
        c[cookie_name] = "any"
        c[cookie_name]["max-age"] = 60
        c[cookie_name]["domain"] = "maxagetest.com"
    jar.update_cookies(c, domain_url)
    assert len(jar) == 5000
    assert len(jar.filter_cookies(domain_url)) == 5000
    assert len(jar.filter_cookies(other_url)) == 0

    filter_domain = timeit.timeit(lambda: jar.filter_cookies(domain_url), number=1000)
    filter_other_domain = timeit.timeit(
        lambda: jar.filter_cookies(other_url), number=1000
    )
    print(f"filter_domain: {filter_domain}")
    print(f"filter_other_domain: {filter_other_domain}")

filter_large_cookie_jar()
Here is the result obtained...
python test_bench_001.py
filter_domain: 59.85247729999901
filter_other_domain: 0.042927300000883406
Is more easier to understand code on how to use a cookie with this Python package using the httpbin website.
httpbin.org is a simple HTTP request and response service. It provides an easy way to test and inspect various aspects of HTTP communication.
Let's see the source code:
import asyncio
import aiohttp

async def main():
    urls = [
        'http://httpbin.org/cookies/set?test=ok',
    ]

    async with aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar()) as s:
        for url in urls:
            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(f'Key: "{cookie.key}", Value: "{cookie.value}"')

if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass
The result of this running is this ...
python test_cookie_001.py
JSON: {'cookies': {'test': 'ok'}}
Key: "test", Value: "ok"