Create a file called cofing.py in your project
# -*- coding: utf-8 -*-
import them
#Set the debug mode
DEBUG=True
#set session
SECRET_KEY=os.urandom(24)
#Set database related information
DIALECT='mysql'
DRIVER='mysqldb'
USERNAME='root'
PASSWORD='chenzhening0623'
HOST='127.0.0.1'
PORT='3306'
DATABASE='zlktqa_demo2'
SQLALCHEMY_DATABASE_URI="{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(
DIALECT,DRIVER,USERNAME,PASSWORD,HOST,PORT,DATABASE
)
SQLALCHEMY_TRACK_MODIFICATIONS=False
then create the database
create database database name charset utf8;
Import the cofing.py file in the main app file as follows
# -*- coding: utf-8 -*-
from flask import Flask
import cofing
app = Flask(__name__)
app.config.from_object(cofing)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
Create a file named ests.py to store db related data content
from flask_sqlalchemy import SQLAlchemy
db=SQLAlchemy()
Create a file called models models.py
# used to create the model
# -*- coding: utf-8 -*-
from ests import db
#create model
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
telphone = db.Column(db.String(11), nullable=False)
username = db.Column(db.String(50), nullable=False)
password = db.Column(db.String(100), nullable=False)
Create a file named manage.py (map the models in models.py to this file)
# -*- coding: utf-8 -*-
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
from untitled import app
from ests import db
from models import User
manager=Manager(app)
Migrate=Migrate(app,db) #Binding
manager.add_command('db',MigrateCommand) #Migrate
if __name__=="__main__":
manager.run()
Use the following command in cmd
python manage.py db init
A folder named migrations will be generated in the project (for initialization files)
python manage.py db migrate #Migrate
python manage.py db upgrade #Real mapping to the database
Details of decorators
# -*- coding: utf-8 -*-
from functools import wraps
def my_fun(func):
@wraps(func)
def wrap(*args,**kw):
return func(*args,**kw)
return wrap
@my_fun
def fun1():
pass
g object
g.key=value
hook function
before_request
Original address: http://www.cnblogs.com/mhxy13867806343/p/7574034.html