Adam Glassman
Adam Glassman

Reputation: 163

How can I override the static file handler in Flask?

Specifically, how can I assign a new handler to the "static" endpoint? I know I can change the static_folder and static_path, but I specifically want to assign a different function to handle requests of any url that are routed to the "static" endpoint in the routing map. I've tried assigning an empty werkzeug.routing.Map to the <Flask app>.url_map but to no avail - I still get an error ("View function mapping is overwriting an existing endpoint function: static") when attempting to add_url_rule.

Thanks in advance.

Upvotes: 16

Views: 6690

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121366

Set static_folder to None to prevent Flask from registering the view:

app = Flask(static_folder=None)

Now you are free to create your own.

Alternatively, have the static view use a different URL path, and give your alternative a different endpoint name:

app = Flask(static_url_path='/flask_static')

@route('/static/<path:filename>')
def my_static(filename):
    # ...

Flask will always use the endpoint name static for the view it creates, so the above uses my_static instead.

Upvotes: 40

Related Questions