Changing aiohttp function to be context managers to simplify calls.

This commit is contained in:
Roland 2024-10-02 21:10:49 -06:00
parent 23878b365a
commit 82acca00b6
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
6 changed files with 76 additions and 69 deletions

View file

@ -112,7 +112,9 @@ async def request_archive(url: str) -> Tuple[str, Optional[str], Optional[str]]:
data = {'url': url}
try:
contents, status = await aiohttp_post(f'{ARCHIVE_SERVICE}/json', json_=data, timeout=ARCHIVE_TIMEOUT)
async with aiohttp_post(f'{ARCHIVE_SERVICE}/json', json_=data, timeout=ARCHIVE_TIMEOUT) as response:
status = response.status
contents = await response.json()
if contents and (error := contents.get('error')):
# Report the error from the archive service.
raise Exception(f'Received error from archive service: {error}')

View file

@ -15,7 +15,9 @@ logger = logger.getChild(__name__)
async def fetch_hrefs(url: str) -> List[str]:
content, status = await aiohttp_get(url, timeout=20)
async with aiohttp_get(url, timeout=20) as response:
status = response.status
content = await response.content.read()
if status != HTTPStatus.OK:
raise RuntimeError(f'Failed to fetch file catalog')

View file

@ -1274,37 +1274,42 @@ async def aiohttp_session(timeout: int = None) -> ClientSession:
yield session
async def aiohttp_post(url: str, json_, timeout: int = None) -> Tuple[Dict, int]:
"""Perform an async aiohttp POST request. Return the json contents."""
@contextlib.asynccontextmanager
async def aiohttp_post(url: str, json_, timeout: int = None, headers: dict = None) -> ClientResponse:
"""Perform an async aiohttp POST request. Yield the response in a session."""
headers = headers or DEFAULT_HTTP_HEADERS
async with aiohttp_session(timeout) as session:
async with session.post(url, json=json_) as response:
return await response.json(), response.status
async with session.post(url, json=json_, headers=headers) as response:
yield response
async def aiohttp_get(url: str, timeout: int = None, headers: dict = None) -> Tuple[bytes, int]:
"""Perform an async aiohttp GET request. Return the contents."""
@contextlib.asynccontextmanager
async def aiohttp_get(url: str, timeout: int = None, headers: dict = None) -> ClientResponse:
"""Perform an async aiohttp GET request. Yield the response in a session."""
headers = headers or DEFAULT_HTTP_HEADERS
async with aiohttp_session(timeout) as session:
async with session.get(url, headers=headers) as response:
return await response.content.read(), response.status
yield response
async def aiohttp_head(url: str, timeout: int = None, headers: dict = None) -> Tuple[ClientResponse, int]:
"""Perform an async aiohttp HEAD request. Return the contents."""
@contextlib.asynccontextmanager
async def aiohttp_head(url: str, timeout: int = None, headers: dict = None) -> ClientResponse:
"""Perform an async aiohttp HEAD request. Yield the response in a session."""
headers = headers or DEFAULT_HTTP_HEADERS
async with aiohttp_session(timeout) as session:
async with session.head(url, headers=headers) as response:
return response, response.status
yield response
async def speed_test(url: str, timeout: int | None = 10) -> int:
"""Request the last megabyte of the provided url, return the content length divided by the time elapsed (speed)."""
response, status = await aiohttp_head(url)
content_length = response.headers['Content-Length']
async with aiohttp_head(url) as response:
content_length = response.headers['Content-Length']
start_bytes = int(content_length) - 10485760
range_ = f'bytes={start_bytes}-{content_length}'
start_time = datetime.now()
content, status = await aiohttp_get(url, headers={'Range': range_}, timeout=timeout)
async with aiohttp_get(url, headers={'Range': range_}, timeout=timeout) as response:
content = await response.content.read()
elapsed = int((datetime.now() - start_time).total_seconds())
return len(content) // elapsed
@ -1355,41 +1360,41 @@ FILENAME_MATCHER = re.compile(r'.*filename="(.*)"')
async def get_download_info(url: str, timeout: int = 60) -> DownloadFileInfo:
"""Gets information (name, size, etc.) about a downloadable file at the provided URL."""
response, status = await aiohttp_head(url, timeout)
download_logger.debug(f'{response.headers=}')
try:
links = response.headers.getall('Link')
except KeyError:
links = None
async with aiohttp_head(url, timeout) as response:
download_logger.debug(f'{response.headers=}')
try:
links = response.headers.getall('Link')
except KeyError:
links = None
new_links = list()
if links:
# Convert "Link" header strings to DownloadFileInfoLink.
for idx, link in enumerate(links):
url, *props = link.split(';')
url = url[1:-1]
properties = dict()
for prop in props:
name, value = prop.strip().split('=')
properties[name] = value
new_links.append(DownloadFileInfoLink(
url,
properties.get('rel').strip() if 'rel' in properties else None,
properties.get('type').strip() if 'type' in properties else None,
int(properties.get('pri').strip()) if 'pri' in properties else None,
properties.get('geo').strip() if 'geo' in properties else None,
))
new_links = list()
if links:
# Convert "Link" header strings to DownloadFileInfoLink.
for idx, link in enumerate(links):
url, *props = link.split(';')
url = url[1:-1]
properties = dict()
for prop in props:
name, value = prop.strip().split('=')
properties[name] = value
new_links.append(DownloadFileInfoLink(
url,
properties.get('rel').strip() if 'rel' in properties else None,
properties.get('type').strip() if 'type' in properties else None,
int(properties.get('pri').strip()) if 'pri' in properties else None,
properties.get('geo').strip() if 'geo' in properties else None,
))
info = DownloadFileInfo(
type=response.headers.get('Content-Type'),
size=int(response.headers['Content-Length']) if 'Content-Length' in response.headers else None,
accept_ranges=response.headers.get('Accept-Ranges'),
status=response.status,
location=response.headers.get('Location'),
links=new_links,
)
info = DownloadFileInfo(
type=response.headers.get('Content-Type'),
size=int(response.headers['Content-Length']) if 'Content-Length' in response.headers else None,
accept_ranges=response.headers.get('Accept-Ranges'),
status=response.status,
location=response.headers.get('Location'),
links=new_links,
)
disposition = response.headers.get('Content-Disposition')
disposition = response.headers.get('Content-Disposition')
if disposition and 'filename' in disposition:
if (match := FILENAME_MATCHER.match(disposition)) and (groups := match.groups()):

