Flask-Session SQLAlchemy Script Migrate wtforms

Flask-session

Flask-session跟框架自帶的session有什麼區別呢~html

框架自帶的session是經過請求上下文~放入到Local中的~那若是咱們想把session放入別的地方怎麼辦呢~~前端

好比redis~或者數據庫~等等~~Flask-session就提供了這些功能~~咱們看下Flask-session怎麼用~~html5

1、下載安裝python

pip install flask-session

2、導入並實例化mysql

複製代碼
from flask_session import Session
from flask import  Flask
def create_app():
app = Flask(__name__)
app.config.from_object("settings.DevConfig")

Session(app)
app.register_blueprint(userBlue)
return app
複製代碼

3、配置文件redis

class BaseConfig(object):
    # Flask-Session  第三步
    # SESSION_TYPE = 'redis'
    # SESSION_REDIS = Redis(host='192.168.0.94', port='6379')

實現原理

回顧一下session的實現原理~請求進來先把request以及session封裝到RequestContext對象中~~sql

而後調用push方法經過LocalStark放入到Local中~這時候放入到Local中的session仍是空的~數據庫

而後調用了session_interface中的open_session 以及save_session方法~~django

那咱們再看下~~Flask-session都作了什麼~~flask

修改了app.session_interface這個類~因此在咱們調用open_session以及save_session的時候~調用的是咱們配置的類裏的方法~

從而實現了session存儲地方的不一樣~

Flask SQLAlchemy

學習Flask-SQLAlchemy以前~你們要先學習一下SQLAlchemy~一個Python的ORM框架~~

點我學習SQLALchemy

接下來是Flask-SQLAlchemy的應用~~

1、下載安裝

pip3 install flask-sqlalchemy

2、導入並實例化SQLAlchemy

複製代碼
# 在跟項目同名的文件夾下的 init.py中
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

from .views.user import us

# !!! 注意事項
#   必須在導入藍圖以前
複製代碼

3、初始化

複製代碼
def create_app():
    app = Flask(__name__)
    app.config.from_object("settings.BaseConfig")

    app.register_blueprint(us)
    # Flask-Session 第二步實例化session
    Session(app)
    # 初始化db
    db.init_app(app)
    return app
複製代碼

4、在配置文件寫入配置信息

複製代碼
class BaseConfig(object):
    # Flask-Session  第三步
    # SESSION_TYPE = 'redis'
    # SESSION_REDIS = Redis(host='192.168.0.94', port='6379')

    SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:root1234@127.0.0.1:3306/code_record?charset=utf8"
    SQLALCHEMY_POOL_SIZE = 10
    SQLALCHEMY_MAX_OVERFLOW = 5

    # SQLALCHEMY_TRACK_MODIFICATIONS = False
    pass
複製代碼

5、建立model

複製代碼
# by gaoxin
from sqlalchemy import Column, Integer, String
from flask_demo import db


class Users(db.Model):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(32), index=True, nullable=False)
複製代碼

6、生成表(須要使用app上下文)

複製代碼
# by gaoxin
from flask_demo import db, create_app
from flask_demo.models import *
# 必定要導入models 不然找不到表建立不出來 app = create_app() app_ctx = app.app_context() with app_ctx: db.create_all() # db.drop_all()
複製代碼

7、基於ORM對數據庫操做

複製代碼
# by gaoxin
from flask import Blueprint
from flask_demo import db
from flask_demo.models import Users

us = Blueprint("us", __name__)


@us.route("/index")
def index():
    # db.session.add(Users(name="gaoxin"))
    # db.session.commit()
    # db.session.remove()
    ret = db.session.query(Users).all()
    print(ret)
    db.session.remove()
    return "Index"
複製代碼

 Flask-Script

1、下載安裝

pip3 install flask-script

2、增長的功能 runserver

複製代碼
# by gaoxin

from flask_demo import create_app
from flask_script import Manager

app = create_app()
manager = Manager(app)

if __name__ == '__main__':
    # app.run()
    manager.run()
# 啓動命令變成
# python3 manager.py runserver -h 127.0.0.1 -p 8000
# Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
複製代碼

3、自定義命令

複製代碼
# by gaoxin

from flask_demo 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)
    
    
# 關鍵字傳參
@manager.option('-n', '--name', dest='name')
@manager.option('-u', '--url', dest='url')
def cmd(name, url):
    """
    自定義命令
    執行: python manage.py  cmd -n gaoxin -u http://www.oldboyedu.com
    :param name:
    :param url:
    :return:
    """
    print(name, url)


if __name__ == '__main__':
    # app.run()
    manager.run()
複製代碼

 Flask-migrate

