Error connecting to a DB in Python

Asked

Viewed 20 times

0

I’m having trouble connecting to a database by a script I developed in Python.

It’s probably some logic error involving the variables I couldn’t decipher and I wish someone could help me.

This is a piece of code...

def create(self, params, name_table):
    credentials = {
        "host": os.getenv("HOST"),
        "db_name": os.getenv("DB_NAME"),
        "user": os.getenv("USER"),
        "password": os.getenv("PASSWORD")
    }

    try:
        conn = psycopg2.connect(f"host={credentials['host']} "
                                f"dbname={credentials['db_name']} "
                                f"user={credentials['user']} "
                                f"password={credentials['password']}")

The environment variables (HOST, DB_NAME, USER, PASSWORD) are defined in my OS.

  • And what’s the problem? If you access directly, credentials work?

  • The problem is that another script calls a class of this to get popular the database with data I pull from an api, and when I run this script from the api it doesn’t end because I can’t connect with the database, I did some prints to see where I was giving trouble, and came from that part of the code, because I could not print the variables, they were not defined.

  • Has confirmed whether credentials is populated with the correct information?

  • What do you mean? Give one print(credentials['host']) for example?

  • Can be, or use any debugging tool

  • So, exactly, when I pull this information from credentials returns me as undefined/Keyerror. And that’s where I can’t see where I’m wrong.

  • Edit your post by placing the exact error that appears on the screen. Enjoy and rotate in your shell echo $VARIAVEL (Linux) or echo %VARIAVEL% (Windows) and update the post with the result. In time: VARIABLE must be replaced by their name (one at a time) HOST, DB_NAME, USER, PASSWORD

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.