1. 程式人生 > >Flask的外掛session、SQLAlchemy、Script、Migrate

Flask的外掛session、SQLAlchemy、Script、Migrate

一、flask-session

1、為什麼要使用flask-session

因為flask預設的session是通過請求上下文放入到Local中的,是存在記憶體的,
而使用flask-session可以更改session存放的位置,
可以存放在redis、memcached、filesystem、mongodb、sqlalchemy等資料庫中,
flask-session也是基於flask原本的session原理實現的,只是讓session存放的位置更改了而已。

 

2、使用步驟

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)

 

3、Demo(使用藍圖搭建的Demo)

# 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
__init__.py
# 2. settings.py
import redis


class DevConfig(object):
    DEBUG = True
    SESSION_TYPE = 'redis'
    SESSION_REDIS = redis.Redis(host='localhost', port=6379)
2. settings.py
# 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"
3. user.py

 

二、Flask-SQLAlchemy

1、前戲

學習Flask-SQLAlchemy之前,我們先去學習一下SQLAlchemy(可看上一篇),SQLAlchemy是一個Python的ORM框架,SQLAlchemy
而Flask-SQLAlchemy是基於SQLAlchemy實現的一個Flask外掛。

 

2、使用步驟

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:[email protected]: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
__init__.py
# settings.py
class DevConfig(object):
    DEBUG = True
    # flask-SQLAlchemy配置
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/sqlalchemy?charset=utf8'
    SQLALCHEMY_POOL_SIZE = 5
    SQLALCHEMY_MAX_OVERFLOW = 2
    SQLALCHEMY_TRACK_MODIFICATIONS = False
settings.py
# 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'))
models.py
# 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()
run_models.py
# 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"
user.py
# manager.py
from FlaskPlug import create_app


app = create_app()

if __name__ == '__main__':

    app.run()
manager.py

 

三、Flask-Script

1、下載安裝

pip install flask-script

 

2、使用

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

 

3、自定義命令

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()

 

四、Flask-Migrate

1、下載

pip install flask-migrate

 

2、注意

flask-migrate依賴flask-script

 

3、使用

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()