Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch all path in flask app

I writing an app in Angular + Flask hosted on heroku. I've been looking to use html5mode to use myapp.co/register for oauth. The problem with html5mode is that server needs to rewrite url if someone refreshes the page or clicks the link that is not root. I tried to use this snippet to catch them all, but it doesn't work.

@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def index(path):
  print path
  return make_response(open(app.static_folder + "index.html").read())

output 404

 * Restarting with reloader
127.0.0.1 - - [23/Jan/2014 13:41:48] "GET /ass HTTP/1.1" 404 -

App got root that servers index.html and /api/v1/ that is RESTful api

like image 271
Lukasz Madon Avatar asked Jan 23 '14 13:01

Lukasz Madon


2 Answers

You need to use something more than you have:

@app.route("/", defaults={"path": ""})
@app.route("/<string:path>") <--- this is missing
@app.route("/<path:path>")
def index(path):
  print path
  return make_response(open(app.static_folder + "index.html").read())

So:

@app.route("/<string:path>")

is missing. It catches string variables (not path), so in your case just ass from your example, when you try to hit http://localhost:5000/ass.

like image 157
turkus Avatar answered Oct 02 '22 04:10

turkus


Your code will catch all urls if you do not have any more routes with more highest priority. But look like it should return 500 error (because I hope you do not have <app_path>/staticindex.html and use unsafe method to send file).

So if you have another rules you must look at rule priority (see https://stackoverflow.com/a/17146563/880326).

If you have error with this route better use:

@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def index(path)
    return send_from_directory(app.static_folder, "index.html")
like image 30
tbicr Avatar answered Oct 02 '22 04:10

tbicr