【问题标题】:How do i use Aiohttp with PyPac我如何将 Aiohttp 与 PyPac 一起使用
【发布时间】:2021-08-19 13:43:31
【问题描述】:

在我的工作中,系统不允许我们在不使用代理的情况下发出 http 请求。但是代理是通过创建 pypac 会话找到的。

如何在 aiohttp 会话中使用这个 pypac 会话来发出异步请求?

【问题讨论】:

    标签: python python-requests python-asyncio aiohttp


    【解决方案1】:

    所以,我发现答案是使用 pypac 会话获取代理,然后您可以将其放入 aiohttp 请求中:

    import asyncio
    import aiohttp
    import re
    from pypac import PACSession, get_pac
    
    pac = get_pac(url="https://somewebaddress.pac")
    pac_session = PACSession(pac)
    
    async def _fetch_async(session, url, proxy:bool=False):
        #Get the proxy for this url
        if proxy:
            proxies = pac_session \
                ._get_proxy_resolver(pac) \
                .get_proxy_for_requests(url)
            match = re.search("^(\w*)", str(url))
            proxy = proxies[match.group()]
        else:
            proxy = None
        #Fetch with aiohttp session
        async with session.request("get", url, proxy=proxy) as resp:
            return resp
    
    async def _fetch_all_async(urls):
        tasks = []
        async with aiohttp.ClientSession() as session:
            for url in urls:
                tasks.append(
                    _fetch_async(
                        session,
                        url
                        )
                    )
            return await asyncio.gather(*tasks)
    
    def request_all(self, urls:list=[]):
        #Start the loop
        loop = asyncio.get_event_loop()
        #Gaher tasks and run
        coro = _fetch_all_async(urls)
        resps = loop.run_until_complete(coro)
        return resps
    

    希望这对任何受苦的人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 2013-05-17
      相关资源
      最近更新 更多