An async consumable session.
| 738 | |
| 739 | |
| 740 | class AsyncHTMLSession(BaseSession): |
| 741 | """ An async consumable session. """ |
| 742 | |
| 743 | def __init__(self, loop=None, workers=None, |
| 744 | mock_browser: bool = True, *args, **kwargs): |
| 745 | """ Set or create an event loop and a thread pool. |
| 746 | |
| 747 | :param loop: Asyncio loop to use. |
| 748 | :param workers: Amount of threads to use for executing async calls. |
| 749 | If not pass it will default to the number of processors on the |
| 750 | machine, multiplied by 5. """ |
| 751 | super().__init__(*args, **kwargs) |
| 752 | |
| 753 | self.loop = loop or asyncio.get_event_loop() |
| 754 | self.thread_pool = ThreadPoolExecutor(max_workers=workers) |
| 755 | |
| 756 | def request(self, *args, **kwargs): |
| 757 | """ Partial original request func and run it in a thread. """ |
| 758 | func = partial(super().request, *args, **kwargs) |
| 759 | return self.loop.run_in_executor(self.thread_pool, func) |
| 760 | |
| 761 | async def close(self): |
| 762 | """ If a browser was created close it first. """ |
| 763 | if hasattr(self, "_browser"): |
| 764 | await self._browser.close() |
| 765 | super().close() |
| 766 | |
| 767 | def run(self, *coros): |
| 768 | """ Pass in all the coroutines you want to run, it will wrap each one |
| 769 | in a task, run it and wait for the result. Return a list with all |
| 770 | results, this is returned in the same order coros are passed in. """ |
| 771 | tasks = [ |
| 772 | asyncio.ensure_future(coro()) for coro in coros |
| 773 | ] |
| 774 | done, _ = self.loop.run_until_complete(asyncio.wait(tasks)) |
| 775 | return [t.result() for t in done] |
no outgoing calls
searching dependent graphs…