Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask URL Route: Route All other URLs to some function

I am working with Flask 0.9. I have experience with Google App Engine.

  1. In GAE, the url match patterns are evaluated in the order they appear, first come first serve. Is it the same case in Flask?

  2. In Flask, how to write a url match pattern to deal with all other unmatched urls. In GAE, you only need to put /.* in the end, like: ('/.*', Not_Found). How to do the same thing in Flask since Flask wont support Regex.

like image 677
Gaby Solis Avatar asked Dec 24 '12 16:12

Gaby Solis


People also ask

Can you use multiple decorators to route URLs to a function in Flask?

The decorator syntax is just a little syntactic sugar. This code block shows an example using our custom decorator and the @login_required decorator from the Flask-Login extension. We can use multiple decorators by stacking them.

What does .route do in Flask?

Routing in Flask The route() decorator in Flask is used to bind an URL to a function. As a result when the URL is mentioned in the browser, the function is executed to give the result.

How do I redirect a route in Flask?

Flask – Redirect & ErrorsFlask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. location parameter is the URL where response should be redirected. statuscode sent to browser's header, defaults to 302.


2 Answers

This works for your second issue.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'This is the front page'

@app.route('/hello/')
def hello():
    return 'This catches /hello'

@app.route('/')
@app.route('/<first>')
@app.route('/<first>/<path:rest>')
def fallback(first=None, rest=None):
    return 'This one catches everything else'

path will catch everything until the end. More about the variable converters.

like image 53
justinas Avatar answered Sep 20 '22 09:09

justinas


  1. I think this is the answer http://flask.pocoo.org/docs/design/#the-routing-system
  2. If you need to handle all urls not found on server — just create 404 hanlder:

    @app.errorhandler(404)
    def page_not_found(e):
        # your processing here
        return result
    
like image 35
cleg Avatar answered Sep 17 '22 09:09

cleg