Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise 404 if Flask catch-all route starts with prefix

Tags:

python

flask

I am using the catch-all url pattern in my Flask route. I want the view to ignore (throw a 404 error) any path that starts with /api. How can I do this?

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
    return 'Hello, World!'
like image 947
Vlad Lazar Avatar asked Mar 03 '17 13:03

Vlad Lazar


People also ask

How does Python handle 404 error Flask?

To handle 404 Error or invalid route error in Flask is to define a error handler for handling the 404 error. @app. errorhandler(404) def invalid_route(e): return "Invalid route." Now if you save the changes and try to access a non existing route, it will return “Invalid route” message.

What does .route do in Flask?

App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. Example: In our application, the URL (“/”) is associated with the root URL.

What does 404 mean in Flask?

A 404 Error is showed whenever a page is not found. Maybe the owner changed its URL and forgot to change the link or maybe they deleted the page itself. Every site needs a Custom Error page to avoid the user to see the default Ugly Error page.


1 Answers

Check if the path starts with the prefix, then abort if it does.

from flask import abort

if path.startswith('api'):
    abort(404)
like image 133
davidism Avatar answered Oct 06 '22 15:10

davidism