Skip to content

Commit 43616c1

Browse files
committed
Codes 4 Week06
1 parent 19d56f4 commit 43616c1

8 files changed

+284
-0
lines changed

Week06/sync_vs_async_v1.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import requests
2+
3+
BASE_URL = "https://www.canbula.com/prime"
4+
5+
6+
def sync_request(n: int):
7+
"""Basic synchronous request"""
8+
requests.get(f"{BASE_URL}/{n}")
9+
print(f"Sync request {n} done")
10+
11+
12+
if __name__ == "__main__":
13+
sync_request(5)

Week06/sync_vs_async_v2.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import requests
2+
3+
BASE_URL = "https://www.canbula.com/prime"
4+
5+
6+
def sync_request(n: int) -> dict:
7+
"""Basic synchronous request"""
8+
response = requests.get(f"{BASE_URL}/{n}")
9+
return response.json()
10+
11+
12+
if __name__ == "__main__":
13+
result = sync_request(5)
14+
print(result)

Week06/sync_vs_async_v3.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import requests
2+
3+
BASE_URL = "https://www.canbula.com/prime"
4+
5+
6+
def sync_request(n: int) -> dict:
7+
"""Synchronous request with error handling"""
8+
try:
9+
response = requests.get(f"{BASE_URL}/{n}")
10+
response.raise_for_status()
11+
return response.json()
12+
except requests.exceptions.RequestException as e:
13+
print(f"Request failed: {e}")
14+
return {}
15+
16+
17+
if __name__ == "__main__":
18+
result = sync_request(5)
19+
print(result)

Week06/sync_vs_async_v4.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import requests
2+
import logging
3+
4+
logging.basicConfig(
5+
format="%(levelname)s @ %(asctime)s : %(message)s",
6+
datefmt="%d.%m.%Y %H:%M:%S",
7+
level=logging.DEBUG,
8+
handlers=[logging.FileHandler("requests.log", mode="w"), logging.StreamHandler()],
9+
)
10+
BASE_URL = "https://www.canbula.com/prime"
11+
12+
13+
def sync_request(n: int) -> dict:
14+
"""Synchronous request with error handling and logging"""
15+
try:
16+
response = requests.get(f"{BASE_URL}/{n}")
17+
response.raise_for_status()
18+
logging.debug(f"Request returned with status code {response.status_code}")
19+
return response.json()
20+
except requests.exceptions.RequestException as e:
21+
logging.error(f"Request for {n} failed: {e}")
22+
return {}
23+
24+
25+
if __name__ == "__main__":
26+
logging.critical("A critical error occurred")
27+
logging.debug("A debug message")
28+
logging.error("An error occurred")
29+
logging.info("An info message")
30+
logging.warning("A warning message")
31+
result = sync_request(5)
32+
print(result)

Week06/sync_vs_async_v5.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import requests
2+
import logging
3+
4+
logging.basicConfig(
5+
format="%(levelname)s @ %(asctime)s : %(message)s",
6+
datefmt="%d.%m.%Y %H:%M:%S",
7+
level=logging.DEBUG,
8+
handlers=[logging.FileHandler("requests.log", mode="w"), logging.StreamHandler()],
9+
)
10+
HEADERS = {
11+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_6) "
12+
"AppleWebKit/537.36 (KHTML, like Gecko) "
13+
"Chrome/106.0.0.0 Safari/537.36"
14+
}
15+
BASE_URL = "https://www.canbula.com/prime"
16+
TIMEOUT = 10
17+
18+
19+
def sync_request(session: requests.Session, n: int) -> dict:
20+
"""Synchronous request with error handling and logging"""
21+
try:
22+
response = session.get(f"{BASE_URL}/{n}", headers=HEADERS, timeout=TIMEOUT)
23+
response.raise_for_status()
24+
logging.debug(f"Request returned with status code {response.status_code}")
25+
return response.json()
26+
except requests.exceptions.RequestException as e:
27+
logging.error(f"Request for {n} failed: {e}")
28+
return {}
29+
30+
31+
if __name__ == "__main__":
32+
with requests.Session() as session:
33+
print(sync_request(session, 5))

Week06/sync_vs_async_v6.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import requests
2+
import logging
3+
import time
4+
5+
logging.basicConfig(
6+
format="%(levelname)s @ %(asctime)s : %(message)s",
7+
datefmt="%d.%m.%Y %H:%M:%S",
8+
level=logging.DEBUG,
9+
handlers=[logging.FileHandler("requests.log", mode="w"), logging.StreamHandler()],
10+
)
11+
HEADERS = {
12+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_6) "
13+
"AppleWebKit/537.36 (KHTML, like Gecko) "
14+
"Chrome/106.0.0.0 Safari/537.36"
15+
}
16+
BASE_URL = "https://www.canbula.com/prime"
17+
MAX_RETRIES = 3
18+
TIMEOUT = 10
19+
20+
21+
def sync_request(session: requests.Session, n: int) -> dict:
22+
"""Synchronous request with error handling, logging, and retry logic"""
23+
for attempt in range(MAX_RETRIES):
24+
try:
25+
response = session.get(f"{BASE_URL}/{n}", headers=HEADERS, timeout=TIMEOUT)
26+
response.raise_for_status()
27+
logging.debug(f"Request returned with status code {response.status_code}")
28+
return response.json()
29+
except requests.exceptions.RequestException as e:
30+
logging.error(f"Request for {n} failed: {e} (attempt {attempt + 1})")
31+
time.sleep(2**attempt) # Exponential backoff
32+
logging.error(f"Request for {n} failed after {MAX_RETRIES} attempts")
33+
return {}
34+
35+
36+
if __name__ == "__main__":
37+
with requests.Session() as session:
38+
print(sync_request(session, 5))

