将一些任意值绑定到 Flask 中的路由

Bind some arbitrary value to route in Flask

如何优雅地绑定任意值和 flask 路由?假设,我想在我的会话接口实现或 before_request 挂钩中访问这个值。

现在我是这样做的:

@app.route('/foo/<bar>', defaults={'_my_val': True}):
def foo(bar, _my_val):  # this is ugly hack
    pass

并像这样通过请求对象访问这个值:

class MyRequest(flask.Request):
    def get_my_val(self):
        return (self.url_rule.defaults or {}).get('_my_val', False)

但它看起来像一个 hack。

UPD: 看起来可以通过扩展 werkzeug.routing.Rule class 并将 **kwargs 添加到其构造函数来完成。可以在烧瓶中覆盖规则 class 吗?

最终我最终覆盖了烧瓶的请求和规则类:

# here app is a Flask current application object
from flask import Request as FlaskRequest
from werkzeug.routing import Rule as FlaskRule

class Request(FlaskRequest):
    def is_foo(self):
        return bool(self.url_rule._foo) if self.url_rule else False

    def get_bar(self):
        return getattr(self.url_rule, '_bar')

class Rule(FlaskRule):
    def __init__(self, *args, **kwargs):
        for param in ('_foo', '_bar'):
            setattr(self, param, kwargs.pop(param, None))
        super().__init__(*args, **kwargs)

# app initialization
app.request_class = Request
app.url_rule_class = Rule

# route example        
@app.route('/path', _foo=True, _bar='baz')
def route():
    pass