Part A

變量 上下文
current_app 程序上下文
g 程序上下文
request 請(qǐng)求上下文
session 請(qǐng)求上下文
>>>from hello import app
>>>from flask import current_app
>>>app_ctx = app.app_context()
>>>app_ctx.push()

請(qǐng)求鉤子
響應(yīng)
返回狀態(tài)碼:

return '<h1>Bad request</h1>',400

利用Response對(duì)象進(jìn)行返回

from flask import make_response

@app.route('/')
def index():
    response = make_response('<h1>This document carrries a cookie.</h1>')
    response.set_cookie('answer', '42')
    return response

重定向

from flask import redirect

redirect('www.example.com')

使用FLask-Script

from flask.ext.script import Manager
manage = Manager(app)

if __name__ == 'main'
    manager.run()

使用Bootstrap

from flask.ext.bootstrap import Bootstrap

bootstrap = Bootstrap(app)

3.4 鏈接

4. web表單

使用 Flask-WTF 第三方擴(kuò)展

4.1 跨站請(qǐng)求偽造保護(hù)

app.config['SECRET_KEY'] = 'hard to guess string'
#設(shè)置密鑰

4.2 表單類

from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required

class NameForm(Form):
    name = StringField('What is your name?', validators=[Required()])//Required()函數(shù)檢查是否輸入為空
    submit = SubmitField('submit')

4.3把表單渲染成HTML

推薦使用Bootstrap中的表單樣式

{% import "bootstrap/wtf.html" as wtf %}
{{ wtf.quick_form(form) }}//參數(shù)為Flask-WTF表單

4.4 在視圖函數(shù)中處理表單

@app.route('/', methods=['GET', 'POST'])
def index():
    name = None
    form = NameForm()
    if form.validate_on_submit():
        name = form.name.data
        form.name.data = ''
    return render_template('index.html', form=form, name=name)

4.5 重定向和用戶會(huì)話

在提交表單之后,用戶刷新瀏覽器,會(huì)收到警告:要求在再次提交表單之前進(jìn)行確認(rèn)。這原因是因?yàn)樗⑿马?yè)面時(shí)瀏覽器會(huì)重新發(fā)送之前已經(jīng)發(fā)送過(guò)的最后一個(gè)請(qǐng)求。如果這個(gè)請(qǐng)求是一個(gè)包含表單數(shù)據(jù)的POST請(qǐng)求,刷新頁(yè)面后會(huì)再次提交表單。
最好的方式就是Post/重定向/Get模式
但是,程序處理POST請(qǐng)求時(shí),一旦這個(gè)請(qǐng)求結(jié)束,數(shù)據(jù)也就丟失了。所以使用session處理

from flask import Flask, render_template, session, redirect, url_for

@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        session['name'] = form.name.data
        return redirect(url_for('index'))
    return render_template('index.html',form=form,name=session.get('name'))

4.6 Flash消息

xx.py中:
flash('..')//把flash消息加入到隊(duì)列中

xx.html中:
get_flashed_messages()//把flash消息提取出來(lái)

5.數(shù)據(jù)庫(kù)

5.5 使用Flask-SQLAlchemy管理數(shù)據(jù)庫(kù)

配置數(shù)據(jù)庫(kù)

from flask.ext.sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = \
    'sqlite:///' + os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

db = SQLAlchemy(app)

5.6 定義模型

class Role(db.Model)://繼承db.Model
    __tablename__ = 'roles'//定義在數(shù)據(jù)庫(kù)中使用的表名
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True)
    
    def __repr__(self):
        return '<Role %r>' % self.name

5.7 關(guān)系

class Role(db.Model):
    #...
    users = db.relationship('User', backref='role')
    
class User(db.Model):
    #...
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

數(shù)據(jù)庫(kù)操作:

//創(chuàng)建表:
from hello import db
db.create_all()

//插入行
from hello import Role, User
admin_role = Role(name='Admin')
db.session.add(admin_role)
db.session.commit()

//刪除行
db.session.delete(admin_role)
db.session.commit()

//查詢行
//Flask-SQLAlchemy為每個(gè)模型類提供query對(duì)象
Role.query.all()
//過(guò)濾器查詢
user_role = Role.query.filter_by(name='Use').first()
//filter_by是一個(gè)過(guò)濾器,first是查詢執(zhí)行函數(shù)

5.10 集成Python shell

from flask.ext.script import Shell

def make_shell_context():
    return dict(app=app, db=db, User=User, Role=Role)
manage.add_command("shell", Shell(make_context=make_shell_context))

5.11 使用Flask-Migrate實(shí)現(xiàn)數(shù)據(jù)庫(kù)遷移

(venv)$ pip install flask-migrate

from flask.ext.migrate import Migrate, MigrateCommand

#...

migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)

//首先用init子命令創(chuàng)建遷移倉(cāng)庫(kù)
python hello.py db init

//創(chuàng)建遷移腳本
python hello.py db migrate -m "initial migration"

//更新數(shù)據(jù)庫(kù)
python hello.py db upgrade
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 22年12月更新:個(gè)人網(wǎng)站關(guān)停,如果仍舊對(duì)舊教程有興趣參考 Github 的markdown內(nèi)容[https://...
    tangyefei閱讀 35,395評(píng)論 22 257
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,551評(píng)論 19 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,007評(píng)論 25 709
  • 第4章 Web表單 我們?cè)诘诙陆榻B過(guò)請(qǐng)求對(duì)象,它包含有客戶端請(qǐng)求的全部信息。尤其是,可以通過(guò)request.fo...
    易木成華閱讀 1,127評(píng)論 0 1
  • 多少年以后,我們都老了。 害怕孤獨(dú)的夜,沒了你的陪伴。 放任的心已蕩然無(wú)存, 含笑地望著你已漸漸遠(yuǎn)去。 微風(fēng)依舊,...
    幕雨XL閱讀 178評(píng)論 0 0

友情鏈接更多精彩內(nèi)容