9

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?

Mr. Developerdude
  • 9,118
  • 10
  • 57
  • 95
  • You want all routes: `favicon`, `faviconFOO`, `favicon_bar` etc. to point same handle, then you may look at this [thread](https://stackoverflow.com/questions/5870188/does-flask-support-regular-expressions-in-its-url-routing) – ZdaR Oct 17 '17 at 07:18
  • Yes exactly. If it was a wildcard it would be /favicon* – Mr. Developerdude Oct 17 '17 at 07:18
  • I would not say it's a duplicate because it is much more spesific than the other question. Besides, I don't care if it is solved using regex or not. – Mr. Developerdude Oct 17 '17 at 07:21
  • It can be perfectly solved with regex, I guess it would be the best way to reduce redundancy in this case(flask). However Django framework has more convenient support for regexs'. – ZdaR Oct 17 '17 at 07:31
  • please let me know if the answer did what you wanted if you found another way to do it. – senaps Oct 17 '17 at 11:05

1 Answers1

18

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

senaps
  • 1,374
  • 1
  • 14
  • 25