From 07a8866f93cb87273ef5a84ec1f29e720fc17468 Mon Sep 17 00:00:00 2001 From: prettysunflower Date: Tue, 24 Jun 2025 21:54:20 -0400 Subject: [PATCH] Refactored the aiohttp_session parameter to use a decorator to access or create it when used as a function parameter name --- surugaya_api/product.py | 54 ++++++++++++++++++++++++++--------------- 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/surugaya_api/product.py b/surugaya_api/product.py index d753463..7a2bbf1 100644 --- a/surugaya_api/product.py +++ b/surugaya_api/product.py @@ -7,6 +7,30 @@ from bs4 import BeautifulSoup from surugaya_api.consts import SURU_COOKIE_STRING +import inspect + +def get_or_create_aiohttp_session(func): + async def wrapper(*args, **kwargs): + sig = inspect.signature(func) + bound_args = sig.bind(*args, **kwargs) + bound_args.apply_defaults() + + aiohttp_session = bound_args.arguments.get("aiohttp_session") + is_created = False + + if not aiohttp_session: + is_created = True + aiohttp_session = aiohttp.ClientSession() + bound_args.arguments["aiohttp_session"] = aiohttp_session + + result = await func(*bound_args.arguments.values()) + + if is_created: + await aiohttp_session.close() + + return result + + return wrapper @dataclass class ProductStock: condition: str @@ -34,30 +58,23 @@ class Product: id: int name: str main_image_href: str - stock: [ProductStock] + stock: list[ProductStock] @property def in_stock(self): return not self.stock +@get_or_create_aiohttp_session async def load_product(product_id, aiohttp_session=None): - if not aiohttp_session: - _aiohttp_session = aiohttp.ClientSession() - else: - _aiohttp_session = aiohttp_session - - async with _aiohttp_session.get( - url="https://www.suruga-ya.jp/product/detail/" + str(product_id), - headers={ - "Cookie": SURU_COOKIE_STRING, - }, + async with aiohttp_session.get( + url="https://www.suruga-ya.jp/product/detail/" + str(product_id), + headers={ + "Cookie": SURU_COOKIE_STRING, + }, ) as response: page = await response.text() - - page_bs = BeautifulSoup( - page, features="html.parser" - ) + page_bs = BeautifulSoup(page, features="html.parser") product = Product( id=int(product_id), @@ -66,10 +83,9 @@ async def load_product(product_id, aiohttp_session=None): stock=[ ProductStock.from_item_price(item_price) for item_price in page_bs.select(".item-price") - ] + ], ) - if not aiohttp_session: - await _aiohttp_session.close() + return product + - return product \ No newline at end of file