特殊装饰器
before_request、after_request
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | from flask import Flask,render_template,redirect app = Flask(__name__) """ before_reuqest = [xxxxxxxxxx1,xxxxxxxxxx2] """ @app .before_request def xxxxxxxxxx1(): print ( '前1' ) @app .before_request def xxxxxxxxxx2(): print ( '前2' ) """ after_request = [oooooooo1,oooooooo2] [oooooooo2,oooooooo1,] reversed(after_request) """ @app .after_request def oooooooo1(response): print ( '后1' ) return response @app .after_request def oooooooo2(response): print ( '后2' ) return response @app .route( '/x1' ,methods = [ 'GET' , 'POST' ]) def x1(): print ( '视图函数x1' ) return "视图函数x1" @app .route( '/x2' ,methods = [ 'GET' , 'POST' ]) def x2(): print ( '视图函数x2' ) return "视图函数x2" if __name__ = = '__main__' : app.__call__ app.run() |
before_request返回
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | from flask import Flask,render_template,redirect app = Flask(__name__) @app .before_request def xxxxxxxxxx1(): print ( '前1' ) return "不要再来烦我了" @app .before_request def xxxxxxxxxx2(): print ( '前2' ) @app .after_request def oooooooo1(response): print ( '后1' ) return response @app .after_request def oooooooo2(response): print ( '后2' ) return response @app .route( '/x1' ,methods = [ 'GET' , 'POST' ]) def x1(): print ( '视图函数x1' ) return "视图函数x1" @app .route( '/x2' ,methods = [ 'GET' , 'POST' ]) def x2(): print ( '视图函数x2' ) return "视图函数x2" if __name__ = = '__main__' : app.__call__ app.run() |
before_request实现用户登录
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 | from flask import Flask,render_template,redirect,request,session app = Flask(__name__) app.secret_key = 'asdfasdfasdf' @app .before_request def check_login(): if request.path = = '/login' : return None user = session.get( 'user_info' ) if not user: return redirect( '/login' ) @app .route( '/login' ,methods = [ 'GET' , 'POST' ]) def login(): return "视图函数x1" @app .route( '/index' ,methods = [ 'GET' , 'POST' ]) def index(): print ( '视图函数x2' ) return "视图函数x2" if __name__ = = '__main__' : app.run() |
errorhandler() 报错返回友好界面
01 02 03 04 | @app .errorhandler( 404 ) def error404(args): print (args) return "您访问的页面不存在或者走丢了,,,,,,%s" % (args) |
天道酬勤 循序渐进 技压群雄
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)