简体   繁体   中英

Flask-Classy gives a BuildError when using url_for to link to a function with a variable in the @route

So I have a view set up as such:

class toi(FlaskView):
    def index(self):
            ...
            return render_template('home.html')

    @route('/api/')
    @route('/api/<int:urlgid>/')
    @route('/api/<int:urlgid>/<int:urlper>/')
    def APIInstruction(self, urlgid=None, urlper=None):
        return render_template('toi-instructions.html')

And then in my main app.py I have

from views.toi import toi
toi.register(app)

And then in the HTML that toi:index is ouputting I have

... <a href="{{ url_for('toi:APIInstruction') }}">how to use the API</a>  ...

This gives me a BuildError (no further details) and I've been pulling my hair out trying to figure this out. If I remove the @routes the error goes away. If I get rid of the 2nd and 3rd @routes it does not give me a builderror. If I put the urlgid and urlper in the url_for() function it does not change anything. I've tried changing the endpoints, I've tried changing url_for to toi:api.

I am not sure what is wrong to cause this BuildError.

When you use multiple routes for a single view, what happens is multiple endpoints get created (one for each route). In order to help you distinguish between each endpoint, Flask-Classy will append an index to the end of the expected route name. The order is from 0 to n starting from the last route defined. So given your example:

@route('/api/') # use: "toi:APIInstruction_2"
@route('/api/<int:urlgid>/') # use: "toi:APIInstruction_1"
@route('/api/<int:urlgid>/<int:urlper>/') # use: "toi:APIInstruction_0"
def APIInstruction(self, urlgid=None, urlper=None):
    return render_template('toi-instructions.html')

You can read more about this behavior here: http://pythonhosted.org/Flask-Classy/#using-multiple-routes-for-a-single-view

Alternatively (this is the method I prefer) you can specify the endpoint you want to use explicitly in any @route decorator. For example:

@route('/api/', endpoint='apibase')

Will be accessible using:

url_for('apibase')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM