Setup App Database & connect to database

In our example we have the posts that will have to be added to a table in our Database

  • The posts table will have to have the following columns:

  • Also added 2 mock posts to the database

To connect Python to our Database

To connect to the database we need to set up the following code

import psycopg

try:
    conn = psycopg.connect("dbname=fastapi user=postgres password=Password1")
    cursor = conn.cursor()
    print("Database connection successful")

except Exception as error:
    print("Connecting to database failed")
    print("Error: ", error)
  • This should either connect or return the error that was raised

If there is any python code that can fail, it is best to use the try/except block in order to not break the code

  • The main problem with the above code is that if the database is not reachable, there is no point in having our server up

  • One solution would be to add the whole thing into a while loop

while True:

    try:
        conn = psycopg.connect("dbname=fastapi user=postgres password=Password1")
        cursor = conn.cursor()
        print("Database connection successful")
        break

    except Exception as error:
        print("Connecting to database failed")
        print("Error: ", error)
        time.sleep(2)
  • We will break out of the loop if the connection is successful

  • If the connection does not work, it will wait 2 seconds and restart the loop

Hint: We have hardcoded our database credentials in our code

This is really bad practice, but as we are learning, this is fine for now.

Last updated