Skip to content

Commit 2e460d9

Browse files
committed
Create a base session
1 parent 9cef8a0 commit 2e460d9

File tree

1 file changed

+20
-31
lines changed

1 file changed

+20
-31
lines changed

requests_html.py

+20-31
Original file line numberDiff line numberDiff line change
@@ -641,46 +641,46 @@ def _get_first_or_list(l, first=False):
641641
return l
642642

643643

644-
class HTMLSession(requests.Session):
645-
"""A consumable session, for cookie persistence and connection pooling,
644+
class BaseSession(requests.Session):
645+
""" A consumable session, for cookie persistence and connection pooling,
646646
amongst other things.
647647
"""
648648

649-
def __init__(self, mock_browser=True, verify=False, browser_args=['--no-sandbox']):
650-
super(HTMLSession, self).__init__()
649+
def __init__(self, mock_browser : bool = True, verify : bool = False,
650+
browser_args : list = ['--no-sandbox']):
651+
super().__init__()
651652

652653
# Mock a web browser's user agent.
653654
if mock_browser:
654655
self.headers['User-Agent'] = user_agent()
655656

656-
self.hooks = {'response': self._handle_response}
657+
self.hooks['response'].append(self.response_hook)
657658

658659
self.__browser_args = browser_args
659660

660-
@staticmethod
661-
def _handle_response(response, **kwargs) -> HTMLResponse:
662-
"""Requests HTTP Response handler. Attaches .html property to
663-
class:`requests.Response <requests.Response>` objects.
664-
"""
661+
def response_hook(self, response, **kwargs) -> HTMLResponse:
662+
""" Change response enconding and replace it by a HTMLResponse. """
665663
if not response.encoding:
666664
response.encoding = DEFAULT_ENCODING
665+
return HTMLResponse._from_response(response, self)
667666

668-
return response
667+
@property
668+
async def browser(self):
669+
if not hasattr(self, "_browser"):
670+
self._browser = await pyppeteer.launch(ignoreHTTPSErrors=self.verify, headless=True, args=self.__browser_args)
671+
return self._browser
669672

670-
def request(self, *args, **kwargs) -> HTMLResponse:
671-
"""Makes an HTTP Request, with mocked User–Agent headers.
672-
Returns a class:`HTTPResponse <HTTPResponse>`.
673-
"""
674-
# Convert Request object into HTTPRequest object.
675-
r = super(HTMLSession, self).request(*args, **kwargs)
676673

677-
return HTMLResponse._from_response(r, self)
674+
class HTMLSession(BaseSession):
675+
676+
def __init__(self, **kwargs):
677+
super(HTMLSession, self).__init__(**kwargs)
678678

679679
@property
680680
def browser(self):
681681
if not hasattr(self, "_browser"):
682682
self.loop = asyncio.get_event_loop()
683-
self._browser = self.loop.run_until_complete(pyppeteer.launch(ignoreHTTPSErrors=self.verify, headless=True, args=self.__browser_args))
683+
self._browser = self.loop.run_until_complete(super().browser)
684684
return self._browser
685685

686686
def close(self):
@@ -690,7 +690,7 @@ def close(self):
690690
super().close()
691691

692692

693-
class AsyncHTMLSession(requests.Session):
693+
class AsyncHTMLSession(BaseSession):
694694
""" An async consumable session. """
695695

696696
def __init__(self, loop=None, workers=None,
@@ -703,20 +703,9 @@ def __init__(self, loop=None, workers=None,
703703
machine, multiplied by 5. """
704704
super().__init__(*args, **kwargs)
705705

706-
# Mock a web browser's user agent.
707-
if mock_browser:
708-
self.headers['User-Agent'] = user_agent()
709-
710-
self.hooks['response'].append(self.response_hook)
711-
712706
self.loop = loop or asyncio.get_event_loop()
713707
self.thread_pool = ThreadPoolExecutor(max_workers=workers)
714708

715-
def response_hook(self, response, **kwargs) -> HTMLResponse:
716-
""" Change response enconding and replace it by a HTMLResponse. """
717-
response.encoding = DEFAULT_ENCODING
718-
return HTMLResponse._from_response(response, self)
719-
720709
def request(self, *args, **kwargs):
721710
""" Partial original request func and run it in a thread. """
722711
func = partial(super().request, *args, **kwargs)

0 commit comments

Comments
 (0)