在before_request信号触发之前,Flask命中装饰器

NFi*_*ano 9 python decorator flask

我正在使用Flask并使用before_request装饰器将有关请求的信息发送到分析系统.我现在正在尝试创建一个装饰器,以防止在几条路线上发送这些事件.

我遇到的问题是让我的装饰器在before_request信号被触发之前被调用.

def exclude_from_analytics(func):

    @wraps(func)
    def wrapped(*args, **kwargs):
        print "Before decorated function"
        return func(*args, exclude_from_analytics=True, **kwargs)

    return wrapped

# ------------------------

@exclude_from_analytics
@app.route('/')
def index():
    return make_response('..')

# ------------------------

@app.before_request
def analytics_view(*args, **kwargs):
    if 'exclude_from_analytics' in kwargs and kwargs['exclude_from_analytics'] is True:
       return
Run Code Online (Sandbox Code Playgroud)

Mar*_*eth 14

你可以使用装饰器简单地在函数上放置一个属性(在下面的例子中,我_exclude_from_analytics用作属性).我使用request.endpointapp.view_functions的组合找到了view函数.

如果在端点上找不到该属性,则可以忽略分析.

from flask import Flask, request

app = Flask(__name__)

def exclude_from_analytics(func):
    func._exclude_from_analytics = True
    return func

@app.route('/a')
@exclude_from_analytics
def a():
    return 'a'

@app.route('/b')
def b():
    return 'b'

@app.before_request
def analytics_view(*args, **kwargs):
    # Default this to whatever you'd like.
    run_analytics = True

    # You can handle 404s differently here if you'd like.
    if request.endpoint in app.view_functions:
        view_func = app.view_functions[request.endpoint]
        run_analytics = not hasattr(view_func, '_exclude_from_analytics')

    print 'Should run analytics on {0}: {1}'.format(request.path, run_analytics)

app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

输出(忽略静态文件......)

Should run analytics on /a: False
127.0.0.1 - - [24/Oct/2013 15:55:15] "GET /a HTTP/1.1" 200 -
Should run analytics on /b: True
127.0.0.1 - - [24/Oct/2013 15:55:18] "GET /b HTTP/1.1" 200 -
Run Code Online (Sandbox Code Playgroud)

我没有测试过看蓝图是否有用.此外,包装并返回NEW函数的装饰器可能导致此操作无效,因为该属性可能被隐藏.