Flask and FastCGI

software development

#1

I’m trying to run Flask with FastCGI. (The wiki indicates that Passenger would want to take over my whole domain, and I cannot do that.) I can verify that FastCGI is working for my domain, using a Flup-based application:

http://vzome.com/reg/foo.fcgi

The equivalent for Flask, however, does not work. Here is the source I’m using.

from flask import Flask
app = Flask(__name__)

@app.route('/reg/hello.fcgi')
def hello_world():
    print( 'hello_world called' )
    return 'Yet Another Hello World!'

if __name__ == '__main__':
    hello_world()

Launching it from the command line works fine. I really don’t understand how the Flask routing interacts with the FastCGI configuration. How can the app.route call have any effect, when FastCGI has already dispatched to this script? Can anyone enlighten me? Does the routing assume that all requests are directed to this app, via .htaccess?


#2

I recently set up Flask through FastCGI and some trouble, but did manage to get it working. From what I recall the naming of your fcgi script file is important. I had to name mine literally “dispatch.fcgi” or it wouldn’t work. I have everything sitting in a subdirectory, “stout”, on my domain.

Here’s my .htaccess file:

[code]RewriteEngine On

RewriteRule ^dispatch.fcgi/ - [L]
RewriteRule ^(.*)$ dispatch.fcgi/$1 [L][/code]

And my dispatch.fcgi:

[code]#!/home/dmertl/dmertl.com/stout/venv/bin/python
from flup.server.fcgi import WSGIServer
from web import app

if name == ‘main’:
WSGIServer(app).run()[/code]

The rest of the setup is a standard Flask app with two packages. The web package runs the pages. The app is defined in the init.py for the package:

[code]$ cat web/init.py
from flask import Flask
app = Flask(name)

import views[/code]

As to your question for the app.route call, all of Flask’s routing is handled internally. FastCGI always calls the same script (dispatch.fcgi in my case), then internally Flask will call the appropriate view method in your app. Here’s an example from my views.py file for the home page:

@app.route('/') def home(): return render_template('home.html')

Flask matches up the request URL “/” to the app.route() I have defined and then calls the home() method.