Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection was closed in the middle of operation when accesing database using Python

I set up a postgresql server using Heroku in addition to my python bot which also runs on heroku but the bot fails to connect to the database

I secured that the password username etc. where correct.

This is the method used to connect:

async def create_db_pool():
    bot.pg_con = await asyncpg.create_pool(database="dbname", 
    user="username", 
    password="dbpw")

And this is how i run it:

bot.loop.run_until_complete(create_db_pool())

It is expected to access the database and write and read data instead i receive following error:

asyncpg.exceptions.ConnectionDoesNotExistError: connection was closed in the middle of operation
Task was destroyed but it is pending!
task: <Task pending coro=<chng_pr() running at I:/Python/HardCoreDisBot/Commands.py:38> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000002571E9B1978>()]>>
like image 602
Akira Avatar asked Jul 07 '19 13:07

Akira


People also ask

Do we need to close DB connection in python?

Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [ conn. close() ], but you can explicitly close the connection if you wish. and similarly for cursors (my emphasis):

How do you close a database in Python?

To disconnect Database connection, use close() method. If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB.


1 Answers

So I looked at your problem and found a thread that had a similar problem and they seemed to find a work around by putting max_inactive_connection_lifetime in their code like this. this is the link to the thread.

async def create_db_pool():
    bot.pg_con = await asyncpg.create_pool(database="dbname", 
    user="username", 
    password="dbpw",
    max_inactive_connection_lifetime=3)
like image 196
Oliver Hnat Avatar answered Oct 25 '22 17:10

Oliver Hnat