Flask app route for paths that start with X

Lennart Rolland picture Lennart Rolland · Oct 17, 2017 · Viewed 11.4k times · Source

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:

  • /favicon
  • /faviconFOO
  • /favicon_bar
  • /favicon/buzz
  • /favicon1337

The following should not be handled:

  • /favico
  • /favicoN
  • /whatever

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

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

How can I do this?

Answer

senaps picture senaps · Oct 17, 2017

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