为变量URL指定转换器时,为什么我的Flask路由列表功能失败?

时间:2015-02-03 16:18:37

标签: python flask url-routing

我有一个函数,用于列出我的Flask应用程序支持的路由

# test.py
import urllib
import flask

def routes(verbose):
    """List routes supported by the application"""
    output = []

    for rule in app.url_map.iter_rules():
        if rule.endpoint == 'static':
            continue
        options = {arg: "[{0}]".format(arg) for arg in rule.arguments}
        url = flask.url_for(rule.endpoint, **options)
        if verbose:
            line = "{:35s} {:25s} {}".format(urllib.unquote(url), rule.endpoint, ','.join(rule.methods))
        else:
            line = "{}".format(urllib.unquote(url))
        output.append(line)

    for line in sorted(output):
        print(line)

但是,如果我有一个功能,我已经为URL的variable part指定了转换器,例如

@app.route('/plot/<int:xyrange>')
def plot(xyrange=10):
    ...

我得到了

File "test.py", line 55, in routes
    url = flask.url_for(rule.endpoint, **options)
  File "/usr/local/lib/python2.7/site-packages/flask/helpers.py", line 305, in url_for
    force_external=external)
  File "/usr/local/lib/python2.7/site-packages/werkzeug/routing.py", line 1648, in build
    rv = self._partial_build(endpoint, values, method, append_unknown)
  File "/usr/local/lib/python2.7/site-packages/werkzeug/routing.py", line 1570, in _partial_build
    append_unknown)
  File "/usr/local/lib/python2.7/site-packages/werkzeug/routing.py", line 1578, in _partial_build
    rv = rule.build(values, append_unknown)
  File "/usr/local/lib/python2.7/site-packages/werkzeug/routing.py", line 718, in build
    add(self._converters[data].to_url(values[data]))
  File "/usr/local/lib/python2.7/site-packages/werkzeug/routing.py", line 930, in to_url
    value = self.num_convert(value)
ValueError: invalid literal for int() with base 10: '[xyrange]'

为什么我会收到此错误,如何避免错误?

1 个答案:

答案 0 :(得分:3)

是的,你唯一应该做的就是检查变量类型以避免这种情况。

请参阅:

ValueError: invalid literal for int() with base 10: '[xyrange]'

你必须传入一个变量:'[xyrange]'。它是一个字符串。

您将url端点参数的类型调整为integer,但您传入了其他类型。我们都知道int方法不能将字符串更改为整数。

因此,请在redirect之前检查您的参数类型,如果您无法确认参数的类型,请不要使用@app.route('xxx/<int:xxxx>'),伙伴。< / p>