Skip to content

Commit 6ffe436

Browse files
committed
Refactor.
1 parent a215eed commit 6ffe436

6 files changed

Lines changed: 32 additions & 16 deletions

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
Make asynchronous HTTP requests and write to disk using **asyncio**, **aiohttp**, & **aiofiles**.
1313

14-
* **Tutorial**: https://hackersandslackers.com/concurrency-asyncio-aiohttp-aiofiles/
14+
* **Tutorial**: https://hackersandslackers.com/async-requests-with-aiohttp/
1515
* **Demo**: TBD
1616

1717

asyncio_tutorial/__init__.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Script initialization."""
22
import asyncio
3-
from asyncio import Task
3+
from asyncio import SelectorEventLoop, Task
44
from typing import List
55

66
from aiohttp import ClientSession
@@ -19,12 +19,20 @@ async def init_script():
1919
async with ClientSession(headers=HTML_HEADERS) as session:
2020
tasks = await create_tasks(session, urls, HTML_EXPORT_DIR)
2121
await asyncio.gather(*tasks)
22+
loop = inspect_loop(tasks)
2223
LOGGER.success(
23-
f"Successfully saved {len(urls)} HTML pages to `{HTML_EXPORT_DIR}`"
24+
f"Saved {len(urls)} HTML pages to `{HTML_EXPORT_DIR}`. Loop: {loop}"
2425
)
2526

2627

27-
def inspect_loop(tasks: List[Task]):
28-
"""Get async loop info."""
28+
def inspect_loop(tasks: List[Task]) -> SelectorEventLoop:
29+
"""
30+
Get async loop info.
31+
32+
:param: List[Task] tasks
33+
34+
:return: SelectorEventLoop
35+
"""
2936
loop = tasks[0].get_loop()
3037
LOGGER.info(f"Loop info: {loop}")
38+
return loop

asyncio_tutorial/fetcher.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from aiohttp import ClientError, ClientSession, InvalidURL
33

44
from asyncio_tutorial.logger import LOGGER
5-
from asyncio_tutorial.writer import write_html_file
5+
from asyncio_tutorial.writer import write_fetched_file_locally
66

77

88
async def fetch_and_save_url(
@@ -20,9 +20,14 @@ async def fetch_and_save_url(
2020
"""
2121
try:
2222
async with session.get(url) as resp:
23-
text = await resp.read()
23+
body = await resp.read()
24+
filetype = (
25+
resp.headers.get("Content-Type")
26+
.replace("; charset=UTF-8", "")
27+
.replace("text/", "")
28+
)
2429
LOGGER.info(f"Successfully fetched URL {i + 1} of {total_count}: {url}")
25-
await write_html_file(url, text, directory)
30+
await write_fetched_file_locally(url, body, filetype, directory)
2631
except InvalidURL as e:
2732
LOGGER.error(f"Unable to fetch invalid URL `{url}`: {e}")
2833
except ClientError as e:

asyncio_tutorial/writer.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,21 @@
44
from .logger import LOGGER
55

66

7-
async def write_html_file(url: str, text: bytes, directory: str):
7+
async def write_fetched_file_locally(
8+
url: str, body: bytes, filetype: str, directory: str
9+
):
810
"""
911
Write contents of fetched URL to new file in local directory.
1012
1113
:param str url: URL which was fetched.
12-
:param bytes text: Source HTML of a single fetched URL.
14+
:param bytes body: Source HTML of a single fetched URL.
15+
:param str filetype: File extension to save fetched data as.
1316
:param str directory: Local directory to save exports to.
1417
"""
1518
try:
16-
filename = f"{directory}/{url.split('/')[-2]}.html"
19+
filename = f"{directory}/{url.split('/')[-2]}.{filetype}"
1720
async with aiofiles.open(filename, mode="wb+") as f:
18-
await f.write(text)
21+
await f.write(body)
1922
await f.close()
2023
except Exception as e:
21-
LOGGER.error(f"Unexpected error while writing file from `{url}`: {e}")
24+
LOGGER.error(f"Unexpected error while writing from `{url}`: {e}")

poetry.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@ loguru = "*"
3030
[tool.poetry.dev-dependencies]
3131
pytest = "*"
3232
mypy = "*"
33-
black = "^21.7b0"
33+
black = "^21.9b0"
3434
isort = "5.9.3"
35-
flake8 = "^3.9.0"
35+
flake8 = "^3.9.2"
3636

3737
[tool.poetry.scripts]
3838
run = "main:init_script"

0 commit comments

Comments
 (0)