本文主要是介绍Flask---flask-script、flask-sqlalchemy、flask_migrate、多app应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
-
-
- flask-script使用
- flask_sqlalchemy使用
- flask_migrate使用
- 多app应用
-
flask-script使用
1、入口文件manage.py
manage.py
from s8day130_pro import create_app
from flask_script import Manager
from flask_script import Command
from flask_script import Manager, Serverapp = create_app()
manager = Manager(app)# 自定义命令二:
@manager.command
def custom(arg):"""自定义命令python manage.py custom 123"""print(arg)# 自定义命令三:
@manager.option('-n', '--name', dest='name')
@manager.option('-u', '--url', dest='url')
def cmd(name, url):"""python manage.py cmd -n safly -u 'baidu.com'python manage.py cmd -name safly -url 'baidu.com'"""print(name, url)# 自定义命令一:
class Hello(Command):"""自定义命令python manage.py hello"""def run(self):print('hello world')manager.add_command('hello', Hello())# 启动项目python manage.py runserverif __name__ == '__main__':# app.run()manager.run()
flask_sqlalchemy使用
2、__init__.py文件
作用:将SQLAlchemy相关的所有功能都封装到db=flask_sqlalchemy.SQLAlchemy()对象中
from flask import Flask
from flask_sqlalchemy import SQLAlchemy# 包含了SQLAlchemy相关的所有操作
db = SQLAlchemy()def create_app():app = Flask(__name__)app.config.from_object('settings.DevelopmentConfig')from .views.account import acapp.register_blueprint(ac)db.init_app(app)return app
3、settings.py配置文件
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:root@127.0.0.1:3306/test?charset=utf8"SQLALCHEMY_POOL_SIZE = 5SQLALCHEMY_POOL_TIMEOUT = 30SQLALCHEMY_POOL_RECYCLE = -1# 追踪对象的修改并且发送信号SQLALCHEMY_TRACK_MODIFICATIONS = Falseclass ProductionConfig(BaseConfig):passclass DevelopmentConfig(BaseConfig):passclass TestingConfig(BaseConfig):pass
4、Blueprint文件
from flask import blueprints
from s8day130_pro import models
from s8day130_pro import db
ac = blueprints.Blueprint('ac',__name__)@ac.route('/login',methods=['GET','POST'])
def login():data = db.session.query(models.Users).all()print(data)db.session.remove()return 'Login'
5、编写离线脚本文件
drop_table.py
"""
Web运行时,flask程序运行起来,用户通过浏览器访问
离线脚本,自定义的一个py文件+使用flask中定义好的功能
"""from s8day130_pro import db
from s8day130_pro import create_app
from s8day130_pro import modelsapp = create_app()
#从栈拿app
with app.app_context():# db.drop_all()db.create_all()data = db.session.query(models.Users).all()print(data)
6、models.py类
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, UniqueConstraint, Index,DateTime,ForeignKey
from s8day130_pro import db
class Users(db.Model):__tablename__ = 'users'id = Column(Integer, primary_key=True,autoincrement=True)name = Column(String(32),nullable=False,unique=True)
直接运行离线脚本drop_table.py
生成users
表
然后通过python manage.py runserver
启动项目即可
flask_migrate使用
作用:做数据库迁移
依赖:
flask-script
flask-sqlalchemy
from flask_migrate import Migrate,MigrateCommand
from s8day130_pro import create_app,dbMigrate(app,db)
manager.add_command('db', MigrateCommand)
数据库迁移命名
python manage.py db initpython manage.py db migrate # makemigrationspython manage.py db upgrade # migrate
多app应用
from flask import Flask
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.serving import run_simpleapp01 = Flask('app01')
app02 = Flask('app02')@app01.route('/login')
def login():return 'app01.login'@app02.route('/index')
def index():return 'app02.index'dm = DispatcherMiddleware(app01, {'/app02': app02,
})if __name__ == '__main__':run_simple('localhost', 5000, dm)
http://localhost:5000/app02/index
http://localhost:5000/login
这篇关于Flask---flask-script、flask-sqlalchemy、flask_migrate、多app应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!