flask-sqlalchemy
flask-sqlalchemy相当于是粘合剂,他把flask跟sqlalchemy粘合在一起,
a. 下载安装
pip install flask-sqlalchemy
b. __init__.py
导入并实例化SQLAlchemy
# 第一步:导入并实例化SQLAlchemy from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
注意事项:
- 必须在导入蓝图之前
- 必须导入models.py
c. 初始化
db.init_app(app)
from flask import Flask from flask_session import Session # 第一步:导入并实例化SQLAlchemy from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from .views.account import ac from .views.user import us from .models import * def create_app(): app = Flask(__name__) app.config.from_object('settings.ProConfig') app.register_blueprint(ac) app.register_blueprint(us) # Flask-Session: 第一步示例Session # Session(app) # 第三步:依赖app中的配置文件 db.init_app(app) return app
d. 在配置文件中写入配置
# ##### SQLALchemy配置文件 ##### SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/s9day122?charset=utf8" SQLALCHEMY_POOL_SIZE = 10 SQLALCHEMY_MAX_OVERFLOW = 5 SQLALCHEMY_TRACK_MODIFICATIONS = False
e. 创建models.py中的类(对应数据库表)
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column from sqlalchemy import Integer,String,Text,Date,DateTime from sqlalchemy import create_engine from chun import db class Users(db.Model): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=False) depart_id = Column(Integer)
f. 生成表(使用app上下文)
#新建create_tablepy from chun import db,create_app app = create_app() app_ctx = app.app_context() # app_ctx = app/g with app_ctx: # __enter__,通过LocalStack放入Local中 db.create_all() # 调用LocalStack放入Local中获取app,再去app中获取配置
g. 基于ORM对数据库进行操作。
from flask import Blueprint from chun import db from chun import models us = Blueprint('us',__name__) @us.route('/index') def index(): # 使用SQLAlchemy在数据库中插入一条数据 # db.session.add(models.Users(name='高件套',depart_id=1)) # db.session.commit() # db.session.remove() result = db.session.query(models.Users).all() print(result) db.session.remove() return 'Index'
flask-session
1、配置__init__.py
def create_app(): app = Flask(__name__) app.config.from_object('settings.ProConfig') app.register_blueprint(ac) app.register_blueprint(us) # Flask-Session: 第一步示例Session # Session(app) db.init_app(app) return app
2、settings.py配置
class BaseConfig(object): # Flask-Session: 第二步配置 # SESSION_TYPE = 'redis' # SESSION_REDIS = Redis(host='192.168.0.94', port='6379')
flask-script
安装
pip install flask-script
使用和配置
a. 增加 runserver
在manage.py文件中导入模块,并且注册manager
from flask_script import Manager app = create_app() manager = Manager(app) if __name__ == '__main__': # app.run() manager.run()
当完成这部操作的时候我们就可以对 用命令进行runserver开启我们的Flask程序
python manage.py runserver -h 127.0.0.1 -p 8001
b. 位置传参
from chun import create_app from flask_script import Manager app = create_app() manager = Manager(app) @manager.command def custom(arg): """ 自定义命令 python manage.py custom 123 :param arg: :return: """ print(arg) if __name__ == '__main__': # app.run() manager.run() python manage.py custom 11111 #单独的执行函数
c. 关键字传参
from chun import create_app from flask_script import Manager app = create_app() manager = Manager(app) @manager.option('-n', '--name', dest='name') @manager.option('-u', '--url', dest='url') def cmd(name, url): """ 自定义命令 执行: python manage.py cmd -n wupeiqi -u http://www.oldboyedu.com :param name: :param url: :return: """ print(name, url) if __name__ == '__main__': # app.run() manager.run()
flask-migrate
pip3 install flask-migrate
依赖:flask-script
flask-migrate是flask的一个扩展模块,主要是扩展数据库表结构的.
models.py
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column from sqlalchemy import Integer,String,Text,Date,DateTime from sqlalchemy import create_engine from chun import db class Users(db.Model): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=False) # depart_id = Column(Integer)
manage.py
from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from chun import create_app from chun import db app = create_app() manager = Manager(app) Migrate(app, db) manager.add_command('db', MigrateCommand)
执行命令
$ python manage.py db init 初始化数据库,会创建一个migations文件夹,并且会在数据库中生成一个alembic_version表 $ python manage.py db migrate 创建迁移历史 $ python manage.py db upgrade 更新数据库
Heroku Postgres, db migrate fail: alembic.util.exc.CommandError: Can't locate revision identified by 如果报这个错误,将alembic_version表中的数据删掉即可
pipreqs
pip install pipreqs
找到项目使用的所有组件和版本。
执行命令:
pipreqs ./ --encoding=utf-8
装文件
pip install requirement.txt
Flask开发模板→文件