Flask Framework Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

Getting ready

Flask-SQLAlchemy is the extension that provides the SQLAlchemy interface for Flask.

This extension can simply be installed by using pip as follows:

    $ pip3 install flask-sqlalchemy

The first thing to keep in mind with Flask-SQLAlchemy is the application configuration parameter that tells SQLAlchemy about the location of the database to be used:

app.config['SQLALCHEMY_DATABASE_URI'] = os.environ('DATABASE_URI') 

SQLALCHEMY_DATABASE_URI is a combination of the database protocol, any authentication needed, and also the name of the database. In the case of SQLite, this would look something like the following:

sqlite:////tmp/test.db 

In the case of PostgreSQL, it would look like the following:

postgresql://yourusername:yourpassword@localhost/yournewdb. 

This extension then provides a class named Model that helps defining models for our application. Read more about database URLs at https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls.

For all database systems other than SQLite, separate libraries are needed. For example, for using PostgreSQL, you need psycopg2.