Setup App Database & connect to database
Last updated
Last updated
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
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
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
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.