Why do I get the error "ClientConnectorError"? - python-3.x

I have an asynchronous function to get data from the site:
async def get_matches_info(url):
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, proxy=proxy) as response:
...
...
...
...
except:
print('ERROR GET URL: ', url)
print(traceback.print_exc())
I have a list of about 200 links. Almost always everything is OK, but sometimes I get the following error:
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\aiohttp\connector.py", line 924, in _wrap_create_connection
await self._loop.create_connection(*args, **kwargs))
File "C:\Python37\lib\asyncio\base_events.py", line 986, in create_connection
ssl_handshake_timeout=ssl_handshake_timeout)
File "C:\Python37\lib\asyncio\base_events.py", line 1014, in _create_connection_transport
await waiter
ConnectionResetError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "parser.py", line 90, in get_matches_info
async with session.get(url, proxy=proxy) as response:
File "C:\Python37\lib\site-packages\aiohttp\client.py", line 1005, in __aenter__
self._resp = await self._coro
File "C:\Python37\lib\site-packages\aiohttp\client.py", line 476, in _request
timeout=real_timeout
File "C:\Python37\lib\site-packages\aiohttp\connector.py", line 522, in connect
proto = await self._create_connection(req, traces, timeout)
File "C:\Python37\lib\site-packages\aiohttp\connector.py", line 851, in _create_connection
req, traces, timeout)
File "C:\Python37\lib\site-packages\aiohttp\connector.py", line 1085, in _create_proxy_connection
req=req)
File "C:\Python37\lib\site-packages\aiohttp\connector.py", line 931, in _wrap_create_connection
raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host www.myscore.com.ua:443 ssl:None [None]
I checked all the links from the errors - they are working. Why can this happen?

This is probably the server limit of concurrent requests thinking you are doing a DoS attack. If you are in control of the server and it's running Apache you can raise that limit on the httpd conf for MaxKeepAliveRequests.
If not, you can also set a limit to the amount of concurrent asyncio requests by using its semaphores. The example below sets that limit to 100 concurrent requests.
async def get_matches_info(url):
sem = asyncio.Semaphore(100)
async with sem:
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, proxy=proxy) as response:
...
Note that if you call this function recursively that semaphore queue will be reset each time so you might want to consider placing this semaphore outside the function and pass it as a parameter.

Related

Migrating to discord.py 2.0 put asyncpg isn't working

