English Blog Address: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database
Chinese translation Address: http://www.pythondoc.com/flask-mega-tutorial/database.html
Open source China Community: www.oschina.net/translate/the-flask-mega-tutorial-part-iv-database
I. Databases in the FLASK
Tutorial: You will use the Flask-sqlalchemy extension to manage the data for our applications. This extension encapsulates the SQLAlchemy project, which is an object-relational mapper or ORM.
Most database tutorials involve the creation and use of a database, but do not adequately address the problem of updating the database as your application expands. Normally, every time you need to update, you end up having to delete the old database and create a new database, and lose all the data. If the data cannot be easily recreated, you may be forced to write your own export and import scripts.
We will use Sqlalchemy-migrate to track updates to the database. It just takes a bit more work to start building a database, which is a small price to worry about, and no more worrying about manual data migrations.
Second, the configuration
The database used in the tutorial is the SQLite database. The SQLite database is the most convenient choice for small applications, and each database is stored in a single file.
There are many new configuration items that need to be added to the configuration file (file config.py):
Import= Os.path.abspath (Os.path.dirname (__file__'sqlite:/// ' ' app.db ' 'db_repository')
Sqlalchemy_database_uri is required for flask-sqlalchemy expansion. This is the path to our database file.
Sqlalchemy_migrate_repo is a folder, we will store the Sqlalchemy-migrate data file here.
When we initialize the application, we also have to initialize the database. To modify the initialization file (file app/__init__.py):
from Import Flask from Import = Flask (__name__) app.config.from_object ('config' ) = SQLAlchemy (APP)fromimport views, models
There are two changes here. One is to create a db object, which is our database and then import a new module called models. Next we will write the models.
Third, the database model
I assume that you can learn a database.
User tables such as:
A total of 4 fields are in the table.
ID: Primary Key
Nickname : string, and specifies the maximum length so that the database can optimize for space consumption.
Email : string, and specifies the maximum length so that the database can optimize space consumption.
role : Integer that indicates which user is the administrator and which is not.
Convert it to code (file app/models.py):
fromAppImportDbrole_user=0role_admin= 1classUser (db. Model): ID= db. Column (db. Integer, Primary_key =True) Nickname= db. Column (db. String (+), index = True, unique =True) Email= db. Column (db. String (+), index = True, unique =True) Role= db. Column (db. Smallinteger, default =role_user)def __repr__(self):return '<user%r>'% (Self.nickname)
The user class defines the few fields we have just created as class variables. The field uses DB. The column class creates an instance, the type of the field as a parameter, and some other optional parameters are provided. For example, parameters that identify field uniqueness and indexes.
The __repr__ method tells Python how to print a class object so that we can use it for debugging purposes.
Iv. Creating a Database
Tutorial: Both the configuration and the model are in place, and it is time to prepare the database files for creation. The Sqlalchemy-migrate package comes with command lines and APIs that create databases in a way that allows for easy upgrades in the future. I found the command exercise rather awkward, so we wrote some Python scripts to invoke the migrated APIs ourselves.
Create a database script (file db_create.py):
#!flask/bin/python fromMigrate.versioningImportAPI fromConfigImportSqlalchemy_database_uri fromConfigImportSqlalchemy_migrate_repo fromAppImportDBImportOs.pathdb.create_all ()if notos.path.exists (Sqlalchemy_migrate_repo): Api.create (Sqlalchemy_migrate_repo,'Database Repository') Api.version_control (Sqlalchemy_database_uri, Sqlalchemy_migrate_repo)Else: Api.version_control (Sqlalchemy_database_uri, Sqlalchemy_migrate_repo, Api.version (SQLALCHEMY_MIGRATE_REPO))
This file is placed under the root directory.
Note that this script is completely generic, and all application path names are read from the configuration file. When you use your own project, you can copy the script to your app's directory to use it normally.
To create a database:
chmod a+x db_create.py
./db_create.py
After running this command, there is a new App.db file in the folder, which is an empty SQLite database that supports migration. A db_repository directory with several files is also generated, which is where Sqlalchemy-migrate stores the database files, and note that if the database already exists it will no longer be regenerated. This will help us to automatically create the existing database once it is lost.
Three databases of flask learning