浏览文章
文章信息
Python 带回调函数的装饰器 | 装饰器回调函数作为参数 | 高度定制 | Flask
14361
1、以flask登陆检测作为示例
from functools import wraps from flask import session, g, jsonify def login_required(callback=None, *args_, **kwargs_): def wrapper(func): def decorated_view(*args, **kwargs): user_id = session.get('user_id') if user_id is not None: g.user_id = user_id return func(*args, **kwargs) else: if callback: return callback(*args_, **kwargs_) return jsonify(errno='403', errmsg='用户未登录') return decorated_view return wrapper用法:
def not_login_callback(): """ 未登录回调 :return: """ return '403' @app.route('/upload', methods=['GET', 'POST']) @login_required(not_login_callback) def upload(): """ 上传文件:需要验证登录,未登录需要跳转登录 :return: """ from WEB.router.file import upload app.config['UPLOAD_FOLDER'] = upload.UPLOAD_FOLDER return upload.upload_file('file/upload-form.html')完毕!