flask_decorators.py

 '''
Flask中的特殊装饰器:
(1)@app.before_request
请求到达视图函数之前,进行自定义操作,类似django中间件中的process_request,在app中使用则为全局,在蓝图中使用则针对当前蓝图
注意正常状态下return值必须为None
(2)@app.after_request
响应返回到达客户端之前,进行自定义操作,类似jango中间件中的process_response,在app中使用则为全局,在蓝图中使用则针对当前蓝图
注意正常状态下视图函数必须定义一个形参接收response对象,并通过return response返回
(3)@app.errorhandler()
错误状态码捕获执行函数,装饰器参数务必是4xx或者5xx的int型错误状态码
(4)@app.template_global() :定义装饰全局模板可用的函数,直接可在模板中进行渲染使用
@app.template_filter(): 定义装饰全局模板可用的过滤器函数,类似django中的自定义过滤器,直接可在模板中使用
两个特殊装饰器主要用在模板渲染,详情使用见falsk学习中的jinjia2学习
'''
import os from flask import Flask, render_template, session, redirect, request, send_file app = Flask(__name__)
app.debug = True
app.secret_key = 'sdfghjhg1234' # (1)@app.before_request请求达到视图函数之前装饰器函数,正常状态务必return None
@app.before_request
def b1():
print('b1')
urls = ['/login']
if request.path in urls:
return None
if session.get('username'):
return None
else:
return redirect('/login') @app.before_request
def b2():
print('b2')
return None # (2)@app.after_request响应到达客户端之前装饰器函数,正常状态被装饰函数必须定义一个形参来接收response,务必return response
@app.after_request
def a1(response):
print('a1')
return response @app.after_request
def a2(response):
print('a2')
return response # (3)@app.errorhandler(错误状态码)错误捕获装饰器,装饰其中必须传入4xx或5xx的错误状态码,同时在被装饰函数中定义一个形参来接收错误信息error
@app.errorhandler(404)
def notfond(errormessage):
print(errormessage)
return send_file(os.path.join(os.path.dirname(__file__), 'static', '1.png')) # (4)@app.template_global()和@app.template_filter()装饰器函数直接在模板中可以全局使用 @app.template_global()
def sum1(a, b):
return a + b @app.template_filter()
def sum2(a, b, c, d):
return a + b + c + d # (5)@app.route()路由视图装饰器,第一个参数为请求路径,其它关键字参数使用相见flask之route路由学习
# 可以使用app.add_url_rule(rule, endpoint=None, view_func=None,)进行路由
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
print('login_get')
return render_template('login.html')
elif request.method == 'POST':
print('login_post')
username = request.form.get('username')
pwd = request.form.get('pwd')
if username == 'yang' and pwd == '':
session['username'] = username
return redirect('/index')
else:
return '登录失败!!!' @app.route('/index')
def index():
print('index')
return render_template('index.html') @app.route('/data')
def data():
print('data')
return 'data' @app.route('/detail')
def detail():
print('detail')
return 'detail' if __name__ == '__main__':
app.run()

index.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
index页面
</body>
</html>

