Wednesday, April 20, 2022

[FIXED] How do I run postgres on heroku for my discord.py bot?

Issue

So I am using heroku (for now) to host my discord.py bot. Recently I started using postgres as a database, this is the connection code:

I am using this code for connection:

import asyncpg

async def create_db_pool():
    client.pg_con = await asyncpg.create_pool(DATABASE_URL) #db url goes here

client.loop.run_until_complete(create_db_pool())
client.run(TOKEN)

The code works absolutely fine when I run it locally, but shows connection error while I use heroku for the same.

I also added 'Heroku-postgres' as an add-on but it still doesn't work? Please share a solution for the same.

Thanks in advance :)


Solution

client.pg_con = await asyncpg.create_pool(DATABASE_URL) #db url goes here

When you add a Postgres DB addon Heroku will add an environment variable to your app. The value of it containing a database url. You need to retrieve that. Something like:

import os
DATABASE_URL = os.environ.get("ENV_VAR_NAME_HERE", None)

@ŁukaszKwieciński I don't want to save the data in the heroku database, I am using the default server of postgres i.e. pgAdmin4 to save data.

Your Heroku app does not come with a database. Anything that is saved on the Heroku app is wiped, see here. There is no "default server of postgres" on your Heroku app. That's why you are adding a (third party) add-on to your app that acts as the database: the postgres add-on.



Answered By - Tin Nguyen
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.