How to connect Flask to a database with Flask-SQLAlchemy

Flask is a framework that is widely used to create APIs in Python. Flask is a simple yet powerful web framework that is designed to help us get started quickly and easily, with the ability to scale up to complex applications.

Flask is called “micro” because it was built with a simple but extensible core.

SQLAlchemy is an Object Relational Mapper (ORM).

Flask-SQLAlchemy is fun to use, incredibly easy for basic applications, and readily extends for larger applications.

For the complete guide, check out the API documentation on the SQLAlchemy class.

Install the dependencies

First, run the commands below to install the required dependencies:

Error: Code Block Widget Crashed, Please Contact Support

Create a file and name it app.py. Let’s get to the code.

app.py

Error: Code Block Widget Crashed, Please Contact Support

Create a folder and name it “templates.”

Inside the “templates” folder, create a file and name it home.html, then add the below code.

home.html

Error: Code Block Widget Crashed, Please Contact Support

Inside the “templates” folder, create a file and name it add.html then add the code below.

add.html

Error: Code Block Widget Crashed, Please Contact Support

Inside the “templates” folder, create a folder and name it “extra,” then create a file named _flash.html and add the code below.

_flash.html

Error: Code Block Widget Crashed, Please Contact Support

In your terminal, run this code to create a database:

Error: Code Block Widget Crashed, Please Contact Support

Run:

Error: Code Block Widget Crashed, Please Contact Support

Your app should be up and running locally at http://127.0.0.1:5000/.

Conclusion

Flask uses an ORM (SQLAlchemy) that helps to easily map out a database. This app shows us how to use Flask-Sqlalchemy to easily map out the model.

Here is a link to the GitHub repo.

Free Resources