I have an old bot that I'm trying to transfer to discord.py v2. Asyncpg isn't working and I'm not sure why. I've tried putting the loop and pool in the on_ready and setup_hook but that didn't work either.
import discord
from discord import app_commands
import aiohttp
import asyncio
import requests
from discord.ext import commands
import os
import asyncpg
# Pydest
# Define Client
class Aclient(commands.Bot):
def __init__(self):
super().__init__(command_prefix='.', intents=discord.Intents.default())
self.synced = False
async def setup_hook(self):
cog = await self.load_extension('cogs.weather')
print(f"Loaded All Cogs")
if not self.synced:
await self.tree.sync()
self.synced = True
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await self.tree.sync()
self.synced = True
await client.change_presence(status=discord.Status.dnd)
print(f'We have logged in as {self.user}')
client=Aclient()
# test command
#client.tree.command(name="test", description="testing")
async def test(interaction: discord.Interaction, name: str):
async with pool.acquire() as connection:
async with connection.transaction():
check = await connection.fetchrow('select * from weather')
print(check)
await connection.close()
loop = asyncio.get_event_loop()
pool = loop.run_until_complete(asyncpg.create_pool(**credentials))
I'm getting this error:
Traceback (most recent call last):
File "/Users/prathik/Documents/GitHub/red/YELLOW/bot.py", line 61, in test
async with connection.transaction():
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/transaction.py", line 62, in __aenter__
await self.start()
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/transaction.py", line 138, in start
await self._connection.execute(query)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/connection.py", line 317, in execute
return await self._protocol.query(query, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "asyncpg/protocol/protocol.pyx", line 338, in query
RuntimeError: Task <Task pending name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() running at /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/tree.py:1089>> got Future <Future pending cb=[Protocol._on_waiter_completed()]> attached to a different loop
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/prathik/Documents/GitHub/red/YELLOW/bot.py", line 60, in test
async with pool.acquire() as connection:
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/pool.py", line 220, in release
raise ex
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/pool.py", line 210, in release
await self._con.reset(timeout=budget)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/connection.py", line 1366, in reset
await self.execute(reset_query, timeout=timeout)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/connection.py", line 317, in execute
return await self._protocol.query(query, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "asyncpg/protocol/protocol.pyx", line 323, in query
File "asyncpg/protocol/protocol.pyx", line 707, in asyncpg.protocol.protocol.BaseProtocol._check_state
asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/commands.py", line 869, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'test' raised an exception: InterfaceError: cannot perform operation: another operation is in progress
Does anyone know why this is happening?

FastAPI FileResponse not entering the except block

Good afternoon friends.
I am having issues with FastApi's FileResponse and catching FileNotFoundError (or any, really) exceptions.
Here's my script:
import os
import sys
from fastapi import FastAPI, HTTPException, File, UploadFile
from fastapi.responses import FileResponse, JSONResponse
from fastapi.encoders import jsonable_encoder
#app.get("/download/{namespace}/{file_name}", response_class=FileResponse)
async def processed_file(namespace: str, file_name: str):
try:
logger.info("About to return file")
return FileResponse(
path=f'{data/{namespace}/{file_name}',
media_type="application/pdf",
filename=file_name,
)
except:
logger.info("Should log this, it doesn't")
raise HTTPException(status_code=404, detail="File not found")
If I call the API endpoint with a path to a non-existing file (which the user can do just by changing one letter in the name of the file, hence the need for this exception),
I can read in the console the following stack trace error:
[2022-10-17 21:00:24 +0000] [8] [ERROR] Exception in ASGI application
Traceback (most recent call last):
File "/opt/venv/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 404, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "/opt/venv/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/fastapi/applications.py", line 199, in __call__
await super().__call__(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/starlette.py", line 293, in _sentry_patched_asgi_app
return await middleware(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 138, in _run_asgi3
return await self._run_app(scope, lambda: self.app(scope, receive, send))
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 187, in _run_app
raise exc from None
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 182, in _run_app
return await callback()
File "/opt/venv/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/starlette.py", line 98, in _create_span_call
await old_call(*args, **kwargs)
File "/opt/venv/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/opt/venv/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 138, in _run_asgi3
return await self._run_app(scope, lambda: self.app(scope, receive, send))
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 148, in _run_app
raise exc from None
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/asgi.py", line 145, in _run_app
return await callback()
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/starlette.py", line 191, in _sentry_exceptionmiddleware_call
await old_call(self, scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/sentry_sdk/integrations/starlette.py", line 98, in _create_span_call
await old_call(*args, **kwargs)
File "/opt/venv/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/opt/venv/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/opt/venv/lib/python3.9/site-packages/starlette/routing.py", line 580, in __call__
await route.handle(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/starlette/routing.py", line 241, in handle
await self.app(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/starlette/routing.py", line 55, in app
await response(scope, receive, send)
File "/opt/venv/lib/python3.9/site-packages/starlette/responses.py", line 286, in __call__
raise RuntimeError(f"File at path {self.path} does not exist.")
RuntimeError: File at path /app/src/../data/new-namespace/wrong.pdf does not exist.
Note: I originally had except FileNotFoundError: instead of the general exception, still nothing works.
The log file correctly shows the "About to return file" entry, it never reaches the exception with the "should log this...". It also, obviously, does not return the 404 HTTPException. The stack trace error never gets to "my own" file, they are exceptions that are all within the site-packages folder.
I am baffled by this as I would have hoped that my solution would catch any exception. Still, the process is not doing what I was expecting. I have a hunch that I'm missing something obvious.
Thanks for any help, best regards,
Rafa.
The exception is raised after the return - i.e. the exception doesn't get raised when you create FileResponse - it gets raised when Starlette (the library under FastAPI) tries to read the file and return it.
Since it never gets raised in your code, there is nothing for you to catch.
Instead you could validate that whether the requested file is valid or not yourself - Starlette calls os.stat on the file and checks whether the result is None - you could do that (it's probably a good idea to validate that the filename is among the allowed files instead of blindly trusting information from a user) - or you could wrap the existing FileResponse and handle the exception there (in your own implementation of __call__ that calls into the parent class).

What is the proper way of catching http error connection with Python module aiohttp?

I want to write a simple script that checks to see if website is up. If it is not, I want to catch the http return error code using the aiohttp module for Python. In the example below, I pass in a fake website 'http://www.googlesr2332.com' rather than returning the http error, I am getting the following:
Traceback (most recent call last):
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/aiohttp/connector.py", l
ine 967, in _create_direct_connection traces=traces), loop=self._loop)
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/aiohttp/connector.py", l
ine 830, in _resolve_host
self._resolver.resolve(host, port, family=self._family) File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/aiohttp/resolver.py", li
ne 30, in resolve
host, port, type=socket.SOCK_STREAM, family=family)
File "/usr/local/lib/python3.7/asyncio/base_events.py", line 784, in getaddrinfo
None, getaddr_func, host, port, family, type, proto, flags)
File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/local/lib/python3.7/socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File "main.py", line 19, in <module>
loop.run_until_complete(main())
File "/usr/local/lib/python3.7/asyncio/base_events.py", line 579, in run_until_complete
return future.result()
File "main.py", line 8, in main
async with session.get(site) as response:
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/aiohttp/client.py", line
1012, in __aenter__
self._resp = await self._coro
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/aiohttp/client.py", line 483, in _request
timeout=real_timeout
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/aiohttp/connector.py", l
ine 523, in connect
proto = await self._create_connection(req, traces, timeout)
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/aiohttp/connector.py", l
ine 859, in _create_connection req, traces, timeout)
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/aiohttp/connector.py", l
ine 971, in _create_direct_connection
raise ClientConnectorError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host www.googlesr2332.com:80 ssl:default [Name or service not known]
Here is the sample code I am running:
import aiohttp
import asyncio
sites = ['http://www.google.com', 'http://python.org', 'http://www.facebook.com', 'http://www.googlesr2332.com']
async def main():
async with aiohttp.ClientSession() as session:
for site in sites:
async with session.get(site) as response:
if response.status == 200:
print("Status:", response.status)
print("Content-type:", response.headers['content-type'])
html = await response.text()
print("Body:", html[15], "...")
else:
print(response.status)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
You have the code when there is a response. But there is no code to handle if the connection itself has got in trouble.
import aiohttp
import asyncio
sites = ['http://www.google.com', 'http://python.org', 'http://www.facebook.com', 'http://www.googlesr2332.com']
async def main():
async with aiohttp.ClientSession() as session:
for site in sites:
try:
async with session.get(site) as response:
if response.status == 200:
print("Status:", response.status)
print("Content-type:", response.headers['content-type'])
html = await response.text()
print("Body:", html[:15], "...")
else:
print(response.status)
except aiohttp.ClientConnectorError as e:
print('Connection Error', str(e))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
When making a request to a website, you expect to get a response from it. But if your request can't reach the desired server, you can't get any response. You don't have any errors handling, so you get an error when trying to reach website that doesn't exist. The error message is pretty much self-explanatory: Cannot connect to host www.googlesr2332.com:80 ssl:default [Name or service not known]. Consider wrapping your request sending function with try except.

Task exception with aiohttp async request

Im trying to accelerate multiple get requests to a web service using asyncio and aiohttp.
For that im fetching my data from a postgresql database using psycopg2 module .fetchmany() inside a function and constructing a dictionary of 100 records to send as lists of dictionary urls to an async function named batch() . batch by batch process.
The problem im facing in batch() function is that some requests are logging the message below although the script continues and dont fail but im not able to catch and log this exceptions to later reprocess them.
Task exception was never retrieved
future: <Task finished coro=<batch.<locals>.fetch() done, defined at C:/PythonProjects/bindings/batch_fetch.py:34> exception=ClientOSError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)>
Traceback (most recent call last):
File "C:/PythonProjects/bindings/batch_fetch.py", line 36, in fetch
async with session.get(url) as resp:
File "C:\Miniconda3\lib\site-packages\aiohttp\client.py", line 1005, in __aenter__
self._resp = await self._coro
File "C:\Miniconda3\lib\site-packages\aiohttp\client.py", line 497, in _request
await resp.start(conn)
File "C:\Miniconda3\lib\site-packages\aiohttp\client_reqrep.py", line 844, in start
message, payload = await self._protocol.read() # type: ignore # noqa
File "C:\Miniconda3\lib\site-packages\aiohttp\streams.py", line 588, in read
await self._waiter
aiohttp.client_exceptions.ClientOSError: [WinError 10054] An existing connection was forcibly closed by the remote host
Task exception was never retrieved
future: <Task finished coro=<batch.<locals>.fetch() done, defined at C:/PythonProjects/bindings/batch_fetch.py:34> exception=ClientConnectorError(10060, "Connect call failed ('xx.xxx.xx.xxx', 80)")>
Traceback (most recent call last):
File "C:\Miniconda3\lib\site-packages\aiohttp\connector.py", line 924, in _wrap_create_connection
await self._loop.create_connection(*args, **kwargs))
File "C:\Miniconda3\lib\asyncio\base_events.py", line 778, in create_connection
raise exceptions[0]
File "C:\Miniconda3\lib\asyncio\base_events.py", line 765, in create_connection
yield from self.sock_connect(sock, address)
File "C:\Miniconda3\lib\asyncio\selector_events.py", line 450, in sock_connect
return (yield from fut)
File "C:\Miniconda3\lib\asyncio\selector_events.py", line 480, in _sock_connect_cb
raise OSError(err, 'Connect call failed %s' % (address,))
TimeoutError: [Errno 10060] Connect call failed ('xx.xxx.xx.xxx', 80)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/PythonProjects/bindings/batch_fetch.py", line 36, in fetch
async with session.get(url) as resp:
File "C:\Miniconda3\lib\site-packages\aiohttp\client.py", line 1005, in __aenter__
self._resp = await self._coro
File "C:\Miniconda3\lib\site-packages\aiohttp\client.py", line 476, in _request
timeout=real_timeout
File "C:\Miniconda3\lib\site-packages\aiohttp\connector.py", line 522, in connect
proto = await self._create_connection(req, traces, timeout)
File "C:\Miniconda3\lib\site-packages\aiohttp\connector.py", line 854, in _create_connection
req, traces, timeout)
File "C:\Miniconda3\lib\site-packages\aiohttp\connector.py", line 992, in _create_direct_connection
raise last_exc
File "C:\Miniconda3\lib\site-packages\aiohttp\connector.py", line 974, in _create_direct_connection
req=req, client_error=client_error)
File "C:\Miniconda3\lib\site-packages\aiohttp\connector.py", line 931, in _wrap_create_connection
raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host cms-uat.cme.in.here.com:80 ssl:None [Connect call failed ('xx.xxx.xx.xxx', 80)]
Im just entering into asyncio world as you can depict from my code, so all the advises on the full code approach for this scenario are very welcomme.
Thank you
full code below.
import psycopg2.extras
import asyncio
import json
from aiohttp import ClientSession
from aiohttp import TCPConnector
base_url = 'http://url-example/{}'
def query_db():
urls = []
# connection to postgres table , fetch data.
conn = psycopg2.connect("dbname='pac' user='user' host='db'")
cursor = conn.cursor('psycopg2 request', cursor_factory=psycopg2.extras.NamedTupleCursor)
sql = "select gid, paid from table"
cursor.execute(sql)
while True:
rec = cursor.fetchmany(100)
for item in rec:
record = {"gid": item.gid, "url": base_url.format(item.paid)}
urls.append(record.get('url'))
if not rec:
break
# send batch for async batch request
batch(urls)
# empty list of urls for new async batch request
urls = []
def batch(urls):
async def fetch(url):
async with ClientSession() as session:
async with session.get(url) as resp:
if resp.status == 200:
response = await resp.json()
# parse the url to fetch the point address id.
paid = str(resp.request_info.url).split('/')[4].split('?')[0]
# build the dictionary with pa id and full response.
resp_dict = {'paid': paid, 'response': response}
with open('sucessful.json', 'a') as json_file:
json.dump(resp_dict, json_file)
json_file.write("\n")
elif resp.status is None:
print(resp.status)
elif resp.status != 200:
print(resp.status)
response = await resp.json()
# parse the url to fetch the paid.
paid = str(resp.request_info.url).split('/')[4].split('?')[0]
# build the dictionary with paid and full response.
resp_dict = {'paid': paid, 'response': response}
with open('failed.json', 'a') as json_file:
json.dump(resp_dict, json_file)
json_file.write("\n")
loop = asyncio.get_event_loop()
tasks = []
for url in urls:
task = asyncio.ensure_future(fetch(url))
tasks.append(task)
try:
loop.run_until_complete(asyncio.wait(tasks))
except Exception:
print("exception consumed")
if __name__ == "__main__":
query_db()
Task exception was never retrieved
You see this warning when you've created some task, it finished with exception, but you never explicitly retrieved (awaited) for its result. Here's related doc section.
I bet in your case problem is with the line
loop.run_until_complete(asyncio.wait(tasks))
asyncio.wait() by default just waits when all tasks are done. It doesn't distinguish tasks finished normally or with exception, it just blocks until everything finished. In this case it's you job to retrieve exceptions from finished tasks and following part won't help you with this since asyncio.wait() will never raise an error:
try:
loop.run_until_complete(asyncio.wait(tasks))
except Exception:
print('...') # You will probably NEVER see this message
If you want to catch error as soon as it happened in one of tasks I can advice you to use asyncio.gather(). By default it will raise first happened exception. Note however that it is you job to cancel pending tasks if you want their graceful shutdown.

