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
- We will need a Postgres Driver 
- There are multiple libraries that are able to do that but we ill use the Psycopg Library 
- To set this up for Psycopg3 use this documentation 
- Basic module usage will help you set up the Database connection 
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 
- 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 - whileloop
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