Python Flask装饰器登录验证
from flask import Flask,render_template,redirect,request,session
app = Flask(__name__)
app.secret_key = "sdfasdfasdf3fsdf"
@app.route('/')
def hello_world():
return 'Hello World!'
def wapper(func):
def inner(*args,**kwargs):
if not session.get('user_info'):
return redirect('/login')
return func(*args,**kwargs)
return inner
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == "GET":
return render_template('login.html')
else:
user = request.form.get('username')
pwd = request.form.get('password')
if user == 'alex' and pwd == '':
session['user_info'] = user
return redirect('/index')
else:
return render_template('login.html',msg='用户或密码错误')
@app.route('/index',methods=['GET'])
@wapper
def index():
return render_template('index.html')
@app.route('/query',methods=['GET'])
def query():
if not session.get('user_info'):
return redirect('/login')
return 'query'
@app.route('/student',methods=['GET'])
@wapper
def student():
return 'student'
if __name__ == '__main__':
app.run()
上面方面使用装饰器会有一个弊端:
"AssertionError: View function mapping is overwriting an existing endpoint function"如何解决
为什么会出现这样的问题:
使用Flask定义URL的时候,如果出现"AssertionError: View function mapping is overwriting an existing endpoint function"这个异常信息,就说明定义了多个同名的视图函数,只需要改成不同的函数名即可。
这是为什么呢? 原来flask中url跟视图函数并不是直接对应的,而是有一个中间者-endpoint。 三者之间的关系是这样的: ```
url---->endpoint---->view_function
``` 它们是一对一的关系,在注册add_url_rule的时候,如果不指定endpoint,那么endpoint就会默认为函数名字,如果同一个endpoint于多个url注册的话,就会发生冲突,从而抛出异常。
解决方法:
from flask import Flask,render_template,redirect,request,session
app = Flask(__name__)
app.secret_key = "sdfasdfasdf3fsdf"
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == "GET":
return render_template('login.html')
else:
user = request.form.get('username')
pwd = request.form.get('password')
if user == 'alex' and pwd == '':
session['user_info'] = user
return redirect('/index')
else:
return render_template('login.html',msg='用户或密码错误')
def wapper(func):
def inner(*args,**kwargs):
if not session.get('user_info'):
return redirect('/login')
return func(*args,**kwargs)
return inner
@app.route('/index',methods=['GET'],endpoint='index')
@wapper
def index():
return render_template('index.html')
@app.route('/query',methods=['GET'],endpoint='query')
@wapper
def query():
if not session.get('user_info'):
return redirect('/login')
return 'query'
@app.route('/student',methods=['GET'],endpoint='student')
@wapper
def student():
return 'student'
if __name__ == '__main__':
app.run()
解决方法
Python Flask装饰器登录验证的更多相关文章
- 如何用python的装饰器定义一个像C++一样的强类型函数
Python作为一个动态的脚本语言,其函数在定义时是不需要指出参数的类型,也不需要指出函数是否有返回值.本文将介绍如何使用python的装饰器来定义一个像C++那样的强类型函数.接下去,先介绍 ...
- 关于Python的装饰器(1)
Python的装饰器的概念,一直有点微妙.之前在StackOverflow上看过一篇感觉说明的很清楚的介绍: *A decorator must accept a function as an arg ...
- 浅谈Django的中间件与Python的装饰器
浅谈Django的中间件 与Python的装饰器 一.原理 1.装饰器是Python的一种语法应用,利用闭包的原理去更改一个函数的功能,即让一个函数执行之前先到另外一个函数中执行其他需求语句,在执行该 ...
- 使用 python 编写一个授权登录验证的模块
使用 python 编写一个授权登录验证的模块 我们编写的思路: 1.登录的逻辑:如果用户名和密码正确,就返回 token . 2.生成 token 的逻辑,根据用户名,随机数,当前时间 + 2 小时 ...
- 练习:python 操作Mysql 实现登录验证 用户权限管理
python 操作Mysql 实现登录验证 用户权限管理
- Python各式装饰器
Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义. 一.函数式装饰器:装饰器本身是一个函数. 1.装饰函数:被装饰对象是一个函数 [1]装饰器无参数: a.被装饰对象无参数: ...
- Python札记 -- 装饰器补充
本随笔是对Python札记 -- 装饰器的一些补充. 使用装饰器的时候,被装饰函数的一些属性会丢失,比如如下代码: #!/usr/bin/env python def deco(func): def ...
- python基础——装饰器
python基础——装饰器 由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数. >>> def now(): ... print('2015-3-25 ...
- 【转】详解Python的装饰器
原文链接:http://python.jobbole.com/86717/ Python中的装饰器是你进入Python大门的一道坎,不管你跨不跨过去它都在那里. 为什么需要装饰器 我们假设你的程序实现 ...
随机推荐
- BZOJ [Ctsc2002] Award 颁奖典礼 解题报告
[Ctsc2002] Award 颁奖典礼 Description IOI2002的颁奖典礼将在YONG-IN Hall隆重举行.人们在经历了充满梦幻的世界杯之后变得更加富于情趣.为了使颁奖典礼更具魅 ...
- POJ.2387 Til the Cows Come Home (SPFA)
POJ.2387 Til the Cows Come Home (SPFA) 题意分析 首先给出T和N,T代表边的数量,N代表图中点的数量 图中边是双向边,并不清楚是否有重边,我按有重边写的. 直接跑 ...
- noip模拟赛 helloworld
分析:对于第一个点,答案为26^n - 25^n,这个很好想.另外30%的点因为n <= 5,所以可以直接暴力搜索. 数学方法不是很好处理,考虑dp,设f[i][j]为前i位匹配到危险串第j位的 ...
- JavaScript知识之判断字符串中出现最多的字符及次数
var str = 'asdddasdfdseeeeeweeeeeeeeeeeee'; var json = {}; // 定义json一个对象 for(var i = 0; i < str.l ...
- EasyUI Tree递归方式获取JSON
最近需要用到EASYUI中的TREE功能,以前我是直接拼接成<UL><LI>发现这样拼完之后在更改树后对树的刷新不是很理想,现改用JSON格式,首先分析TREE中JOSN格式如 ...
- 【Android】完善Android学习(三:API 3.0)
备注:之前Android入门学习的书籍使用的是杨丰盛的<Android应用开发揭秘>,这本书是基于Android 2.2API的,目前Android已经到4.4了,更新了很多的API,也增 ...
- jenkins修改job默认名字
${GIT_BRANCH,fullName="false"}-${BUILD_NUMBER}-${GIT_REVISION,length=12}-${deploy_rollback ...
- mysql 并发下数据不一致的问题分析及解决
MySQL 5.6 , InnoDB存储引擎,默认事务隔离级别(REPEATABLE-READ) 初始sql 脚本如下: CREATE DEFINER=`root`@`localhost` PROCE ...
- bzoj 2200: [Usaco2011 Jan]道路和航线——拓扑+dijkstra
Description Farmer John正在一个新的销售区域对他的牛奶销售方案进行调查.他想把牛奶送到T个城镇 (1 <= T <= 25,000),编号为1T.这些城镇之间通过R条 ...
- 【LibreOJ】#538. 「LibreOJ NOIP Round #1」数列递推
[题意]LibreOJ [算法]乱搞 [题解]容易发现数列最后一定单调,最后单调递增则最大值赋为最后一个,反之最小值赋为最后一个,然后处理一些细节就可以AC,要注意以下几点: 1.数列连续三项以及数列 ...