Flask 中编写含有参数的装饰器,该怎么传递参数?

2016-03-22 09:55:30 +08:00
 JhOOOn

比如:

def required ( x ):
    def decorator ( f ):
    	def wrapper (*args, **kws ):
            if x:
            	return f(*args, **kws)
            else:
            	abort
        return wrapper
    return decoator

@app.route('/')
@required(x)
def main():
	return

那么我访问, http ://localhost : 5000 时,如何像 required 传递参数呢? 可以直接通过在装饰器里获取参数吗?比如:

request.args.get('x')
4933 次点击
所在节点    Flask
6 条回复
strahe
2016-03-22 10:06:07 +08:00
可以直接通过在装饰器里获取参数,但是就没必要写带参数的装饰器了,因为你是在里面获取参数的,而不需要外面传进去,
strahe
2016-03-22 10:08:36 +08:00
可以把
x = request.args.get('x')
写到 wrapper 里面,把最面外那一层去掉,
也可以在调用 required 时传入:
`@required(x)`
Mithrandir
2016-03-22 10:20:40 +08:00
直接这么写不久行了?

@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
hahastudio
2016-03-22 10:38:19 +08:00
如果你想自定义参数的话,可以试试
https://gist.github.com/hahastudio/426a750fb4c7a4beb210
JhOOOn
2016-03-22 10:41:02 +08:00
@strahe 恩,在装饰器里直接调用 request ,我正在尝试。请问,如果直接 Get ‘ localhost : 5000 ’,如何把参数传到装饰器里面去呢?
strahe
2016-03-22 14:01:21 +08:00
@JhOOOn 不需要传啊 直接在装饰器里用 request.args.get 就 ok

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/265346

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX