Flask装饰器如何有参数? [英] How can a Flask decorator have arguments?

查看:203
本文介绍了Flask装饰器如何有参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个方法实现了一个装饰器

,但问题仍然未解决...



我用装饰器有这个功能

$ $ $ $ c $ @ blueprint.route('< var>)
@ blueprint.my_decorator(var)
def function(var):
do stuff

我得到这个错误

$ p $ NameError:没有定义全局名称'var'

如何解决这个问题?




更新

蓝图是继承Blueprint类的类。
所以我实现了这个方法:
$ b

def my_decorator(self,fn):
@wraps(fn)
def decorator(* args,** kwargs):
value = kwargs ['value']
#做东西的值
return fn( * args,** kwargs)
返回装饰器

但值仍然是一个未知的键...

解决方案

装饰器在导入时执行,它们基本上是语法糖:

  @foo(bar)
def baz():
return'w00t!'

相当于

$ $ $ code> def baz()
return'w00t!'
baz = foo(bar)(baz)

所以在上面的例子中,变量 bar 必须存在于这个模块的全局范围中,然后才作为参数传递给装饰器。这就是你得到的错误告诉你的。






更新



根据下面的讨论,问题中的代码应该拦截传递给view函数的值,并用它做一些事情。下面是一个演示它的例子:

  from functools导入包装
从瓶子导入瓶子,中止

app = Flask(__ name__)

def foobar(fn):
@wraps(fn)
def decorated_view(* args,** kwargs):
value = kwargs ['value']
#做一些有价值的事情...
if value =='foobar':
abort(400)
return fn(* args ,** kwargs)
return decorated_view

@ app.route('/< value>)
@foobar
def view(value):
返回值


I implemented a decorator in the same way as here How to make a python decorator function in Flask with arguments (for authorization) but problem still unsolved...

I have this function with decorators

@blueprint.route('<var>')
@blueprint.my_decorator(var)
def function(var):
    do stuff

and I get this error

NameError: global name 'var' is not defined

How do I solve this?


Update

The blueprint is a class inheriting the Blueprint class. So I implemented the method

def my_decorator(self, fn):
    @wraps(fn)
    def decorator(*args, **kwargs):
        value = kwargs['value']
        # do stuff with value
        return fn(*args, **kwargs)
    return decorator

but still the value is an uknown key...

解决方案

Decorators are executed at import time, they're essentially syntactic sugar:

@foo(bar)
def baz():
    return 'w00t!'

is equivalent to

def baz():
   return 'w00t!'
baz = foo(bar)(baz)

So in the example above variable bar must exist in the global scope of this module before it is passed to the decorator as argument. That's what the error you've got tells you.


Update

Based on the discussion below, the code in the question should intercept the value passed to view function and do something with it. Here's an example that demonstrates it:

from functools import wraps
from flask import Flask, abort

app = Flask(__name__)

def foobar(fn):
    @wraps(fn)
    def decorated_view(*args, **kwargs):
        value = kwargs['value']
        # Do something with value...
        if value == 'foobar':
            abort(400)
        return fn(*args, **kwargs)
    return decorated_view

@app.route('/<value>')
@foobar
def view(value):
    return value

这篇关于Flask装饰器如何有参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