zoukankan      html  css  js  c++  java
  • Flask的请求扩展

    from flask import Flask,request
    app = Flask(__name__)
    

    一.请求前

    before_request

    用法

    @app.before_request
    def func():
        print(request) #可以在请求来前对于request进行处理
        #return 如果有返回值页面将渲染返回值不走@app.routex相关函数
        #如有有返回值且有after_request相关函数他的返回值会接着执行after_request相关函数
        #如果有多个before_request他会自上而下按照顺序执行
    

    二.请求后

    after_reques

    用法

    @app.after_request
    def func(response): #必须传一个response对象
        return response #必须返回一个response对象
       #有多个after_request他会从后往前执行
    

    三.页面第一次请求

    before_first_request

    用法

    @app.before_first_request
    def first():
        pass
    

    FLask启动时候,页面请求第一次才会执行,第二次不会执行与浏览器无关

    四.异常捕获

    teardown_request

    用法

    @app.teardown_request 
    def ter(e):
        pass
    
    • 只能捕获异常而不能让页面渲染出自定义的异常信息
    • app.debug=True模式下e为空
    • 无论什么情况函数都会运行

    五.异常处理

    用法

    @app.errorhandler(状态码)
    def error_404(arg):
        return "页面我们自定义错误信息进行渲染"
    

    六.页面渲染

    用法

    @app.template_global()
    def sb(a1, a2):
        return a1 + a2
    

    所有页面渲染的时候如果页面上有sb变量他将自动调用该函数

    页面中

    {{sb(1,2)}}
    #页面显示结果为3
    

    七.过滤器

    用法

    @app.template_filter()
    def db(a1, a2, a3):
        return a1 + a2 + a3
    

    页面中

    #{{ 第一个变量|db(第二个变量,第三个变量)}}
    
  • 相关阅读:
    事件DOMContentLoaded与load的区别
    JavaScript的执行环境
    JS中函数运行的执行次序
    正则表达式30分钟入门教程
    mysql数据库备份
    杂篇
    memcached
    mysql问题解决
    php学习
    apache 安装
  • 原文地址:https://www.cnblogs.com/pythonywy/p/11598299.html
Copyright © 2011-2022 走看看