Flask redirecting multiple routes

前端 未结 4 917
北恋
北恋 2021-01-30 10:49

I\'m trying to implement a redirecting pattern, similar to what StackOverflow does:

@route(\'///\')
@route(\'//\')
de         


        
4条回答
  •  不要未来只要你来
    2021-01-30 11:30

    You've almost got it. defaults is what you want. Here is how it works:

    @route('///')
    @route('//', defaults={'username': None})
    def profile(id, username):
        user = User.query.get_or_404(id)
    
        if username is None or user.clean_username != username:
            return redirect(url_for('profile', id=id, username=user.clean_username))
    
        return render_template('user/profile.html', user=user)
    

    defaults is a dict with default values for all route parameters that are not in the rule. Here, in the second route decorator there is no username parameter in the rule, so you have to set it in defaults.

提交回复
热议问题