From the course: Advanced Python: Practical Database Examples

Unlock the full course today

Join today to access over 24,800 courses taught by industry experts.

Connect a database to a Python Flask project

Connect a database to a Python Flask project - Python Tutorial

From the course: Advanced Python: Practical Database Examples

Connect a database to a Python Flask project

- [Instructor] We can connect our Flask application to our database using SQLAlchemy. Within our virtual environment, we can install a special extension that allows us to use SQLAlchemy in our Flask code. Let's activate the environment. We'll install Flask-SQLAlchemy. Then we'll add it as an import to our app.py file. Within our app, there's a few things we need to configure. First, we'll configure the SQLALCHEMY_DATABASE_URI. This URI is like a connection string that allows us to connect to our Postgres database. It's what we fed in to the create engine function before when we used SQLAlchemy previously. we'll also add a SECRET_KEY. This will allow us to securely use SQLAlchemy sessions in our Flask application. Now the value for this key is something we set and we can generate one quickly using a Python Three shell. Let's open one up. We'll import the os module and use os.urandom24 to generate a random value. Let's…

Contents