Week06/sync_vs_async_v7.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import requests
2+
import logging
3+
import time
4+
5+
logging.basicConfig(
6+
format="%(levelname)s @ %(asctime)s : %(message)s",
7+
datefmt="%d.%m.%Y %H:%M:%S",
8+
level=logging.INFO,
9+
handlers=[logging.FileHandler("requests.log", mode="w"), logging.StreamHandler()],
10+
)
11+
HEADERS = {
12+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_6) "
13+
"AppleWebKit/537.36 (KHTML, like Gecko) "
14+
"Chrome/106.0.0.0 Safari/537.36"
15+
}
16+
BASE_URL = "https://www.canbula.com/prime"
17+
MAX_RETRIES = 3
18+
TIMEOUT = 10
19+
20+
21+
def sync_request(session: requests.Session, n: int) -> dict:
22+
"""Synchronous request with error handling, logging, and retry logic"""
23+
for attempt in range(MAX_RETRIES):
24+
try:
25+
response = session.get(f"{BASE_URL}/{n}", headers=HEADERS, timeout=TIMEOUT)
26+
response.raise_for_status()
27+
logging.info(f"Request returned with status code {response.status_code}")
28+
return response.json()
29+
except requests.exceptions.RequestException as e:
30+
logging.error(f"Request for {n} failed: {e} (attempt {attempt + 1})")
31+
time.sleep(2**attempt) # Exponential backoff
32+
logging.error(f"Request for {n} failed after {MAX_RETRIES} attempts")
33+
return {}
34+
35+
36+
def sync_main(n: int) -> dict:
37+
with requests.Session() as session:
38+
start_time = time.time()
39+
results = [sync_request(session, i) for i in range(1, n + 1)]
40+
total_time = time.time() - start_time
41+
logging.info(f"Time taken for {n} requests: {total_time:.2f} seconds with sync")
42+
for result in results:
43+
logging.info(result)
44+
45+
46+
if __name__ == "__main__":
47+
n = 25
48+
logging.info(f"Starting synchronous requests for {n} numbers")
49+
sync_main(n)

Week06/sync_vs_async_v8.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import requests
2+
import logging
3+
import time
4+
import asyncio
5+
import aiohttp
6+
7+
logging.basicConfig(
8+
format="%(levelname)s @ %(asctime)s : %(message)s",
9+
datefmt="%d.%m.%Y %H:%M:%S",
10+
level=logging.INFO,
11+
handlers=[logging.FileHandler("requests.log", mode="w"), logging.StreamHandler()],
12+
)
13+
HEADERS = {
14+
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_6) "
15+
"AppleWebKit/537.36 (KHTML, like Gecko) "
16+
"Chrome/106.0.0.0 Safari/537.36"
17+
}
18+
BASE_URL = "https://www.canbula.com/prime"
19+
MAX_RETRIES = 3
20+
TIMEOUT = 10
21+
22+
23+
def sync_request(session: requests.Session, n: int) -> dict:
24+
"""Synchronous request with error handling, logging, and retry logic"""
25+
for attempt in range(MAX_RETRIES):
26+
try:
27+
response = session.get(f"{BASE_URL}/{n}", headers=HEADERS, timeout=TIMEOUT)
28+
response.raise_for_status()
29+
logging.info(
30+
f"Request returned for {n} with status code {response.status_code}"
31+
)
32+
return response.json()
33+
except requests.exceptions.RequestException as e:
34+
logging.error(f"Request for {n} failed: {e} (attempt {attempt + 1})")
35+
time.sleep(2**attempt) # Exponential backoff
36+
logging.error(f"Request for {n} failed after {MAX_RETRIES} attempts")
37+
return {}
38+
39+
40+
async def async_request(session: aiohttp.ClientSession, n: int) -> dict:
41+
"""Asynchronous request with error handling, logging, and retry logic"""
42+
for attempt in range(MAX_RETRIES):
43+
try:
44+
response = await session.get(
45+
f"{BASE_URL}/{n}", headers=HEADERS, timeout=TIMEOUT
46+
)
47+
response.raise_for_status()
48+
logging.info(f"Request returned for {n} with status code {response.status}")
49+
return await response.json()
50+
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
51+
logging.error(f"Request for {n} failed: {e} (attempt {attempt + 1})")
52+
await asyncio.sleep(2**attempt)
53+
logging.error(f"Request for {n} failed after {MAX_RETRIES} attempts")
54+
return {}
55+
56+
57+
def sync_main(n: int) -> dict:
58+
with requests.Session() as session:
59+
start_time = time.time()
60+
results = [sync_request(session, i) for i in range(1, n + 1)]
61+
total_time = time.time() - start_time
62+
logging.info(f"Time taken for {n} requests: {total_time:.2f} seconds with sync")
63+
for result in results:
64+
logging.info(result)
65+
66+
67+
async def async_main(n: int) -> dict:
68+
async with aiohttp.ClientSession() as session:
69+
start_time = time.time()
70+
tasks = [async_request(session, i) for i in range(1, n + 1)]
71+
results = await asyncio.gather(*tasks)
72+
total_time = time.time() - start_time
73+
logging.info(
74+
f"Time taken for {n} requests: {total_time:.2f} seconds with async"
75+
)
76+
for result in results:
77+
logging.info(result)
78+
79+
80+
if __name__ == "__main__":
81+
n = 25
82+
logging.info(f"Starting synchronous requests for {n} numbers")
83+
sync_main(n)
84+
85+
logging.info(f"Starting asynchronous requests for {n} numbers")
86+
asyncio.run(async_main(n))

0 commit comments

Comments
 (0)