V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
JhOOOn
V2EX  ›  Flask

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

  •  
  •   JhOOOn · 2016-03-22 09:55:30 +08:00 · 4915 次点击
    这是一个创建于 2951 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如:

    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')
    
    6 条回复    2016-03-22 14:01:21 +08:00
    strahe
        1
    strahe  
       2016-03-22 10:06:07 +08:00
    可以直接通过在装饰器里获取参数,但是就没必要写带参数的装饰器了,因为你是在里面获取参数的,而不需要外面传进去,
    strahe
        2
    strahe  
       2016-03-22 10:08:36 +08:00
    可以把
    x = request.args.get('x')
    写到 wrapper 里面,把最面外那一层去掉,
    也可以在调用 required 时传入:
    `@required(x)`
    Mithrandir
        3
    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
        4
    hahastudio  
       2016-03-22 10:38:19 +08:00
    如果你想自定义参数的话,可以试试
    https://gist.github.com/hahastudio/426a750fb4c7a4beb210
    JhOOOn
        5
    JhOOOn  
    OP
       2016-03-22 10:41:02 +08:00
    @strahe 恩,在装饰器里直接调用 request ,我正在尝试。请问,如果直接 Get ‘ localhost : 5000 ’,如何把参数传到装饰器里面去呢?
    strahe
        6
    strahe  
       2016-03-22 14:01:21 +08:00
    @JhOOOn 不需要传啊 直接在装饰器里用 request.args.get 就 ok
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2589 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:30 · PVG 12:30 · LAX 21:30 · JFK 00:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.