Flask框架实现给视图函数增加装饰器操作示例

yipeiwu_com6年前Python基础

本文实例讲述了Flask框架实现给视图函数增加装饰器操作。分享给大家供大家参考,具体如下:

@app.route的情况下增加装饰器的写法:

from flask import Flask,request,render_template,redirect,session,url_for,views
from flask import render_template
app = Flask(__name__) #实例化flask对象
app.debug = True  #能够随时更改自动重启,不加的话每次更改代码需要手动重启
app.config['SECRET_KEY'] = '123456'  #secret_key,用于给session加密
@app.route('/login',methods=['GET','POST'],endpoint='t1') #endpoint是url的别名,相当于django中Url的name
def login():
  if request.method == "GET":
    # res = request.query_string
    # print(res) 获取通过GET请求url传过来的参数
    return render_template('login.html')
  else:
    user = request.form.get('user')
    pwd = request.form.get('pwd')
    if user == 'tom' and pwd == '123':
      session['userinfo'] = user  #设置session
      return render_template('hello.html')
    return render_template('login.html', error='用户名或密码错误')
def wapper(func):
  def inner(*args,**kwargs):
    user = session.get('user_info')
    if not user:
      return redirect('/login')
    return func(*args,**kwargs)
  return inner
@app.route('/detail/<int:nid>',methods=['GET'],endpoint='n1')
@wapper
def detail(nid):
  print(nid)
  return render_template('hello.html')
'''
如果给一个视图函数增加装饰器,应该加在app.route下面,这样的效果就是,
装饰器将下面的所有内容包裹,然后路由对应到这大的包裹中来。
需要注意endpoint要注明,如果不注明endpoint则默认用函数名来定义,
此时所有的函数名都叫inner了,所以需要注明endpoint,只是为了区分。
'''
if __name__ == '__main__':
  app.run()

另一种写法:

import functools
def wapper(func):
  @functools.wraps(func)
  def inner(*args,**kwargs):
    return func(*args,**kwargs)
  return inner
'''
functools.wraps()相当于保留元信息
说白了就是,如果不加这个装饰器,那么你打印detail的__name__它就是inner了,
因为加了装饰器,效果等同于inner=inner(detail()),
如果在装饰器中加了functools这个装饰器,那么相当于给__name__重新赋值,inner.__name__ = func.__name_-
其函数的名字得以保留。
'''
@wapper
def detail():
  pass
print(detail.__name__)

flask的get_flashed_messages,flash

from flask import Flask,get_flashed_messages,flash
app = Flask(__name__)
app.secret_key = 'asdf'
@app.route('/get')
def get():
  data = get_flashed_messages()
  print(data)
  return 'Hello world'
@app.route('/set')
def set():
  flash('info info')
  '''
  闪现效果,相当于set视图函数执行2次,会在一个列表中存储两个flash函数的内容,
  当执行get_flashed_messages的时候则会取出该列表,并清空,类似字典的Pop。
  具体用处不大。。。
  '''
  return 'Hello world'
if __name__ == '__main__':
  app.run()

flash还可以通过category参数给Flash内容归类,通过不同类别取不同内容。

更多关于Python相关内容可查看本站专题:《Python入门与进阶经典教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python构造icmp echo请求和实现网络探测器功能代码分享

python发送icmp echo requesy请求复制代码 代码如下:import socketimport struct def checksum(source_string):&...

基于MATLAB和Python实现MFCC特征参数提取

基于MATLAB和Python实现MFCC特征参数提取

1、MFCC概述 在语音识别(Speech Recognition)和话者识别(Speaker Recognition)方面,最常用到的语音特征就是梅尔倒谱系数(Mel-scale Fr...

Python网络编程之TCP套接字简单用法示例

本文实例讲述了Python网络编程之TCP套接字简单用法。分享给大家供大家参考,具体如下: 上学期学的计算机网络,因为之前还未学习python,而java则一知半解,C写起来又麻烦,所以...

Python中的字符串操作和编码Unicode详解

本文主要给大家介绍了关于 Python中的字符串操作和编码Unicode的一些知识,下面话不多说,需要的朋友们下面来一起学习吧。 字符串类型 str:Unicode字符串。采...

详解Python中打乱列表顺序random.shuffle()的使用方法

之前自己一直使用random中 randint生成随机数以及使用for将列表中的数据遍历一次。 现在有个需求需要将列表的次序打乱,或者也可以这样理解: 【需求】将一个容器中的数据每次...