Why doesn't the Flask route list function work when I specify a converter for URL variables?

I have a function that I used to list the routes supported by my flash application

# 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)

But if I have a function where I specified a converter for the variable part of the URL, for example

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

I get

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]'

Why am I getting this error and how to avoid it?

+4
source share
1 answer

Yes, the only thing you need to do is check the type of the variable to avoid this.

cm

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

you had to pass a variable: '[xyrange]'. And this is the line.

url integer, . , int .

, redirect, , @app.route('xxx/<int:xxxx>'), .

+3

All Articles