sdc
sdc

Reputation: 101

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.

Upvotes: 10

Views: 2437

Answers (2)

Ejaz
Ejaz

Reputation: 1632

Not sure if the above solution solved the query.

I think the .htaccess file needs to be this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*)$ /path/to/the/application.cgi/$1 [L]

It will work perfectly with this. I have tested with my code.

Reference - here

Upvotes: 0

Jari
Jari

Reputation: 2152

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]

Upvotes: 2

Related Questions