日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

關于Flask高級_內置信號的介紹和兩個小實例

作者:NewBurlaSKing 更新時間: 2022-08-30 編程語言

Flask高級_內置信號

一.介紹

Flask中常用的內置信號:
  1. template_rendered:模版渲染完成后的信號。
  2. before_render_template:模版渲染之前的信號。
  3. request_started:請求開始之前,在到達視圖函數之前發送信號。
  4. request_finished:請求結束時,在響應發送給客戶端之前發送信號。
  5. request_tearing_down:請求對象被銷毀時發送的信號,即使在請求過程中發生異常也會發送信 號。
  6. got_request_exception:在請求過程中拋出異常時發送信號,異常本身會通過exception傳遞到訂 閱(監聽)的函數中。一般可以監聽這個信號,來記錄網站異常信息。
  7. appcontext_tearing_down:應用上下文被銷毀時發送的信號。
  8. appcontext_pushed:應用上下文被推入到棧上時發送的信號。
  9. appcontext_popped:應用上下文被推出棧時發送的信號。
  10. message_flashed:調用了Flask的 flash 方法時發送的信號。

二.實例

template_rendered的使用:
#coding=utf-8

from flask import Flask,render_template,template_rendered

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('home.html')

def renderfunc(sender,template,context):
    print(sender)
    print(template)
    print(context)

template_rendered.connect(renderfunc)

if __name__ == '__main__':
    app.run(debug=True)

在這里插入圖片描述

got_request_exception的使用:
#coding=utf-8

from unicodedata import name
from flask import Flask,got_request_exception

app = Flask(__name__)

@app.route('/')
def zero_err():
    x = 1 / 0
    return 'Hello~'

def errhandle(sender,exception):
    with open('text.log','a',encoding='utf-8') as f:
        f.write(str(sender) + '\n')
        f.write(str(exception) + '\n')

got_request_exception.connect(errhandle)

if __name__ == '__main__':
    app.run(debug=True)

在這里插入圖片描述

注:

如果覺得筆記有些問題,麻煩在百忙之中在評論中指正,或提出建議!另外,如果覺得這份筆記對你有所幫助,麻煩動動發財的小手手點一波贊!

原文鏈接:https://blog.csdn.net/qq_55961861/article/details/126592627

欄目分類
最近更新