I am writing my API using aiohttp, asycpg and asyncpgsa.
I create my application:
async def create_app():
app = web.Application(client_max_size=1024 ** 2 * 70)
Then I execute these lines:
async def on_start(app):
app['db'] = asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backend")
async def on_shutdown(app):
app['db'].close()
app.on_startup.append(on_start)
app.on_cleanup.append(on_shutdown)
In general, in the example where I got it from, it is written like this:
app['db'] = await asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backend")
But if I write like this, then an error is thrown "ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 5432)"
But that's okay. Now, when the user visits the URL I need, this function should be triggered:
async def post(request):
async with request.app["db"].acquire() as conn:
query = select([datab.post])
result = await conn.fetch(query)
The datab file says this:
from sqlalchemy import Table, Text, VARCHAR, Integer, MetaData, Column
meta = MetaData()
post = Table(
"post", meta,
Column("id", Integer, primary_key=True),
Column("title", VARCHAR, nullable=True),
Column("body", Text))
But when I go to the URL I want, the site gives me "500 Internal Server Error Server got itself in trouble "
And Pycharm: Error handling request asyncpg.exceptions._base.InterfaceError: pool is not initialized
Very little has been written on the Internet about asyncpg (sa), so I will be immensely grateful if you can help me fix the problem.
I'll add my own code.
main.py
from aiohttp import web
from demo import create_app
import argparse
import sqlalchemy
import asyncpgsa
async def post_handler(request):
body1 = await request.json()
print(body1)
return web.json_response(data=body1, status=201)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--host", help="IPv4/IPv6 address API server would listen on", default="0.0.0.0")
parser.add_argument('--port', help='TCP port API server would listen on', default=8080, type=int)
args = parser.parse_args()
app = create_app()
web.run_app(app, host=args.host, port=args.port)
if __name__ == '__main__':
main()
app.py
from aiohttp import web
import asyncpgsa
from .routes import setup_routes
async def on_start(app):
app['db'] = asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backendyandex")
async def on_shutdown(app):
app['db'].close()
async def create_app():
app = web.Application(client_max_size=1024 ** 2 * 70)
setup_routes(app)
app.on_startup.append(on_start)
app.on_cleanup.append(on_shutdown)
return app
If you write
app['db'] = await asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backend")
Then an error occurs
unhandled exception during asyncio.run() shutdown
task: <Task finished coro=<_run_app() done, defined at C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web.py:287> exception=ConnectionRefusedError(10061, "Connect call failed ('127.0.0.1', 5432)")>
Traceback (most recent call last):
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web.py", line 508, in run_app
loop.run_until_complete(main_task)
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 587, in run_until_complete
return future.result()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web.py", line 319, in _run_app
await runner.setup()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_runner.py", line 275, in setup
self._server = await self._make_server()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_runner.py", line 375, in _make_server
await self._app.startup()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_app.py", line 416, in startup
await self.on_startup.send(self)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\signals.py", line 34, in send
await receiver(*args, **kwargs) # type: ignore
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\demo\app.py", line 11, in on_start
app['db'] = await asyncpgsa.create_pool(dsn="postgresql://127.0.0.1:5432/backendyandex")
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 407, in _async__init__
await self._initialize()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 435, in _initialize
await first_ch.connect()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 127, in connect
self._con = await self._pool._get_new_connection()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 482, in _get_new_connection
**self._connect_kwargs)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connection.py", line 1997, in connect
max_cacheable_statement_size=max_cacheable_statement_size,
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 677, in _connect
raise last_error
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 668, in _connect
record_class=record_class,
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 634, in _connect_addr
tr, pr = await compat.wait_for(connector, timeout=timeout)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\compat.py", line 103, in wait_for
return await asyncio.wait_for(fut, timeout)
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\tasks.py", line 442, in wait_for
return fut.result()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\connect_utils.py", line 547, in _create_ssl_connection
host, port)
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 962, in create_connection
raise exceptions[0]
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 949, in create_connection
await self.sock_connect(sock, address)
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\selector_events.py", line 473, in sock_connect
return await fut
File "C:\Users\lisgl\AppData\Local\Programs\Python\Python37\lib\asyncio\selector_events.py", line 503, in _sock_connect_cb
raise OSError(err, f'Connect call failed {address}')
ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 5432)
site.py
from aiohttp import web
from sqlalchemy import select
from . import datab
async def post(request):
async with request.app["db"].acquire() as conn:
query = select([datab.post])
result = await conn.fetch(query)
return web.Response(body=str(result))
And here is the error that crashes if you go to the URL I need:
Error handling request
Traceback (most recent call last):
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_protocol.py", line 422, in _handle_request
resp = await self._request_handler(request)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\aiohttp\web_app.py", line 499, in _handle
resp = await handler(request)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\demo\site.py", line 13, in post
async with request.app["db"].acquire() as conn:
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 785, in __aenter__
self.connection = await self.pool._acquire(self.timeout)
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 622, in _acquire
self._check_init()
File "C:\Users\lisgl\Desktop\PycharmProjects\BackendYandex\venv\lib\site-packages\asyncpg\pool.py", line 745, in _check_init
raise exceptions.InterfaceError('pool is not initialized')
asyncpg.exceptions._base.InterfaceError: pool is not initialized
Your dsn is incorrect, so you can't connect to your database.
postgres://user:pass#host:port/database?option=value is the correct format. You forgot the user and the password.
Also asyncpgsa.create_pool() should be awaited, if not. You don't get the error, because you only assign a coroutine to the variable app['db']. So the connection pool is also not created.
Your second error (from site.py) is caused by not initizalising the connection pool.
More about that you can find in the documentation of asyncpg here (because asyncpgsa's connection pool is based on asyncpg's connection pool).
Related
I've been banging my head against my keyboard for a day now, so I'm giving up and asking for help.
I've got a working consumer using confluence kafka, but I need to make it run as a coroutine so I can get things working with FastAPI. I really wanted to try out AIOKafka for this, but for the life of me, I can't get it to work with a self-signed certificate (this is in our dev env).
Here is the working config for my confluence kafka consumer:
conf = {
"bootstrap.servers": "10.142.252.214:9093",
"group.id": "myConsumerID",
"security.protocol": "SASL_SSL",
"sasl.username": kafkaUser,
"sasl.password": kafkaPass,
"sasl.mechanisms": "PLAIN",
"enable.ssl.certificate.verification": "False",
"on_commit": commit_completed,
"heartbeat.interval.ms": "1000",
"socket.connection.setup.timeout.ms": "10000",
"auto.offset.reset": "earliest"
}
Here is the code I'm trying to use for AIOKafka
async def consume():
cert = "../foo/cert/certificate.pem"
key = "../foo/cert/key.pem"
context2 = ssl.create_default_context()
context2.load_cert_chain(certfile=cert, keyfile=key)
context2.check_hostname = False
context2.verify_mode = CERT_NONE
#context2.ssl_cafile="../foo/cert/CARoot.pem"
context2.ssl_certfile = "cert.pem"
context2.ssl_keyfile = "key.pem"
context2.ssl_password = kafkaKey
context2.ssl_keystore_type = "PEM"
consumer = AIOKafkaConsumer(
'TopicA', 'TopicB',
bootstrap_servers="10.142.252.214:9093",
group_id="myConsumerGroup",
sasl_plain_username="kafkaUser",
sasl_plain_password="kafkaPass",
sasl_mechanism="PLAIN",
security_protocol="SASL_SSL",
ssl_context=context2)
await consumer.start()
try:
# Consume messages
async for msg in consumer:
print("consumed: ", msg.topic, msg.partition, msg.offset,
msg.key, msg.value, msg.timestamp)
finally:
# Will leave consumer group; perform autocommit if enabled.
await consumer.stop()
When I try to run this, I just get the most cryptic errors ever and I can't make any sense on where to start trying to figure out what's wrong.
$ python test-main.py
Traceback (most recent call last):
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 375, in _on_read_task_error
read_task.result()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 518, in _read
resp = await reader.readexactly(4)
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/streams.py", line 706, in readexactly
raise exceptions.IncompleteReadError(incomplete, n)
asyncio.exceptions.IncompleteReadError: 0 bytes read on a total of 4 expected bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/myUser/scripts/ansible-hello-world/test-main.py", line 165, in <module>
asyncio.run(consume())
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/Users/myUser/scripts/ansible-hello-world/test-main.py", line 155, in consume
await consumer.start()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/consumer/consumer.py", line 346, in start
await self._client.bootstrap()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/client.py", line 210, in bootstrap
bootstrap_conn = await create_conn(
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 96, in create_conn
await conn.connect()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 234, in connect
await self._do_sasl_handshake()
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/site-packages/aiokafka/conn.py", line 314, in _do_sasl_handshake
auth_bytes = await self._send_sasl_token(
File "/Users/myUser/.pyenv/versions/3.10.5/lib/python3.10/asyncio/tasks.py", line 445, in wait_for
return fut.result()
kafka.errors.KafkaConnectionError: KafkaConnectionError: Connection at 10.142.252.214:9093 closed
Unclosed AIOKafkaConsumer
consumer: <aiokafka.consumer.consumer.AIOKafkaConsumer object at 0x107338670>
import discord
from discord.ext import commands
import random
import praw
cl = commands.Bot(command_prefix = '!')
reddit = praw.Reddit(client_id = "",
client_secret = "",
username = "",
password = "",
user_agent = "")
#cl.event
async def on_ready():
print("Bot is ready, get ready to do wutever u want with it")
#cl.command()
async def meme(ctx, amount=50, subr="memes", filter="top"):
all_submission = []
subreddit = reddit.subreddit("subr")
subs = subreddit.filter(limit = amount)
for submission in subs:
all_submission.append(submission)
random_sub = random.choice(all_submission)
name = random_sub.title
url = random_sub.url
em = discord.embed(title = name)
em.set_image = url
await ctx.send(embed=em)
print("embed sent")
cl.run("")
when I was running this nothing showed up but when I debugged it and !meme in discord it was showing me this traceback error thing
It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
Ignoring exception in command meme:
Traceback (most recent call last):
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 20, in meme
subs = subreddit.filter(limit = amount)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/base.py", line 34, in __getattr__
self._fetch()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 584, in _fetch
data = self._fetch_data()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 581, in _fetch_data
return self._reddit.request("GET", path, params)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/reddit.py", line 885, in request
return self._core.request(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 330, in request
return self._request_with_retries(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 228, in _request_with_retries
response, saved_exception = self._make_request(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 185, in _make_request
response = self._rate_limiter.call(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/rate_limit.py", line 33, in call
kwargs["headers"] = set_header_callback()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 283, in _set_header_callback
self._authorizer.refresh()
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 425, in refresh
self._request_token(
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 158, in _request_token
raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OAuthException: invalid_grant error processing request
This is the error thing I was talking about and it is very weird like telling me to download async praw which I have never had a problem with and pls help it is needed
This doesn't appear to be a discord.py issue, it appears to be related to the praw 0auth flow.
According to the traceback, there's an authentication issue in your praw credentials. Double, triple, and quadruple check your authentication credentials and flow with the workflow and methodology in the docs
I'm trying to connect to a ble device with bleak that uses a passkey.
async def connect(self, address):
print("Connecting to device...")
async with BleakClient(address) as client:
response = await client.connect()
print(response)
i'm using above code. The device displays the passkey to enter and windows displays the add a device message to input the code, but i get a timeout error from asyncio and never recieve the response to python.
Traceback (most recent call last):
File "C:\Users\halmelam\PycharmProjects\read_passcode\main.py", line 137, in <module>
asyncio.run(pair.connect(device.address))
File "C:\Users\halmelam\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\halmelam\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\halmelam\PycharmProjects\read_passcode\main.py", line 95, in connect
response = await client.connect()
File "C:\Users\halmelam\.virtualenvs\read_passcode\lib\site-packages\bleak\backends\winrt\client.py", line 249, in connect
await asyncio.wait_for(event.wait(), timeout=timeout)
File "C:\Users\halmelam\AppData\Local\Programs\Python\Python39\lib\asyncio\tasks.py", line 494, in wait_for
raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
How do I get the response and how can i send the passkey via python?
I'm making a discord.py bot and I want to create a async function to send a message. However, a I want to call this function from a non-async function.
This is the discord client initialization
import requests
import json
from datetime import datetime
import discord
import asyncio
from discord.ext import commands
import firebase_admin
from firebase_admin import credentials, firestore
intents = discord.Intents.all()
client = commands.Bot(command_prefix='&', intents=intents)
This is my send_message function
async def msg(msg,channel):
await channel.send(msg)
This is the non-async function that's calling msg()
def checkStart(doc_snapshot,changes,read_time):
for change in changes:
if change.type.name == 'ADDED' or change.type.name == 'MODIFIED':
anaDoc = change.document.to_dict()
if anaDoc['start'] == True:
asyncio.run(msg('Game started!',main_channel[change.document.reference.parent.parent.id]))
print(change.document.reference.parent.parent.id)
Traceback
Thread-ConsumeBidirectionalStream caught unexpected exception Timeout context manager should be used inside a task and will exit.
Traceback (most recent call last):
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\google\api_core\bidi.py", line 657, in _thread_main
self._on_response(response)
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\google\cloud\firestore_v1\watch.py", line 462, in on_snapshot
meth(proto)
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\google\cloud\firestore_v1\watch.py", line 392, in _on_snapshot_target_change_no_change
self.push(change.read_time, change.resume_token)
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\google\cloud\firestore_v1\watch.py", line 568, in push
self._snapshot_callback(keys, appliedChanges, read_time)
File "c:\Users\Chico\Documents\newCartola\main.py", line 221, in checkStart
asyncio.run(msg('Jogo iniciado!',main_channel[change.document.reference.parent.parent.id]))
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "c:\Users\Chico\Documents\newCartola\main.py", line 213, in msg
await channel.send(msg)
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\abc.py", line 904, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 185, in request
async with self.__session.request(method, url, **kwargs) as r:
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 1012, in __aenter__
self._resp = await self._coro
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client.py", line 426, in _request
with timer:
File "C:\Users\Chico\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\helpers.py", line 579, in __enter__
raise RuntimeError('Timeout context manager should be used '
RuntimeError: Timeout context manager should be used inside a task
I coded a discord bot which will verify a licensekey with a wordpress api.
If a User say: !key xxx-xxx-xxx-xxx
The Bot checks if the license is valid via a key and if its valid it will start insert into a table and will reply to the user.
If the license is not valid (Error 404) it will only respond to the user.
The Code is following:
# bot.py
import os
import aiohttp
from urllib.request import urlopen
import json
import mysql.connector
import discord
import logging
from discord.ext import commands
from discord.utils import get
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, filename="logfile", filemode="a+",
format="%(asctime)-15s %(levelname)-8s %(message)s")
TOKEN ='TOKEN'
GUILD_ID = 'ID'
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
logging.info('------')
logging.info('Logged in as')
logging.info(bot.user.name)
logging.info(bot.user.id)
logging.info('------')
#bot.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send('bla')
def remove_prefix(str, prefix):
return str.lstrip(prefix)
#bot.command(name='g')
async def rename(ctx, name):
await bot.user.edit(username=name)
#bot.command(name='key', pass_context=True)
async def nine_nine(ctx):
if ctx.channel.id == ctx.author.dm_channel.id:
cs = 'cs_***'
ck = 'ck_5***'
username = ctx.message.author.name
discordMemberID = ctx.message.author.id
userMessage = ctx.message.content
key = remove_prefix(userMessage, '!key ')
server = bot.get_guild(id)
role = discord.utils.get(server.roles, id=id)
member = server.get_member(ctx.message.author.id)
user3 = ctx.message.author.id
logging.info( 'DicordUserId %s'%user3)
session = aiohttp.ClientSession()
r = await session.get('https:/mywebsite.com/wp-json/lmfwc/v2/licenses/activate/' + key + '?' + 'consumer_key=' + ck + '&consumer_secret=' + cs )
logging.info(r.status)
if r.status == 200:
r.close()
logging.info("R**")
print("**")
cnx = mysql.connector.connect(host=....)
if cnx.is_connected():
db_Info = cnx.get_server_info()
logging.info('**')
cursor = cnx.cursor(buffered=True)
logging.info("You're connected to database: ")
cursor.execute(***)
if cursor.rowcount == 0:
***
cursor.execute(***)
cnx.commit()
logging.info(**)
cursor.close()
cnx.close())
if member:
await member.add_roles(role)
await ctx.send("**)#
await ctx.send("**")"
await ctx.send('***')
cursor.close()
cnx.close()
logging.info("Closed Connection.")
else:
logging.error("Conection Error")
await ctx.send('Connection Problems. Please Contact an Administrator of the Server!')
elif r.status == 404:
r.close()
print('HTTPError: {}'.format(e.code))
await ctx.send('***')
else:
logging.warning("Private command only")
await ctx.send("Private command only. Please DM me with the '!key' command :)")
bot.run(TOKEN)
Its running perfectly fine but after about 20 minutes there is like a timeout with the connection and the bot WONT respons at first !key command:
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
======= RESTART: C:\Users\Administrator\Desktop\Discord Bot\LicenseBot.py ======
Ignoring exception in command key:
Traceback (most recent call last):
File "C:\Program Files\Python37\lib\site-packages\aiohttp\connector.py", line 936, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa
File "C:\Program Files\Python37\lib\asyncio\base_events.py", line 985, in create_connection
ssl_handshake_timeout=ssl_handshake_timeout)
File "C:\Program Files\Python37\lib\asyncio\base_events.py", line 1013, in _create_connection_transport
await waiter
File "C:\Program Files\Python37\lib\asyncio\selector_events.py", line 814, in _read_ready__data_received
data = self._sock.recv(self.max_size)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Program Files\Python37\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Administrator\Desktop\Discord Bot\LicenseBot.py", line 72, in nine_nine
r = await session.get('URL + key + '?' + 'consumer_key=' + ck + '&consumer_secret=' + cs )
File "C:\Program Files\Python37\lib\site-packages\aiohttp\client.py", line 483, in _request
timeout=real_timeout
File "C:\Program Files\Python37\lib\site-packages\aiohttp\connector.py", line 523, in connect
proto = await self._create_connection(req, traces, timeout)
File "C:\Program Files\Python37\lib\site-packages\aiohttp\connector.py", line 859, in _create_connection
req, traces, timeout)
File "C:\Program Files\Python37\lib\site-packages\aiohttp\connector.py", line 1004, in _create_direct_connection
raise last_exc
File "C:\Program Files\Python37\lib\site-packages\aiohttp\connector.py", line 986, in _create_direct_connection
req=req, client_error=client_error)
File "C:\Program Files\Python37\lib\site-packages\aiohttp\connector.py", line 943, in _wrap_create_connection
raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host URL.com:443 ssl:default [An existing connection was forcibly closed by the remote host]
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Program Files\Python37\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Program Files\Python37\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Program Files\Python37\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientConnectorError: Cannot connect to host URL.com:443 ssl:default [An existing connection was forcibly closed by the remote host]
After this error I can normally fullfill the !key command again and new users will receive a be welcome message.
Already tried library requests instead of urlib
Tried requests with a session and a session.close() too.
Hosting via AWS EC2. Otehr services running perfectly fine.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: URLError: <urlopen error [WinError 10054] An existing connection was forcibly closed by the remote host>
As the error says, the connection was closed by the remote host.
Check your internet connection, and the connection of the server.
Since you are using async python you need to use aiohttp. urlopen is not async and will block the event loop.
If you don't think it's your internet connection then Discord closed the connection. Either bad connectivity or blocking code (time.sleep, requests, sync SQL access, intense computation/image processing, or you're just doing things too fast i.e sending too many messages.