1. 程式人生 > >PythonWeb框架之Flask

PythonWeb框架之Flask

視圖 func 循環 https rul session out quest turn

簡單實例:

from flask import Flask

app = Flask(__name__)


@app.route(/)
def hello_world():
    return Hello World!


if __name__ == __main__:
    app.run()

1.配置

  通過app.config進行配置項的設置:

  - 直接賦值

app.config[secret_key] = "sdf234jkwjk3423kldjl"

  - 通過配置文件進行配置項管理

# settings.py 定義類,變量名要大寫,在flask的使用源碼裏進行了isupper的判斷
class BaseConfig(): SALT = "3d086a6d-a140-41d8-817b-61f66de49fc0" SECRET_KEY = "3c43k6zl5las1d2kk3d8y7tw" # 使用 app.config.from_object("settings.BaseConfig")

2.路由系統

  - 方式一

def index():
    pass
app.add_url_rule(/, index, index) # ‘/‘:url,‘index‘:endpoint,index:對應執行的函數

  - 方式二

@app.route(
/‘, endpoint=‘index‘) def index(): pass

  - 動態傳參

@app.route(/index/<int:nid>)
def index(nid):
    return "Index"

  endpoint指定反向解析url的方式,默認為函數名

url_for(endpoint) # 反向解析
url_for(endpoint, nid=參數) # 反向解析傳參

  指定請求方式methods

@app.route(/, methods=[GET,POST])  # 默認只有GET

3.CBV

  示例

#
CBV視圖 from flask import Flask,url_for,views #----------------------------------------------------- app=Flask(__name__) #裝飾器 def auth(func): print(我在上面) def inner(*args,**kwargs): return func(*args,**kwargs) return inner #-------------------------------------------------------- class IndexView(views.MethodView): #CBV視圖 methods=[GET] #允許的http請求方法(改CBV只允許GET方法) decorators = [auth,] #每次請求過來都加auth裝飾器 def get(self): return Index.GET def post(self): return Index.POST app.add_url_rule(/index/,view_func=IndexView.as_view(name=name1)) #(name=‘name1‘反向生成url別名 if __name__ == __main__: app.run() CBV視圖

4.請求相關

  request能獲取的數據:

request.method
request.args
request.form
request.values
request.cookies
request.headers
request.path
request.full_path
request.script_root
request.url
request.base_url
request.url_root
request.host_url
request.host
request.files

  詳細信息參考博客https://www.cnblogs.com/wangjikun/p/6935592.html

5.響應

  - return "Hello World" 返回字符串

  - return jsonify({‘data‘: data}) 返回json數據

  - return render_template(‘index.html‘) 返回HTML

  - return redirect(‘/login‘) 跳轉

  定制響應頭:

from flask import make_response

response = make_response("Hello World")
response.headers["xxx"] = "value"
# 設置cookie
response.set_cookie("key", "value")
return response

6.模板渲染

  使用方式和Django的模板渲染類似:{{ }} 和 {% %}。

  基本方法不太一樣,函數需要加括號執行,類似於python的語法:

    - {{ dict.get() }} 或 {{ dict["key"] }}

    - {{ list[0] }}

    - {% for 循環 %} {% endfor %}

    - {% if 判斷 %} {% endif %}

  還可以自定義全局函數,在模板中使用:

@app.template_global()
def sum(a1, a2):
    return a1 + a2
# 模板中使用{{ sum(2, 3) }}

# 類似的
@app.template_filter()
def sum(a1, a2, a3):
    return a1 + a2 + a3
# 調用方式不同{{ 1|sum(2,3) }}    

  模板繼承:

{% extends "mater.html"%}

{% block content %}
    自定義內容
{% endblock %}

{% include "組件.html" %}    

  定義宏:

{% macro input(name, type=text, value= ) %}
<input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}

# 使用
<form>
{{ input(username) }}
{{ input(password, type="password") }}
{{ input( , type="submit", value="提交") }}
</form>

  安全:

# 前端
{{ data|safe }}

# 後端
from flask import Markup
data = Markup(data)

7.session

  flask中的session正常保存在cookie中,當請求時,會從cookie中讀取session值,進行解密和反序列化保存在Local對象中,通過導入的session可以在視圖中進行操作。請求結束時,會從Local對象中讀取值,進行序列化和加密後保存到cookie中。

8.flash

  flask中暫時儲存數據的一個方式

from flask import flash, get_flashed_messages

# 儲存數據
flash("臨時數據", "name")

# 獲取數據, 通過pop獲取並移除
msg = get_flashed_messages(category_filter=["name"])

9.中間件

  flask中請求到來時會執行app.__call__方法,而__call__會執行app.wsgi_app方法。而我們就可以通過重寫wsgi_app完成一個中間件,重寫app.wsgi_app為對象,執行app.wsgi_app()就會觸發類的__call__方法,在__call__方法裏完成中間件的操作。

class Middleware():
    def __init__(self, wsgi_app)
        self.wsgi_app = wsgi_app

    def __call__(self, environ, start_response):
        # 在處理請求前的操作
        ret = self.wsgi_app(environ, start_response)
        # 在請求完成後的操作
        return ret

if __name__ == __main__:
    app.wsgi_app = Middleware(app.wsgi_app)
    app.run()

10.特殊裝飾器

  1.before_request:在執行請求對應的視圖函數之前執行其裝飾的函數,可以用作登錄驗證。

  2.after_request:在請求完成後執行其裝飾的函數

  3.before_first_request:在第一次請求時執行其裝飾的函數

  4.template_global

  5.template_filter

  6.errorhandler:捕捉指定的錯誤,進而執行其裝飾的函數    

PythonWeb框架之Flask