- Flask Framework Cookbook(Second Edition)
- Shalabh Aggarwal
- 248字
- 2021-06-24 13:58:04
How to do it...
Let's create a small application in this recipe to understand the basic database connection with Flask. We will build over this application in the next few recipes. Here, we will just see how to create a db instance and some basic database commands. The file's structure would look like the following:
flask_catalog/ - run.py
my_app/
- __init__.py
First, we start with flask_app/run.py. This is the usual run file that we have read about previously in this book:
from my_app import app
app.run(debug=True)
Then, we configure our application configuration file, that is, flask_app/my_app/__init__.py:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app)
Here, we configure our application to point SQLALCHEMY_DATABASE_URI to a specific location. Then, we create an object of SQLAlchemy with the name db. As the name suggests, this is the object that will handle all our ORM-related activities. As mentioned earlier, this object has a class named Model, which provides the base for creating models in Flask. Any class can just subclass or inherit the Model class to create models, which will act as database tables.
Now, if we open the http://127.0.0.1:5000 URL in a browser, we will see nothing. This is because we have just configured the database connection for this application and there is nothing to be seen on the browser. However, you can always head to the location specified in app.config for the database location to see the newly created test.db file.