一。自定义命令。
在flask中也可以将应用改写成可以使用命令的形式,需要用到模块:
pip install flask-script
使用关键字manage使得其能使用终端启动:
from flask import Flask from flask_script import Manager app = Flask(__name__) manager=Manager(app) @app.route("/") def index(): return "ok"
在启动的时候就可以使用以下命令:
python 文件名.py runserver
使用命令运行函数:
@manager.command def custom(arg,a): print(arg,a)
运行命令:
python t1.py custom 1 2
当然,可以自定义命令:
@manager.option('-n','--name',dest='name') @manager.option('-u','--url',dest='url') def cmd(name,url): print(name,url)
函数中,每有一个参数,就需要有一个option,第一个参数是别名,第二个参数是详细名,两者都可以用做运行,dest代表绑定的关键字参数。
运行命令
python t1.py cmd -n lzx -u 111
python t1.py cmd --name lzx --url 111
二。多app应用
需要导入模块:
from werkzeug.wsgi import DispatcherMiddleware from werkzeug.serving import run_simple from flask import Flask app1 = Flask('app01') app2 = Flask('app02')
当这个模块使用时:
@app1.route('/index') def index(): return "app01" @app2.route('/index') def index2(): return "app2" dm = DispatcherMiddleware(app1, { '/sec12': app2, }) if __name__ == "__main__": run_simple('localhost', 5000, dm)
执行方法时run,当页面访问时,需要将dm中的前缀加上才能访问。
三。wtform
导入模块
pip install wtforms
使用
from flask import Flask, render_template, request, redirect from wtforms import Form from wtforms.fields import simple from wtforms import validators from wtforms import widgets app = Flask(__name__) app.debug = True class LoginForm(Form): # 字段(内部包含正则表达式) name = simple.StringField( label='用户名', validators=[ validators.DataRequired(message='用户名不能为空.'), validators.Length(min=2, max=6, message='用户名长度必须大于%(min)d且小于%(max)d') ], widget=widgets.TextInput(), # 页面上显示的插件 render_kw={'class': 'form-control'} ) # 字段(内部包含正则表达式) pwd = simple.PasswordField( label='密码', validators=[ validators.DataRequired(message='密码不能为空.'), validators.Length(min=8, message='密码长度必须大于%(min)d'), # validators.Regexp(regex="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}", # message='密码至少8个字符,至少1个大写字母,1个小写字母,1个数字和1个特殊字符') ], widget=widgets.PasswordInput(), render_kw={'class': 'form-control'} ) @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': form = LoginForm() return render_template('login.html', form=form) else: form = LoginForm(formdata=request.form) if form.validate(): print('用户提交数据通过格式验证,提交的值为:', form.data) else: print(form.errors) return render_template('login.html', form=form) if __name__ == '__main__': app.run()
label代表的是字段前缀,vaildate代表的是校验,widget,代表的是input类型,render_kw,代表的是定义的类或元素。
template
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>登录</h1> <form method="post"> <p>{{form.name.label}} {{form.name}} {{form.name.errors[0] }}</p> <p>{{form.pwd.label}} {{form.pwd}} {{form.pwd.errors[0] }}</p> <input type="submit" value="提交"> </form> </body> </html>
所有的form类型:
from flask import Flask, render_template, request, redirect
from wtforms import Form
from wtforms.fields import core
from wtforms.fields import html5
from wtforms.fields import simple
from wtforms import validators
from wtforms import widgets
app = Flask(__name__, template_folder='templates')
app.debug = True
class RegisterForm(Form):
def validate_pwd_confirm(self, field):
# 钩子函数
"""
自定义pwd_confirm字段规则,例:与pwd字段是否一致
:param field:
:return:
"""
# 最开始初始化时,self.data中已经有所有的值
print(field.data)
if field.data !="sb":
#raise validators.ValidationError("sb") # 继续后续验证
raise validators.StopValidation("SB") # 不再继续后续验证
# if field.data != self.data['pwd']:
# raise validators.ValidationError("密码不一致") # 继续后续验证
#raise validators.StopValidation("密码不一致") # 不再继续后续验证
name = simple.StringField(
label='用户名',
validators=[
validators.DataRequired()
],
widget=widgets.TextInput(),
render_kw={'class': 'form-control'},
default='tank'
)
pwd = simple.PasswordField(
label='密码',
validators=[
validators.DataRequired(message='密码不能为空.')
],
widget=widgets.PasswordInput(),
render_kw={'class': 'form-control'}
)
pwd_confirm = simple.PasswordField(
label='重复密码',
validators=[
validate_pwd_confirm,
validators.DataRequired(message='重复密码不能为空.'),
#validators.EqualTo('pwd', message="两次密码输入不一致")
],# 判断重复密码
widget=widgets.PasswordInput(),
render_kw={'class': 'form-control'}
)
email = html5.EmailField(
label='邮箱',
validators=[
validators.DataRequired(message='邮箱不能为空.'),
validators.Email(message='邮箱格式错误')
],
widget=widgets.TextInput(input_type='email'),
render_kw={'class': 'form-control'}
)
gender = core.RadioField(
label='性别',
choices=(
(1, '男'),
(2, '女'),
),
coerce=int # “1” “2” # 将选择的数据类型变为数字类型
)
city = core.SelectField(
label='城市',
choices=(
('bj', '北京'),
('sh', '上海'),
)
)
hobby = core.SelectMultipleField(
label='爱好',
choices=(
(1, '篮球'),
(2, '足球'),
),
coerce=int
)
favor = core.SelectMultipleField(
label='喜好',
choices=(
(1, '篮球'),
(2, '足球'),
),
widget=widgets.ListWidget(prefix_label=False),
option_widget=widgets.CheckboxInput(),
coerce=int,
default=[1, 2]
)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.favor.choices = ((1, '篮球'), (2, '足球'), (3, '羽毛球'))
self.favor.data=[1,] # 设置默认值
# 可以修改字段中的元素
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
form = RegisterForm(data={'gender': 2,'hobby':[1,]}) # initial
# 设置默认值
return render_template('register.html', form=form)
else:
form = RegisterForm(formdata=request.form)
if form.validate():
print('用户提交数据通过格式验证,提交的值为:', form.data)
else:
print(form.errors)
return render_template('register.html', form=form)
if __name__ == '__main__':
app.run()
四。SQLAlchemy
这是一个基于python的orm框架,可以实现sql语句的操作。其也是由pymysql等数据中间键来操作的。
安装:
pip3 install sqlalchemy
(不常用)使用原生sql语句操作数据库。
import time import threading import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.engine.base import Engine engine = create_engine( "mysql+pymysql://root:123456@127.0.0.1:3306/test?charset=utf8", max_overflow=0, # 超过连接池大小外最多创建的连接 pool_size=5, # 连接池大小 pool_timeout=30, # 池中没有线程最多等待的时间,否则报错 pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置) ) def task(arg): conn = engine.raw_connection() cursor = conn.cursor() cursor.execute( "select * from app01_book" ) result = cursor.fetchall() print(result) cursor.close() conn.close() for i in range(20): t = threading.Thread(target=task, args=(i,)) t.start()
orm使用
orm需要导入各种数据进行配置
import datetime from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index Base = declarative_base() class Users(Base): __tablename__ = 'users' # 数据库表名称 id = Column(Integer, primary_key=True) # id 主键 name = Column(String(32), index=True, nullable=False) # name列,索引,不可为空 # email = Column(String(32), unique=True) #datetime.datetime.now不能加括号,加了括号,以后永远是当前时间 # ctime = Column(DateTime, default=datetime.datetime.now) # extra = Column(Text, nullable=True) __table_args__ = ( # UniqueConstraint('id', 'name', name='uix_id_name'), #联合唯一 # Index('ix_id_name', 'name', 'email'), #索引 ) def init_db(): """ 根据类创建数据库表 :return: """ engine = create_engine( "mysql+pymysql://root:123456@127.0.0.1:3306/aaa?charset=utf8", max_overflow=0, # 超过连接池大小外最多创建的连接 pool_size=5, # 连接池大小 pool_timeout=30, # 池中没有线程最多等待的时间,否则报错 pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置) ) Base.metadata.create_all(engine) def drop_db(): """ 根据类删除数据库表 :return: """ engine = create_engine( "mysql+pymysql://root:123456@127.0.0.1:3306/aaa?charset=utf8", max_overflow=0, # 超过连接池大小外最多创建的连接 pool_size=5, # 连接池大小 pool_timeout=30, # 池中没有线程最多等待的时间,否则报错 pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置) ) Base.metadata.drop_all(engine) if __name__ == '__main__': # drop_db() init_db()
所有的类表需要继承自base,否则不在管理之内。增删表都只能管理他的子类。不能增加字段,也不能删除字段,但是可以将数据库字段和orm字段设置成一样的,也可以用。
3.app导入:
from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from models import Users #"mysql+pymysql://root@127.0.0.1:3306/aaa" engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/aaa", max_overflow=0, pool_size=5) Connection = sessionmaker(bind=engine) # 每次执行数据库操作时,都需要创建一个Connection con = Connection() # ############# 执行ORM操作 ############# obj1 = Users(name="lqz") con.add(obj1) # 提交事务 con.commit() # 关闭session,其实是将连接放回连接池 con.close()
五。scoped_session
scoped_session可以使得线程安全,保证所有线程之间不会互相操作。
from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session from models import Users engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/flask", max_overflow=0, pool_size=5) Session = sessionmaker(bind=engine) """ # 线程安全,基于本地线程实现每个线程用同一个session # 特殊的:scoped_session中有原来方法的Session中的一下方法: public_methods = ( '__contains__', '__iter__', 'add', 'add_all', 'begin', 'begin_nested', 'close', 'commit', 'connection', 'delete', 'execute', 'expire', 'expire_all', 'expunge', 'expunge_all', 'flush', 'get_bind', 'is_modified', 'bulk_save_objects', 'bulk_insert_mappings', 'bulk_update_mappings', 'merge', 'query', 'refresh', 'rollback', 'scalar' ) """ #scoped_session类并没有继承Session,但是却又它的所有方法 session = scoped_session(Session) # ############# 执行ORM操作 ############# obj1 = Users(name="jason") session.add(obj1) # 提交事务 session.commit() # 关闭session session.close()
六,基本增删改操作:
使用方法session.add可以添加表对象添加数据。
使用add_all可以添加列表套对象的方式添加数据。
删除使用session.query(User).filter(User.id>2).delete()
首先查出改字段对象,执行delete方法删除那些对象。
修改表数据‘
1。session.query(User).filter(User.id>2).updata({'age':30}),字典代表的是字段和数据。
2.session.query(Users).filter(Users.id == 3).update({Users.name: Users.name + "sb"}, synchronize_session=False)
类似于f查询,将其字段进行拼接,但是synchronize_session必须设置成false。(仅对于字符串)
3.session.query(Users).filter(Users.id == 7).update({"age": Users.age + 16}, synchronize_session="evaluate")
如果操作的数据,需要设置synchronize_session="evaluate"
如果session.query(Users)不加all,则打印的就是原生sql语句
import time import threading from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine from sqlalchemy.sql import text from models import Users engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/flask", max_overflow=0, pool_size=5) Session = sessionmaker(bind=engine) session = Session() # ################ 添加 ################ # obj1 = Users(name="wupeiqi",age=40) # session.add(obj1) # # session.add_all([ # Users(name="tank"), # Users(name="jason"), # #Hosts(name="c1.com"), # ]) # session.commit() # ################ 删除 ################ # session.query(Users).filter(Users.id == 5).delete() # session.commit() # ################ 修改 ################ #传字典 #session.query(Users).filter(Users.id ==4 ).update({"age" : 30,}) #类似于django的F查询 #session.query(Users).filter(Users.id == 3).update({Users.name: Users.name + "sb"}, synchronize_session=False) #session.query(Users).filter(Users.id == 7).update({"age": Users.age + 16}, synchronize_session="evaluate") # session.commit() # ################ 查询 ################ # r1 = session.query(Users).all() # print(r1),query后面可以增加多个表 #只取age列,把name重命名为xx,label代表的是起别名 # r2 = session.query(Users.name.label('sb'), Users.age).filter(Users.id==8).first() # print(r2.sb) #filter传的是表达式,filter_by传的是参数 # r3 = session.query(Users).filter(Users.name == "jason").all() # print(r3) # r4 = session.query(Users).filter_by(name='jason').all() # print(r4) # r5 = session.query(Users).filter_by(name='lqz').first(),.first取出其中的第一条。 #:value 和:name 相当于占位符,用params传参数 #r6 = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name='fred').order_by(Users.id).all() #自定义查询sql #r7 = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name='ed').all() #增,删,改都要commit() session.close()
如果需要对其打印输出的字段可以设置:
def __repr__(self): return self.name
七。查询
import time import threading from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine from sqlalchemy.sql import text from models import Users engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/flask", max_overflow=0, pool_size=5) Session = sessionmaker(bind=engine) session = Session() # 条件 # ret = session.query(Users).filter_by(name='lqz').all() #表达式,and条件连接,逗号代表且操作 # ret = session.query(Users).filter(Users.id > 7, Users.name == 'jason').all() # print(ret)between代表的是在3-5之间 # ret = session.query(Users).filter(Users.id.between(3, 5), Users.name == 'jason').all() # print(ret) #注意下划线,in代表的是在这个区间之间 # ret = session.query(Users).filter(Users.id.in_([1,3,4])).all() # print(ret) #~非,代表除。。外 # ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all() # print(ret) # #二次筛选 # ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='jason'))).all() # print(ret) from sqlalchemy import and_, or_ #or_包裹的都是or条件,and_包裹的都是and条件 #ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all() # ret = session.query(Users).filter(or_(Users.id >6 , Users.name == 'jason')).all() # print(ret) # ret = session.query(Users).filter( # or_( # Users.id < 2, # and_(Users.name == 'eric', Users.id > 3), # Users.age != "" # )).all() # 通配符like,以e开头,不以e开头,有_代表的是占位符,可以配合~ # ret = session.query(Users).filter(Users.name.like('_q%')).all() # print(ret) # ret = session.query(Users).filter(~Users.name.like('j%')).all() # print(ret) # 限制,用于分页,区间 # ret = session.query(Users)[1:9] # print(ret) # # # 排序,根据name降序排列(从大到小)desc代表降序 # ret = session.query(Users).order_by(Users.name.desc()) # print(ret) # #第一个条件重复后,再按第二个条件升序排,使用,隔开
# ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()) # print(ret) # # # 分组 from sqlalchemy.sql import func # func需要风阻之后的输出 # ret = session.query(Users).group_by(Users.name).all() # print(ret) # #分组之后取最大id,id之和,最小id # ret = session.query( # func.max(Users.id), # func.sum(Users.id), # func.min(Users.id)).group_by(Users.name).all() # print(ret) # #haviing筛选 # ret = session.query( # # func.max(Users.id), # # func.sum(Users.id), # # func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2) # # print(ret)
八。一对多查询。
一对多建表:
class Hobby(Base): __tablename__ = 'hobby' id = Column(Integer, primary_key=True) caption = Column(String(50), default='篮球') class Person(Base): __tablename__ = 'person' nid = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=True) # hobby指的是tablename而不是类名, hobby_id = Column(Integer, ForeignKey("hobby.id"))# 代表的是表明 # 跟数据库无关,不会新增字段,只用于快速链表操作 # 类名,backref用于反向查询,uselist=False hobby = relationship('Hobby', backref='pers') # 关联字段,不会生成字段,backref代表的是反向查询的时候的字段。 def __repr__(self): return self.name
一对多:
import time import threading from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine from sqlalchemy.sql import text from sqlalchemy.engine.result import ResultProxy from models import Users, Hobby, Person engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/flask?charset=utf8", max_overflow=0, pool_size=5) Session = sessionmaker(bind=engine) session = Session() # 添加 # 1.不关联表的添加方法 # session.add_all([ # Hobby(caption='乒乓球'), # Hobby(caption='羽毛球'), # Person(name='张三', hobby_id=1), # Person(name='李四', hobby_id=2), # ]) # 正向将hobby对象插入,可以自动关联 # person = Person(name='张九', hobby=Hobby(caption='姑娘')) # session.add(person) #添加二,反向查询 # hb = Hobby(caption='人妖') # hb.pers = [Person(name='文飞'), Person(name='博雅')] # session.add(hb) # # session.commit() """ # 使用relationship正向查询 """ # v = session.query(Person).first() # print(v.name) # print(v.hobby.caption) """ # 使用relationship反向查询 """ # v = session.query(Hobby).first() # print(v.caption) # print(v.pers) #方式一,自己链表,isouter代表的是外联查询 # person_list=session.query(Person).join(Hobby,isouter=True) # print(person_list) # person_list=session.query(Person,Hobby).join(Hobby,isouter=True) # print(person_list) # for row in person_list: # # print(row.name,row.caption) # print(row[0].name,row[1].caption) # # #方式二:通过relationship # person_list=session.query(Person).all() for row in person_list: print(row.name,row.hobby.caption) # #查询喜欢姑娘的所有人 # obj=session.query(Hobby).filter(Hobby.id==1).first() # persons=obj.pers # print(persons) # session.close() #如果没有建立外键 # ret = session.query(Person).join(Hobby,Person.nid==Hobby.id, isouter=True) # print(ret)
九。多对多
多对多建表
class Boy2Girl(Base): __tablename__ = 'boy2girl' id = Column(Integer, primary_key=True, autoincrement=True) girl_id = Column(Integer, ForeignKey('girl.id')) boy_id = Column(Integer, ForeignKey('boy.id')) class Girl(Base): __tablename__ = 'girl' id = Column(Integer, primary_key=True) name = Column(String(64), unique=True, nullable=False) class Boy(Base): __tablename__ = 'boy' id = Column(Integer, primary_key=True, autoincrement=True) hostname = Column(String(64), unique=True, nullable=False) # 与生成表结构无关,仅用于查询方便,放在哪个单表中都可以 girl = relationship('Girl', secondary='boy2girl', backref='boys')
多对多
import time import threading from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine from sqlalchemy.sql import text from sqlalchemy.engine.result import ResultProxy from models import Users, Hobby, Person, Girl, Boy2Girl, Boy engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/flask?charset=utf8", max_overflow=0, pool_size=5) Session = sessionmaker(bind=engine) session = Session() # 添加 # session.add_all([ # Girl(name='c1.com'), # Girl(name='c2.com'), # Boy(hostname='A组'), # Boy(hostname='B组'), # ]) # session.commit() #需要设置中间表建立联系
# s2g = Boy2Girl(girl_id=1,boy_id=1) # session.add(s2g) # session.commit() # # 直接添加一个对象,设置改对象的外键值 # gp = Girl(name='C组') # gp.boys = [Boy(hostname='c3.com'),Boy(hostname='c4.com')] # session.add(gp) # session.commit() # # 反向添加 # ser = Boy(hostname='c6.com') # ser.girl = [Girl(name='F组'),Girl(name='G组')] # session.add(ser) # session.commit() # 使用relationship正向查询 # v = session.query(Boy).first() # print(v.hostname) # print(v.girl) # 使用relationship反向查询 # v = session.query(Girl).first() # print(v.name) # print(v.boys) # # # # session.close()
十。flask-SQLALchemy
这是一个flask和SQLAchemy的管理者
安装:
pip install flask-sqlalchemy
如果需要和django一样,迁移数据库文件,需要安装flask-migrate
pip install flask-migrate
项目结构:
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Blueprint from .. import db from .. import models account = Blueprint('account', __name__) @account.route('/login') def login(): # db.session.add(models.Users(username='lqz', email='123')) # db.session.query(models.Users).all() # db.session.commit() # 添加示例 """ db.session.add(models.Users(username='lqz', pwd='123', gender=1)) db.session.commit() obj = db.session.query(models.Users).filter(models.Users.id == 1).first() print(obj) PS: db.session和db.create_session """ # db.session.add(models.Users(username='wupeiqi1', email='wupeiqi1@xx.com')) # db.session.commit() # db.session.close() # # db.session.add(models.Users(username='wupeiqi2', email='wupeiqi2@xx.com')) # db.session.commit() # db.session.close() # db.session.add(models.Users(username='alex1',email='alex1@live.com')) # db.session.commit() # db.session.close() user_list = db.session.query(models.Users).all() db.session.close() for item in user_list: print(item.username) return 'login'
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from .models import * from .views import account def create_app(): app = Flask(__name__) app.config.from_object('settings.DevelopmentConfig') # 将db注册到app中 db.init_app(app) # 注册蓝图 app.register_blueprint(account.account) return app
#!/usr/bin/env python # -*- coding:utf-8 -*- from . import db class Users(db.Model): """ 用户表 """ __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) # ids = db.Column(db.Integer) def __repr__(self): return '<User %r>' % self.username
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 生成依赖文件: pipreqs ./ """ from sansa import create_app from flask_script import Manager from flask_migrate import Migrate,MigrateCommand from sansa import db app = create_app() manager=Manager(app) #为了实现迁移 Migrate(app,db) #现在把命令注册进来 manager.add_command('db1', MigrateCommand) if __name__ == '__main__': # app.run() manager.run()
#!/usr/bin/env python # -*- coding:utf-8 -*- class BaseConfig(object): # SESSION_TYPE = 'redis' # session类型为redis # SESSION_KEY_PREFIX = 'session:' # 保存到session中的值的前缀 # SESSION_PERMANENT = True # 如果设置为False,则关闭浏览器session就失效。 # SESSION_USE_SIGNER = False # 是否对发送到浏览器上 session:cookie值进行加密 SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:123@127.0.0.1:3306/flask01?charset=utf8" SQLALCHEMY_POOL_SIZE = 5 SQLALCHEMY_POOL_TIMEOUT = 30 SQLALCHEMY_POOL_RECYCLE = -1 # 追踪对象的修改并且发送信号 SQLALCHEMY_TRACK_MODIFICATIONS = False class ProductionConfig(BaseConfig): pass class DevelopmentConfig(BaseConfig): pass class TestingConfig(BaseConfig): pass
启动迁移命令:
python manage.py db1 init # 初始化init,没有表 python manage.py db1 migrate # 设置表,相当于makemigrations python manage.py db1 upgrade #相当于migrate
这样的设计就可以和django一样,操作表的字段了,所有操作都要找db
补充:
反向生成model文件:
python manage.py inspectdb > app/models.py