View file

@ -5,6 +5,7 @@ import mock
from wrolpi.downloader import DownloadResult
from wrolpi.files.downloader import FileDownloader
from wrolpi.scrape_downloader import ScrapeHTMLDownloader
from wrolpi.switches import await_switches
EXAMPLE_HTTP = '''
<html>
@ -20,7 +21,7 @@ EXAMPLE_HTTP = '''
'''
async def fake_fetch_http(self, url: str):
async def fake_fetch_html(self, url: str):
return EXAMPLE_HTTP
@ -37,17 +38,17 @@ async def test_scrape_html_downloader(test_directory, test_session, test_downloa
settings = {
'depth': 1,
'suffix': '.pdf',
'suffix': '.PDF', # Suffix case is ignored.
'destination': str(destination),
}
test_download_manager.create_download('https://example.com/dir', 'scrape_html', settings=settings,
sub_downloader_name='file')
assert_download_urls(['https://example.com/dir', ])
with mock.patch('wrolpi.scrape_downloader.ScrapeHTMLDownloader.fetch_http', fake_fetch_http), \
with mock.patch('wrolpi.scrape_downloader.ScrapeHTMLDownloader.fetch_html', fake_fetch_html), \
mock.patch('wrolpi.files.downloader.FileDownloader.do_download', fake_file_do_download):
await test_download_manager.wait_for_all_downloads()
await asyncio.sleep(1)
await await_switches()
assert_download_urls([
'https://example.com/dir',
@ -70,7 +71,7 @@ async def test_scrape_html_downloader_html(test_directory, test_session, test_do
sub_downloader_name='file')
assert_download_urls(['https://example.com/dir', ])
with mock.patch('wrolpi.scrape_downloader.ScrapeHTMLDownloader.fetch_http', fake_fetch_http), \
with mock.patch('wrolpi.scrape_downloader.ScrapeHTMLDownloader.fetch_html', fake_fetch_html), \
mock.patch('wrolpi.files.downloader.FileDownloader.do_download', fake_file_do_download):
await test_download_manager.wait_for_all_downloads()
await asyncio.sleep(1)

View file

@ -1,11 +1,9 @@
import pathlib
from http import HTTPStatus
from urllib.parse import urlparse
from wrolpi.common import aiohttp_session, logger, get_html_soup
from wrolpi.common import logger, get_html_soup, aiohttp_get
from wrolpi.downloader import Downloader, Download, DownloadResult
from wrolpi.errors import UnrecoverableDownloadError
from wrolpi.vars import DEFAULT_HTTP_HEADERS
logger = logger.getChild(__name__)
@ -39,12 +37,9 @@ class ScrapeHTMLDownloader(Downloader):
return '<ScrapeHTMLDownloader>'
@staticmethod
async def fetch_http(url: str) -> str:
async with aiohttp_session(timeout=60 * 5) as session:
async with session.get(url, headers=DEFAULT_HTTP_HEADERS) as response:
logger.debug(f'Got status={response.status_code} from {url}')
if response.status_code == HTTPStatus.OK:
return await response.text()
async def fetch_html(url: str) -> str:
async with aiohttp_get(url, timeout=60 * 5) as response:
return await response.text()
async def do_download(self, download: Download) -> DownloadResult:
if download.attempts > 3:
@ -68,6 +63,8 @@ class ScrapeHTMLDownloader(Downloader):
if not destination.is_dir():
raise UnrecoverableDownloadError(f'Destination does not exist: {destination}')
suffix = suffix.lower()
page_count = 0
for i in range(depth):
@ -80,7 +77,7 @@ class ScrapeHTMLDownloader(Downloader):
break
# Get the HTML of the URL.
content = await self.fetch_http(url)
content = await self.fetch_html(url)
page_count += 1
if not content:
logger.error(f'Failed to download url: {url}')
@ -101,7 +98,7 @@ class ScrapeHTMLDownloader(Downloader):
logger.debug(f'Not a real anchor: {a}')
continue
child_url = resolve_url(url, href)
if child_url and child_url.endswith(suffix):
if child_url and child_url.lower().endswith(suffix):
# Found a file that the User requested.
download_urls.append(child_url)
else:

View file

@ -850,13 +850,13 @@ async def test_aiohttp(simple_web_server):
"""Test that aiohttp convenience functions work."""
httpd, server_url = simple_web_server
content, status = await common.aiohttp_get(server_url)
assert content
assert status == 200
async with common.aiohttp_get(server_url) as response:
assert response.content.read()
assert response.status == 200
content, status = await common.aiohttp_head(server_url)
assert content
assert status == 200
async with common.aiohttp_head(server_url) as response:
assert response.content.read()
assert response.status == 200
def test_can_connect_to_server(simple_web_server):