from datetime import datetime

"""
Explanation: HTTPX
<img src="https://raw.githubusercontent.com/encode/httpx/master/docs/img/butterfly.png" alt="HTTPX Logo" style="width: 400px;"/>
https://www.python-httpx.org/
A next-generation HTTP client for Python.
HTTPX is a fully featured HTTP client for Python 3, which provides sync and async APIs, and support for both HTTP/1.1 and HTTP/2.
Alternatives: aiohttp, asks
End of explanation
"""


import requests

def requests_get(index=None):
    response = requests.get("https://httpbin.org/delay/1")
    response.raise_for_status()
    print(f"{index} - {response.status_code} - {response.elapsed}")

requests_get()

before = datetime.now()

for index in range(0, 5):
    requests_get(index)
    
after = datetime.now()
print(f"total time: {after - before}")

import httpx

def httpx_get(index=None):
    response = httpx.get("https://httpbin.org/delay/1")
    response.raise_for_status()
    print(f"{index} - {response.status_code} - {response.elapsed}")

httpx_get()

before = datetime.now()

for index in range(0, 5):
    httpx_get(index)
    
after = datetime.now()
print(f"total time: {after - before}")

async with httpx.AsyncClient() as client:
    response = await client.get('https://httpbin.org/delay/1')
print(response)

async def async_httpx_get(index=None):
    async with httpx.AsyncClient() as client:
        response = await client.get("https://httpbin.org/delay/1")
        response.raise_for_status()
        print(f"{index} - {response.status_code} - {response.elapsed}")

await async_httpx_get()

before = datetime.now()

for index in range(0, 5):
    await async_httpx_get(index)
    
after = datetime.now()
print(f"total time: {after - before}")

many_gets = tuple(async_httpx_get(index) for index in range(0,5))

import asyncio

before = datetime.now()

await asyncio.gather(*many_gets)

after = datetime.now()
print(f"total time: {after - before}")

semaphore = asyncio.Semaphore(3)

async def async_semaphore_httpx_get(index=None):
    async with semaphore:
        async with httpx.AsyncClient() as client:
            response = await client.get("https://httpbin.org/delay/1")
            response.raise_for_status()
            print(f"{index} - {response.status_code} - {response.elapsed}")

semaphore_many_gets = tuple(
    async_semaphore_httpx_get(index) for index in range(0,10))

before = datetime.now()

await asyncio.gather(*semaphore_many_gets)

after = datetime.now()
print(f"total time: {after - before}")

"""
Explanation: Using httpbin.org:
https://httpbin.org/delay/1
End of explanation
"""


