Install SQLAlchemy
pip3 install sqlalchemy
Flask need to use the flask-sqlalchemy support package
pip3 install flask-sqlalchemy
Create a database
create database flask default charset utf8 collate utf8_general_ci;
Configure connect to the database
app.config [ 'SQLALCHEMY_DATABASE_URI'] = "mysql: // username: password @ database server address: port number / name of the database."
app.config['SQLALCHEMY_DATABASE_URI']="mysql://root:123456@localhost:3306/flask"
Create an instance of SQLAlchemy
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(app)
By operating in the program database db
Definition Model:
class MODELNAME(db.Model): __tablename__ = " the TABLENAME " # can not write, the default lowercase class name table name COLUMN_NAME = db.Column (db.TYPE, the OPTIONS) # attribute name, column name correspondence table
TYPE type:
类型名 python类型
Integer int
SmallInteger int
BigInteger int
Float float
String str
Text str
Boolean bool
Date datetime.date
Time datetime.time
DateTime datetime.datetime
OPTIONS:
Option Name Description
autoincrement if set to True indicates that the column you want to customize the growth
primary_key if set to True indicates that the column primary key
unique If True represents a unique value for the column
index if set to True indicates that the value added to the index of the column is
nullable If True to indicate that the column allows null
default specify a default value for the column
Migration: generally do not have these two
will create the entity classes to database: db.create_all ()
All data tables Delete all: db.drop_all ()
migrate
Start with a project manager:
from flask_script import Manager
manager = Manager(app)
manager.run()
After the model has been defined migration model is mapped back to the database:
from flask_migrate import Migrate,MigrateCommand
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)
Command line:
Initialize the database, perform only once
python3 xxx.py db init
Generating an intermediate file
python3 xxx.py db migrate
Map back to database
python3 xxx.py db upgrade