Save cookies after successful authentication in HTTP crawler

This commit is contained in:
I-Al-Istannen 2021-05-22 23:30:32 +02:00
parent 3053278721
commit adfdc302d7

View File

@ -1,5 +1,6 @@
import asyncio import asyncio
from pathlib import PurePath from pathlib import PurePath
from typing import Optional
import aiohttp import aiohttp
from rich.markup import escape from rich.markup import escape
@ -25,6 +26,7 @@ class HttpCrawler(Crawler):
self._output_dir.register_reserved(self.COOKIE_FILE) self._output_dir.register_reserved(self.COOKIE_FILE)
self._authentication_id = 0 self._authentication_id = 0
self._authentication_lock = asyncio.Lock() self._authentication_lock = asyncio.Lock()
self._current_cookie_jar: Optional[aiohttp.CookieJar] = None
async def prepare_request(self) -> int: async def prepare_request(self) -> int:
# We acquire the lock here to ensure we wait for any concurrent authenticate to finish. # We acquire the lock here to ensure we wait for any concurrent authenticate to finish.
@ -43,6 +45,9 @@ class HttpCrawler(Crawler):
return return
await self._authenticate() await self._authenticate()
self._authentication_id += 1 self._authentication_id += 1
# Saving the cookies after the first auth ensures we won't need to re-authenticate
# on the next run, should this one be aborted or crash
await self._save_cookies()
async def _authenticate(self) -> None: async def _authenticate(self) -> None:
""" """
@ -51,17 +56,29 @@ class HttpCrawler(Crawler):
""" """
raise RuntimeError("_authenticate() was called but crawler doesn't provide an implementation") raise RuntimeError("_authenticate() was called but crawler doesn't provide an implementation")
async def run(self) -> None: async def _save_cookies(self) -> None:
cookie_jar = aiohttp.CookieJar() log.explain_topic("Saving cookies")
if not self._current_cookie_jar:
log.explain("No cookie jar - save aborted")
return
try: try:
cookie_jar.load(self._cookie_jar_path) self._current_cookie_jar.save(self._cookie_jar_path)
log.explain(f"Cookies saved to {escape(str(self.COOKIE_FILE))}")
except Exception:
log.print(f"[bold red]Warning:[/] Failed to save cookies to {escape(str(self.COOKIE_FILE))}")
async def run(self) -> None:
self._current_cookie_jar = aiohttp.CookieJar()
try:
self._current_cookie_jar.load(self._cookie_jar_path)
except Exception: except Exception:
pass pass
async with aiohttp.ClientSession( async with aiohttp.ClientSession(
headers={"User-Agent": f"{NAME}/{VERSION}"}, headers={"User-Agent": f"{NAME}/{VERSION}"},
cookie_jar=cookie_jar, cookie_jar=self._current_cookie_jar,
) as session: ) as session:
self.session = session self.session = session
try: try:
@ -69,7 +86,5 @@ class HttpCrawler(Crawler):
finally: finally:
del self.session del self.session
try: # They are saved in authenticate, but a final save won't hurt
cookie_jar.save(self._cookie_jar_path) await self._save_cookies()
except Exception:
log.print(f"[bold red]Warning:[/] Failed to save cookies to {escape(str(self.COOKIE_FILE))}")