mirror of
https://github.com/kennethreitz/requests-html.git
synced 2026-06-05 23:00:20 +00:00
Add HTMLSession.browser runtime exception, AsyncSession an async close method
This commit is contained in:
committed by
Alessandro Romano
parent
47a3646405
commit
2d4c58deb8
@@ -681,6 +681,8 @@ class HTMLSession(BaseSession):
|
||||
def browser(self):
|
||||
if not hasattr(self, "_browser"):
|
||||
self.loop = asyncio.get_event_loop()
|
||||
if self.loop.is_running():
|
||||
raise RuntimeError("Cannot use HTMLSession within an existing event loop. Use AsyncHTMLSession instead.")
|
||||
self._browser = self.loop.run_until_complete(super().browser)
|
||||
return self._browser
|
||||
|
||||
@@ -711,3 +713,9 @@ class AsyncHTMLSession(BaseSession):
|
||||
""" Partial original request func and run it in a thread. """
|
||||
func = partial(super().request, *args, **kwargs)
|
||||
return self.loop.run_in_executor(self.thread_pool, func)
|
||||
|
||||
async def close(self):
|
||||
""" If a browser was created close it first. """
|
||||
if hasattr(self, "_browser"):
|
||||
await self._browser.close()
|
||||
super().close()
|
||||
|
||||
@@ -247,6 +247,15 @@ def test_browser_session():
|
||||
# assert count_chromium_process() == 0
|
||||
|
||||
|
||||
@pytest.mark.ok
|
||||
@pytest.mark.asyncio
|
||||
async def test_browser_session_fail():
|
||||
""" HTMLSession.browser should not be call within an existing event loop> """
|
||||
session = HTMLSession()
|
||||
with pytest.raises(RuntimeError):
|
||||
session.browser
|
||||
|
||||
|
||||
@pytest.mark.ok
|
||||
def test_browser_process():
|
||||
for _ in range(3):
|
||||
@@ -256,6 +265,14 @@ def test_browser_process():
|
||||
assert r.html.page == None
|
||||
|
||||
|
||||
@pytest.mark.ok
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_browser_session():
|
||||
session = AsyncHTMLSession()
|
||||
browser = await session.browser
|
||||
assert isinstance(browser, Browser)
|
||||
await session.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_containing()
|
||||
|
||||
Reference in New Issue
Block a user