flask之Flask特殊装饰器的更多相关文章

  1. flask笔记(三)Flask 添加登陆验证装饰器报错,及解析

    Flask 添加登陆验证装饰器报错,及解析 写这个之前,是想到一个需求,这个是关于之前写Flask笔记(二)中的一个知识点,路由相关 需求为 : 有一些页面必须是登陆之后才能访问的,比如Shoppin ...

  2. Flask之基于route装饰器的路由系统(源码阅读解析)

    一 路由系统 1. 在flask中配置URL和视图函数的路由时,首先需要在main.py中实例化一个app对象: from flask import Flask, render_template ap ...

  3. Flask中的before_request装饰器和after_request装饰器以及WTForms组件

    一.before_request装饰器和after_request装饰器 我们现在有一个Flask程序其中有3个路由和视图函数 from flask import Flask app = Flask( ...

  4. flask模板语言,装饰器,路由及配置

    1.模板语言jinja2 Flask中默认的模板语言是Jinja2 1.0 模板传参 from flask import Flask,render_template app = Flask(__nam ...

  5. Flask(2)- 装饰器的坑及解决办法、flask中的路由/实例化配置/对象配置/蓝图/特殊装饰器(中间件、重定义错误页面)

    一.装饰器的坑以及解决方法 1.使用装饰器装饰两个视图函数,代码如下 from flask import Flask, redirect, render_template, request, sess ...

  6. Flask 模板语言,装饰器

      Jinja2模板语言 # -*- coding: utf-8 -*-   from flask import Flask, render_template, request, redirect,  ...

  7. Flask框架视图多层装饰器问题

    Flask中的app.route装饰器 我们知道,在flask框架中,我们的路由匹配就是通过有参装饰器来实现的,我们看一个简单的例子: from flask import Flask, render_ ...

  8. Flask内的特殊装饰器

    @app.template_global()  # 全局变量 @app.template_filter()    # 偏函数 @app.before_request    # 请求进入视图函数之前,比 ...

  9. Flask入门 之 没有装饰器的路由

    有些时候,需要一个类似路由的功能,但又不能或者不想写装饰器,这该怎么办? so easy! eg: @app.route('login') def login(): return 'hello wor ...

  10. Flask 中的 特殊装饰器before_request/after_request

    before_request :在请求收到之前绑定一个函数做一些事情. after_request: 每一个请求之后绑定一个函数,如果请求没有异常. teardown_request: 每一个请求之后 ...

随机推荐

  1. 字符串的z型转换

    class Solution(object):     def convert(self, s, numRows):         if numRows==1:             return ...

  2. Scala教程之:函数式的Scala

    文章目录 高阶函数 强制转换方法为函数 方法嵌套 多参数列表 样例类 比较 拷贝 模式匹配 密封类 单例对象 伴生对象 正则表达式模式 For表达式 Scala是一门函数式语言,接下来我们会讲一下几个 ...

  3. docker 部署FastDFS

    教程:https://blog.csdn.net/fangchao2011/article/details/103202591 教程:https://www.jianshu.com/p/3f80cba ...

  4. Linux系统管理第一二三四章 系统管理 目录和文件管理 安装及管理程序 账号管理

    命令 功能 序号 第一章   cd 切换目录 1 stat 查看文件状态信息 2 cp 复制   -f -i -p -r 3 du 统计磁盘的大小 4 find 精细查找文件和目录 5 help 帮助 ...

  5. Linux下必知必会文件和目录

    转载于:https://blog.51cto.com/xiyuxingxia/2372712

  6. BigDecimal 01 - 在JAVA中怎么比较Double类型数据的大小?

    2019独角兽企业重金招聘Python工程师标准>>>  非整型数,运算由于精度问题,可能会有误差,建议使用BigDecimal类型! double a = 0.001;  doub ...

  7. html入门详细笔记

    Web的基本概念 什么是Web? 中文翻译"网页",它是一些列技术的总称,(包括网站的前台布局.后台程序.美工.数据库开发等),我们称它为网页. Web标准 结构标准(HTML) ...

  8. 数据结构--链式栈--C++实现

    #include <iostream> using namespace std; template<class T>class Stack { private: struct ...

  9. SVN 应用

    1.从服务器上down 资料 在电脑上安装SVN客户端 在电脑本地创建个文件夹作为版本库 进入 xfssvn 文件夹右击鼠标选择 SVN Checkout 或 SVN Update 输入服务器中配置好 ...

  10. Nginx模块开发(4)————使用subrequest访问第三方服务

    该模块可以完成如下的功能,当我们输入http://你的ip/lcw?s_sh000001时,会使用subrequest方式得到新浪服务器上的上证指数,代码如下: //start from the ve ...