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中实现对Timestamp和Datetime及UTC时间之间的转换

Python项目中很多时候会需要将时间在Datetime格式和TimeStamp格式之间转化,又或者你需要将UTC时间转化为本地时间,本文总结了这几个时间之间转化的函数,供大家参考。 一...

Python编程实现的简单神经网络算法示例

Python编程实现的简单神经网络算法示例

本文实例讲述了Python编程实现的简单神经网络算法。分享给大家供大家参考,具体如下: python实现二层神经网络 包括输入层和输出层 # -*- coding:utf-8 -*-...

python实现对指定字符串补足固定长度倍数截断输出的方法

简单的小练习,注意考虑全可能就行,下面是实现: #!usr/bin/env python #encoding:utf-8 ''' __Author__:沂水寒城 功能:̶...

Python中对列表排序实例

很多时候,我们需要对List进行排序,Python提供了两个方法,对给定的List L进行排序: 方法1.用List的成员函数sort进行排序 方法2.用built-in函数sorted...

Pycharm如何打断点的方法步骤

Pycharm如何打断点的方法步骤

一. python代码的调试方式 1. 使用print语句打印出来 2. 在编辑工具中,加断点跟踪(打断点) 3. 使用日志模块,输出到日志中 下面我们来看一下如何打断点 二. 环境 p...