Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path routing in Flask

I want to run a Python CGI on a shared hosting environment. I followed Flask's example and came up with a tiny application as below:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

@app.route("/pi")
def pi():
    return "3.1416"

if __name__ == "__main__":
    app.run()

My .htaccess contains:

Options +ExecCGI 
AddHandler cgi-script .cgi .py .rb
DirectoryIndex index.cgi index.htm

And my index.cgi is

#!/usr/bin/env python
from wsgiref.handlers import CGIHandler
from firstflask import app

CGIHandler().run(app)

It successfully maps the path / to index(), however it fails to map the path /pi to pi(), instead returning a 404 error. I guess I miss something obvious. Thanks for the help.

like image 676
sdc Avatar asked Apr 02 '12 18:04

sdc


1 Answers

Comments about cgi vs. wsgi are valid, but if you really want to go with cgi setup, you need some rewriting rules in order to catch URLs other than "/" with the index.cgi. With your setup you basically say that index file is index.cgi, but in case there is something else in the path index.cgi won't get executed. This is why you get 404 Not Found for /pi request.

You can access the pi() function by requesting url /index.cgi/pi and it will successfully render you 3.1416, but obviously that is not a very nice URL. That gives a hint about what needs to be configured for rewriting though: rewrite all requests with / to /index.cgi/. This gives very simple rewrite rules together with your original configuration:

Options +ExecCGI
AddHandler cgi-script .cgi .py .rb
DirectoryIndex index.cgi index.htm

RewriteEngine On
RewriteRule ^index.cgi/(.*)$ - [S=1]
RewriteRule ^(.*)$ index.cgi/$1 [QSA,L]
like image 153
Jari Avatar answered Oct 18 '22 02:10

Jari