python装饰器传参数_python flask如何将动态参数传递给装饰器

我正在使用python flask框架。我编写了一个需要一个参数的装饰器,该参数是动态的。

我的装饰器如下所示,将获得一个密钥,并使用该密钥从redis获取数据。

def redis_hash_shop_style(key):

def fn_wrapper(f):

@wraps(f)

def decorated_function(*args, **kwargs):

data = redis_hash(key)

return data

return decorated_function

return fn_wrapper

而且我有一个使用这种装饰器的类,像这样的代码

class ShopAreaAndStyleListAPI(Resource):

@redis_hash_shop_style(key='shop_{}_style'.format(g.city.id))

def get(self):

# if not found from redis, query from mysql

pass

如您所见,我的装饰器需要一个名为的参数key,然后像这样传递密钥

@redis_hash_shop_style(key='shop_{}_style'.format(g.city.id)) g.city.id

将获得城市的ID,如果一切正常,密钥将如下所示

shop_100_style

但我得到了错误:

class ShopAreaAndStyleListAPI(Resource):

File "xx.py", line 659, in ShopAreaAndStyleListAPI

@redis_hash_shop_style(key='shop_{}_style'.format(g.city.id))

File "/Users/xx/.virtualenvs/yy/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__

return getattr(self._get_current_object(), name)

File "/Users/xx/.virtualenvs/yy/lib/python2.7/site-packages/werkzeug/local.py", line 306, in _get_current_object

return self.__local()

File "/Users/xx/.virtualenvs/yy/lib/python2.7/site-packages/flask/globals.py", line 44, in _lookup_app_object

raise RuntimeError(_app_ctx_err_msg)

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that

needed to interface with the current application object in a way.

To solve this set up an application context with app.app_context().

See the documentation for more information.

我很困惑,在烧瓶中,如何将动态参数传递给装饰器?

谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值