标签:upgrade elf 信息 set and 离线 ext 使用步骤 cond
因为flask默认的session是通过请求上下文放入到Local中的,是存在内存的,
而使用flask-session可以更改session存放的位置,
可以存放在redis、memcached、filesystem、mongodb、sqlalchemy等数据库中,
flask-session也是基于flask原本的session原理实现的,只是让session存放的位置更改了而已。
1. 下载 pip install flask-session 2. 导入 from flask-session import Session 到__init__的app实例里面 3. 更改配置文件 class DevConfig(object): DEBUG = True SESSION_TYPE = "redis" SESSION_REDIS = redis.Redis(host="127.0.0.1", port="6379") 4. 实例化 Session(app)
# 1. __init__.py from flask import Flask from FlaskPlug.views.user import userBlue # 测试的视图 from flask_session import Session # 导入插件flask-session def create_app(): app = Flask(__name__, template_folder=‘templates‘) # 更改配置信息 app.config.from_object(‘settings.DevConfig‘) # 实例化 Session(app) app.register_blueprint(userBlue) return app
# 2. settings.py import redis class DevConfig(object): DEBUG = True SESSION_TYPE = ‘redis‘ SESSION_REDIS = redis.Redis(host=‘localhost‘, port=6379)
# 3. user.py from flask import Blueprint, session userBlue = Blueprint("userBlue", __name__) @userBlue.route(‘/‘) def index(): session[‘test‘] = ‘test-flask-session‘ return "index" @userBlue.route("/user") def user(): print(session.get(‘test‘)) return "user"
学习Flask-SQLAlchemy之前,我们先去学习一下SQLAlchemy(可看上一篇),SQLAlchemy是一个Python的ORM框架,SQLAlchemy
而Flask-SQLAlchemy是基于SQLAlchemy实现的一个Flask插件。
1. 下载 pip install flask-sqlalchemy
2. 导入 from flask_sqlalchemy import SQLAlchemy
3. 在init.py 实例化 并且实现初始化
from flask import Flask from flask_sqlalchemy import SQLAlchemy # SQLAlchemy必须在导入蓝图之前实例化 db = SQLAlchemy() from FlaskPlug.views.user import userBlue def create_app(): app = Flask(__name__) # 导入配置信息 app.config.from_object(‘settings.DevConfig‘) app.register_blueprint(userBlue) # 初始化db db.init_app(app) return app
4. 配置文件
# settings.py class DevConfig(object): DEBUG = True # flask-SQLAlchemy配置 # 连接什么数据库,哪个数据库 SQLALCHEMY_DATABASE_URI = ‘mysql+pymysql://root:123abc@127.0.0.1:3306/sqlalchemy?charset=utf8‘ SQLALCHEMY_POOL_SIZE = 5 SQLALCHEMY_MAX_OVERFLOW = 2 SQLALCHEMY_TRACK_MODIFICATIONS = False
5. 建models
# 表必须继承flask-SQLAlchemy的SQLAlchemy的实例化对象db.Model from FlaskPlug import db # 其他一些字段的东西导入的是python的SQLAlchemy from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import relationship class Book(db.Model): __tablename__ = ‘book‘ id = Column(Integer, primary_key=True) title = Column(String(64), nullable=False) publisher_id = Column(Integer, ForeignKey(‘publisher.id‘)) publisher = relationship(‘Publisher‘, backref=‘books‘) tags = relationship(‘Tag‘, backref=‘books‘, secondary=‘book2tag‘) __table_args__ = ( # UniqueConstraint联合唯一,这个联合唯一的字段名为:uni_id_name UniqueConstraint("id", "title", name="uni_id_title"), # 联合索引 Index("id", "title") ) def __repr__(self): return self.title class Publisher(db.Model): __tablename__ = ‘publisher‘ id = Column(Integer, primary_key=True) title = Column(String(64), nullable=False) def __repr__(self): return self.title class Tag(db.Model): __tablename__ = ‘tag‘ id = Column(Integer, primary_key=True) title = Column(String(64), nullable=False) def __repr__(self): return self.title class Book2Tag(db.Model): __tablename__ = ‘book2tag‘ id = Column(Integer, primary_key=True) book_id = Column(Integer, ForeignKey(‘book.id‘)) tag_id = Column(Integer, ForeignKey(‘tag.id‘))
6. 生成表
# 需要使用app上下文 # 离线脚本这时候就体现作用了 from FlaskPlug import db, create_app # 一定要导入models 否则找不到表创建不出来 from FlaskPlug.models import * app = create_app() # app_context()就是前两篇文章里面Flask请求上下文走过的流程啊 # app_ctx = AppContext(app) app_ctx = app.app_context() # with 就会去走AppContext的__enter__和__exit__方法 # __enter__就是去取app了,__exit__就是删除 with app_ctx: db.create_all() 注意:一般建表的py文件和生成表的py文件要分成两个文件执行,不然有时候会导致循环引用。
7. 基于flask-SQLAlchemy的ORM操作
跟python的SQLAlchemy一样的 @userBlue.route(‘/‘) def index(): # 给Tag增加一条数据 tag_obj = Tag(title=‘python‘) db.session.add(tag_obj) db.session.commit() db.session.close() return "index"
8. Demo
# __init__.py from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from FlaskPlug.views.user import userBlue def create_app(): app = Flask(__name__, template_folder=‘templates‘) app.config.from_object(‘settings.DevConfig‘) app.register_blueprint(userBlue) db.init_app(app) return app
# settings.py class DevConfig(object): DEBUG = True # flask-SQLAlchemy配置 SQLALCHEMY_DATABASE_URI = ‘mysql+pymysql://root:123abc@127.0.0.1:3306/sqlalchemy?charset=utf8‘ SQLALCHEMY_POOL_SIZE = 5 SQLALCHEMY_MAX_OVERFLOW = 2 SQLALCHEMY_TRACK_MODIFICATIONS = False
# models.py from FlaskPlug import db from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index from sqlalchemy.orm import relationship class Book(db.Model): __tablename__ = ‘book‘ id = Column(Integer, primary_key=True) title = Column(String(64), nullable=False) publisher_id = Column(Integer, ForeignKey(‘publisher.id‘)) publisher = relationship(‘Publisher‘, backref=‘books‘) tags = relationship(‘Tag‘, backref=‘books‘, secondary=‘book2tag‘) __table_args__ = ( # UniqueConstraint联合唯一,这个联合唯一的字段名为:uni_id_name UniqueConstraint("id", "title", name="uni_id_title"), # 联合索引 Index("id", "title") ) def __repr__(self): return self.title class Publisher(db.Model): __tablename__ = ‘publisher‘ id = Column(Integer, primary_key=True) title = Column(String(64), nullable=False) def __repr__(self): return self.title class Tag(db.Model): __tablename__ = ‘tag‘ id = Column(Integer, primary_key=True) title = Column(String(64), nullable=False) def __repr__(self): return self.title class Book2Tag(db.Model): __tablename__ = ‘book2tag‘ id = Column(Integer, primary_key=True) book_id = Column(Integer, ForeignKey(‘book.id‘)) tag_id = Column(Integer, ForeignKey(‘tag.id‘))
# run_models.py from FlaskPlug import db, create_app # 一定要导入models 否则找不到表创建不出来 from FlaskPlug.models import * app = create_app() # app_context()就是前两篇文章里面Flask请求上下文走过的流程啊 # app_ctx = AppContext(app) app_ctx = app.app_context() # with 就会去走AppContext的__enter__和__exit__方法 # __enter__就是去取app了,__exit__就是删除 with app_ctx: db.create_all()
# user.py from flask import Blueprint, session from FlaskPlug import db from FlaskPlug.models import Tag, Book, Publisher userBlue = Blueprint("userBlue", __name__) @userBlue.route(‘/‘) def index(): # 给Tag增加一条数据 tag_obj = Tag(title=‘python‘) db.session.add(tag_obj) db.session.commit() db.session.close() return "index"
# manager.py from FlaskPlug import create_app app = create_app() if __name__ == ‘__main__‘: app.run()
pip install flask-script
1. manager.py下的代码 from FlaskPlug import create_app from flask_script import Manager app = create_app() manager = Manager(app) if __name__ == ‘__main__‘: # app.run() manager.run() 2. 启动命令 这样使用Manager后,我们就可以在Terminal中启动我们的项目 或者在cmd里面 cd到项目目录下启动也可以 启动命令变成 1. 使用默认端口 python manager.py runserver 2. 自定义域名和端口 python manager.py runserver -h 127.0.0.1 -p 8000
from FlaskPlug import create_app from flask_script import Manager app = create_app() manager = Manager(app) # 位置传参 @manager.command def my_add(arg1, arg2): """ 自定义命令 python manager.py my_add 1 2 """ ret = int(arg1) + int(arg2) print(arg1, arg2, ret) # 关键字传参 # 关键字参数的简写:-n # 关键字参数全写:--name # 关键字的描述:dest @manager.option(‘-n‘, ‘--name‘, dest=‘name‘) @manager.option(‘-a‘, ‘--age‘, dest=‘age‘) def person(name, age): """ 自定义命令 执行: python manager.py person -n 小明 --age 28 """ print(name, age) if __name__ == ‘__main__‘: # app.run() manager.run()
pip install flask-migrate
flask-migrate依赖flask-script
from FlaskPlug import create_app, db from FlaskPlug.models import * from flask_script import Manager from flask_migrate import Migrate, MigrateCommand # 1. 导入SQLAlchemy的实例化db和script、migrate插件 app = create_app() manager = Manager(app) Migrate(app, db) # 2. 实例化Migrate # 3. 给manager添加命令(MigrateCommand里面就存放了自定义的命令) manager.add_command("db", MigrateCommand) """ 数据库迁移命令 依赖 flask-script python manager.py db init # 初始化 python manager.py db migrate # 相当于Django的ORM的makemigrations python manager.py db upgrade # 相当于Django的ORM的migrate """ if __name__ == ‘__main__‘: # app.run() manager.run()
Flask的插件session、SQLAlchemy、Script、Migrate
标签:upgrade elf 信息 set and 离线 ext 使用步骤 cond
原文地址:https://www.cnblogs.com/Zzbj/p/10215890.html