Proxybroker - AttributeError 'dict' object has no attribute 'expired'

Well I have this weird problem. Same script works on windows7 and on windows10 throws AttributeError. And I just can't figure out what is the difference.
This is py code:
import asyncio
from proxybroker import Broker
async def use(proxies):
while True:
proxy = await proxies.get()
if proxy is None:
break
elif 'SOCKS5' in proxy.types: # filter by type
print('Found SOCKS5 proxy: %s' % proxy)
else:
print('Found proxy: %s' % proxy)
async def find(proxies, loop):
broker = Broker(queue=proxies,
timeout=8,
attempts_conn=3,
max_concurrent_conn=200,
judges=['https://httpheader.net/', 'http://httpheader.net/'],
providers=['http://www.proxylists.net/', 'http://fineproxy.org/eng/'],
verify_ssl=False,
loop=loop)
# only anonymous & high levels of anonymity for http protocol and high for others:
types = [('HTTP', ('Anonymous', 'High')), 'HTTPS', 'SOCKS4', 'SOCKS5']
countries = ['US', 'GB', 'DE']
limit = 10
await broker.find(types=types, countries=countries, limit=limit)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
proxies = asyncio.Queue(loop=loop)
tasks = asyncio.gather(find(proxies, loop), use(proxies))
loop.run_until_complete(tasks)
And this is the error that it throws:
C:\Users\draga\AppData\Local\Programs\Python\Python36-32\python.exe "C:/Users/draga/Desktop/Rts/PROXY/Proxy.py"
C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\client.py:576: DeprecationWarning: Use async with instead
warnings.warn("Use async with instead", DeprecationWarning)
C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\helpers.py:72: DeprecationWarning: ClientSession.close() is not coroutine
warnings.warn(self._msg, DeprecationWarning)
C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\helpers.py:72: DeprecationWarning: ClientSession.close() is not coroutine
warnings.warn(self._msg, DeprecationWarning)
C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\helpers.py:72: DeprecationWarning: ClientSession.close() is not coroutine
warnings.warn(self._msg, DeprecationWarning)
Traceback (most recent call last):
File "C:/Users/draga/Desktop/Rts/PROXY/Proxy.py", line 35, in <module>
loop.run_until_complete(tasks)
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\asyncio\base_events.py", line 466, in run_until_complete
return future.result()
File "C:/Users/draga/Desktop/Rts/PROXY/Proxy.py", line 29, in find
await broker.find(types=types, countries=countries, limit=limit)
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\proxybroker\api.py", line 108, in find
await self._run(self._checker.check_judges(), action)
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\proxybroker\api.py", line 114, in _run
await tasks
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\proxybroker\api.py", line 153, in _grab
proxies = await task
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\asyncio\tasks.py", line 452, in _wait_for_one
return f.result() # May raise f.exception().
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\proxybroker\providers.py", line 68, in get_proxies
await self._pipe()
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\proxybroker\providers.py", line 101, in _pipe
await self._find_on_page(self.url)
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\proxybroker\providers.py", line 117, in _find_on_page
page = await self.get(url, data=data, headers=headers, method=method)
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\proxybroker\providers.py", line 132, in get
page = await self._get(url, data=data, headers=headers, method=method)
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\proxybroker\providers.py", line 144, in _get
method, url, data=data, headers=headers) as resp:
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\client.py", line 637, in __aenter__
self._resp = yield from self._coro
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\client.py", line 231, in _request
conn = yield from self._connector.connect(req)
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\connector.py", line 378, in connect
proto = yield from self._create_connection(req)
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\connector.py", line 686, in _create_connection
_, proto = yield from self._create_direct_connection(req)
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\connector.py", line 697, in _create_direct_connection
hosts = yield from self._resolve_host(req.url.raw_host, req.port)
File "C:\Users\draga\AppData\Local\Programs\Python\Python36-32\lib\site-packages\aiohttp\connector.py", line 666, in _resolve_host
self._cached_hosts.expired(key):
AttributeError: 'dict' object has no attribute 'expired'
Update: it seems the problem is in loop.run_until_complete(tasks) still dunno why.
ProxyBroker doesn't works after updating aiohttp to 2.1.0... You have to downgrade it to older version.

Resources