Flask-Session SQLAlchemy Script Migrate wtforms
Flask-session
Flask-session跟框架自帶的session有什麽區別呢~
框架自帶的session是通過請求上下文~放入到Local中的~那如果我們想把session放入別的地方怎麽辦呢~~
比如redis~或者數據庫~等等~~Flask-session就提供了這些功能~~我們看下Flask-session怎麽用~~
一、下載安裝
pip install flask-session
二、導入並實例化
def create_app(): app = Flask(__name__) app.config.from_object("settings.BaseConfig") app.register_blueprint(us) # Flask-Session 第二步實例化session Session(app) return app
三、配置文件
class BaseConfig(object): # Flask-Session 第三步 # SESSION_TYPE = ‘redis‘ # SESSION_REDIS = Redis(host=‘192.168.0.94‘, port=‘6379‘)
實現原理
回顧一下session的實現原理~請求進來先把request以及session封裝到RequestContext對象中~~
然後調用push方法通過LocalStark放入到Local中~這時候放入到Local中的session還是空的~
然後調用了session_interface中的open_session 以及save_session方法~~
那我們再看下~~Flask-session都做了什麽~~
修改了app.session_interface這個類~所以在我們調用open_session以及save_session的時候~調用的是我們配置的類裏的方法~
從而實現了session存儲地方的不同~
Flask SQLAlchemy
學習Flask-SQLAlchemy之前~大家要先學習一下SQLAlchemy~一個Python的ORM框架~~
點我學習SQLALchemy
接下來是Flask-SQLAlchemy的應用~~
一、下載安裝
pip3 install flask-sqlalchemy
二、導入並實例化SQLAlchemy
# 在跟項目同名的文件夾下的 init.py中 from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from .views.user import us # !!! 註意事項 # 必須在導入藍圖之前
三、初始化
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
四、在配置文件寫入配置信息
class BaseConfig(object): # Flask-Session 第三步 # SESSION_TYPE = ‘redis‘ # SESSION_REDIS = Redis(host=‘192.168.0.94‘, port=‘6379‘) SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:[email protected]:3306/code_record?charset=utf8" SQLALCHEMY_POOL_SIZE = 10 SQLALCHEMY_MAX_OVERFLOW = 5 # SQLALCHEMY_TRACK_MODIFICATIONS = False pass
五、創建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)
六、生成表(需要使用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()
七、基於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
一、下載安裝
pip3 install flask-script
二、增加的功能 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)
三、自定義命令
# 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
一、下載安裝
pip3 install flask-migrate
二、增加的命令
!!!! 依賴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組件大同小異~~
一、下載安裝
pip3 install wtforms
二、自動生成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>
三、驗證
第一步 在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>
四、拓展字段
以用戶註冊為例,輸入用戶名,密碼,重復密碼,性別和愛好。
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>register.html
!!! 註意選項字段需要去數據庫取數據 還有就是從數據庫取數據的實時更新
Flask-Session SQLAlchemy Script Migrate wtforms