1、下載安裝

pip3 install flask-migrate

2、增長的命令  

  !!!! 依賴flask-script  !!!!

原來數據庫有表的話,會把原來多餘的表刪了。不能多表或者少表

複製代碼
# by gaoxin

from flask_demo import create_app, db
from flask_demo.models import *
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

app = create_app()
manager = Manager(app)
Migrate(app, db)

"""
# 數據庫遷移命名
# 依賴 flask-script
python manage.py db init # 初始化
python manage.py db migrate # makemigrations
python manage.py db upgrade # migrate
"""
manager.add_command("db", MigrateCommand)

if __name__ == '__main__':
    # app.run()
    manager.run()
複製代碼

 wtforms

類比咱們django的Form組件~

Form組件的主要應用是~幫助咱們自動生成HTML,以及作表單數據的驗證~~

用法跟Form組件大同小異~~

1、下載安裝

pip3 install wtforms

2、自動生成HTML

第一步 生成一個Form類

第二步 實例化這個Form類,把這個實例化對象當成參數傳遞給前端

複製代碼
# 視圖頁面
from wtforms import Form, widgets, validators
from wtforms.fields import simple
class MyForm(Form):
    name = simple.StringField(
        label="用戶名",
        render_kw={"placeholder": "請輸入用戶名"},
        widget=widgets.TextArea(),
        default="gaoxin"
    )
    pwd = simple.PasswordField()


@ac.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        form = MyForm(data={"name": "gao"})
        return render_template("login.html", form=form)
複製代碼
複製代碼
<!--html頁面-->
<form action="" novalidate>
    用戶名: {{form.name}}
    密碼: {{form.pwd}}
    <button type="submit">提交</button>

</form>
<!--循環出來的頁面-->
<form action="">
    {% for field in form %}
        {{field.label}}: {{field}}

    {% endfor %}
    <button type="submit">提交</button>

</form>
複製代碼

3、驗證

第一步  在Form類中增長驗證信息

第二步 在視圖中作數據的校驗 而且頁面展現錯誤信息

複製代碼
# 視圖頁面
class MyForm(Form):
    name = simple.StringField(
        label="用戶名",
        render_kw={"placeholder": "請輸入用戶名"},
        # widget=widgets.TextArea(),
        validators=[
            validators.DataRequired(message="用戶名不能爲空"),
            validators.Length(min=6, max=18, message='用戶名長度必須大於%(min)d且小於%(max)d')
        ],
        # default="gaoxin"
    )
    pwd = simple.PasswordField(
        label="密碼",
        widget=widgets.PasswordInput(),
        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個特殊字符')
        ]
    )


@ac.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        form = MyForm(data={"name": "gao"})
        return render_template("login.html", form=form)
    form = MyForm(formdata=request.form)
    if form.validate():
        print(form.data)
    else:
        return render_template("login.html", form=form)
    return "lakdsjlga"
複製代碼
複製代碼
<!--循環出來的頁面-->
<form action="" method="post" novalidate>
    {% for field in form %}
        {{field.label}}: {{field}} {{field.errors[0]}}

    {% endfor %}
    <button type="submit">提交</button>

</form>
複製代碼

4、拓展字段

以用戶註冊爲例,輸入用戶名,密碼,重複密碼,性別和愛好。

複製代碼
class RegisterForm(Form):
    name = simple.StringField(
        label='用戶名',
        validators=[
            validators.DataRequired()
        ],
        widget=widgets.TextInput(),
        # render_kw={'class': 'form-control'},
        default='gaoxin'
    )

    pwd = simple.PasswordField(
        label='密碼',
        validators=[
            validators.DataRequired(message='密碼不能爲空.')
        ],
        widget=widgets.PasswordInput(),
        # render_kw={'class': 'form-control'}
    )

    pwd_confirm = simple.PasswordField(
        label='重複密碼',
        validators=[
            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
    )
    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, '羽毛球'))


@ac.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        form = RegisterForm(data={'gender': 1})
        return render_template('register.html', form=form)
    else:
        form = RegisterForm(formdata=request.form)
        if form.validate():
            return "註冊成功"
        else:
            print(form.errors)
            return render_template('register.html', form=form)
複製代碼
複製代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>用戶註冊</h1>
<form method="post" novalidate style="padding:0  50px">
    {% for item in form %}
    <p>{{item.label}}: {{item}} {{item.errors[0] }}</p>
    {% endfor %}
    <input type="submit" value="提交">
</form>
</body>
</html>
複製代碼

!!! 注意選項字段須要去數據庫取數據 還有就是從數據庫取數據的實時更新

相關文章
相關標籤/搜索