Search code examples
pythonapacheflaskwebserverfastcgi

Python flask & fast-cgi on apache - 500 Internal Server Error (Premature end of script headers)


I want to setup my flask app on an apache prodcution server. I have created the following .htaccess file:

<IfModule mod_fcgid.c>
   AddHandler fcgid-script .fcgi
   <Files ~ (\.fcgi)>
       SetHandler fcgid-script
       Options +SymLinksIfOwnerMatch +ExecCGI
   </Files>
</IfModule>

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^(.*)$ /fcgi-bin/runFlaskApp.fcgi/$1 [QSA,L]
</IfModule>

Which should redirect to the following fcgi file (set to chmod 755):

#!/usr/bin/env python2.7
# -*- coding: UTF-8 -*-

RELATIVE_WEB_URL_PATH = '/app_dict'

import os
# This points to the application on the local filesystem.
LOCAL_APPLICATION_PATH = os.path.expanduser('~') + '/html/app_dict'
import sys
sys.path.insert(0, LOCAL_APPLICATION_PATH)

from flup.server.fcgi import WSGIServer
from tmain import app


class ScriptNamePatch(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        environ['SCRIPT_NAME'] = RELATIVE_WEB_URL_PATH
        return self.app(environ, start_response)

app = ScriptNamePatch(app)

if __name__ == '__main__':
    WSGIServer(app).run()

Which in return should start the following flask app:

#!/usr/bin/env python2.7
# -*- coding: utf8 -*-

from flask import Flask
app = Flask(__name__)

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

But when I try to access the website, an Internal Server Error 500 is shown. And the following lines show up in the apache error log:

[warn] [client 0.0.0.0] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server
[error] [client 0.0.0.0] Premature end of script headers: runFlaskApp.fcgi

If I run the fcgi file with"python2.7 runFlaskApp.fcgi" it returns the following:

WSGIServer: missing FastCGI param REQUEST_METHOD required by WSGI!
WSGIServer: missing FastCGI param SERVER_NAME required by WSGI!
WSGIServer: missing FastCGI param SERVER_PORT required by WSGI!
WSGIServer: missing FastCGI param SERVER_PROTOCOL required by WSGI!
Status: 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 12

Hello World!

I belive the header errors are because it´s not run in the context of an WSGIServer.

I already tried to provoke an exception in the flask app by adding a wrong formated line of code. But no exception shows up in the apache error log. This lead me to belive that the flask app isnt´t even loaded by the fcgi script.

Is there a way to debug this any further, or does anyone know a solution to this problem?


Solution

  • The problem was with the rights or line endings of the fcgi file. Uploading it from Windows to the server and setting chmod 755 dosn´t work. Only creating the file on the server and then running chmod 755 worked for me.