pythonpython-3.xflaskpathapp-route

Flask app route for paths that start with X


I am a beginner with Flask and python. I want to create a handler function for paths that start with "/favicon". For example the following should be handled:

The following should not be handled:

If Flask supporeted wildcards, it would be "/favicon*"

EDIT: I don't need support for regular expressions.

How can I do this?


Solution

  • I would do a catch-all url and then, try to use a wildcard with it from inside the view:

    @app.route('/<path:text>', methods=['GET', 'POST'])
    def all_routes(text):
        if text.startswith('favicon'):
            #do stuff
        else:
            return redirect(url_for('404_error'))
    

    you can use string too:

    @app.route('/<string:text>', methods=['GET'])
    

    but using string wouldn't catch / strings. so if string is used, url's containing something like favicon/buzz wouldn't be cached by it, path in the other hand would catch /'s too. so you should go with first option.

    you can look at routing documentation in flask site. and you should create a better conditional than if x in Y because it will fail if you were passed something like /thingfavicon