9
votes

I want to run python code in apache2(ubuntu 14.04) server. I have followed these steps and getting Error:

Step 1:

Configuration 1: I have created a directory and file under

/var/www/cgi-bin

Configuration 2 : I have edited /etc/apache2/sites-available/000-default.conf

Alias /cgi-bin /var/www/cgi-bin
<Directory "/var/www/cgi-bin">
Options Indexes FollowSymLinks ExecCGI
AddHandler cgi-script .cgi .py
Allow from all
</Directory>

<Directory /var/www/cgi-bin>
Options All
</Directory>

Step 2:

and my python script is: index.py

#!/usr/bin/env python
import cgi;
import cgitb;cgitb.enable()

print "Content-Type: text/plain\n"

print "<b>Hello python</b>"

step 3:

When i ran through chrome browser using: URL : http://localhost/cgi-bin/index.py

step 4:

I am getting this Error in error-log

malformed header from script 'index.py': Bad header: Hello Python
3

3 Answers

17
votes

You should end your header with \r\n, then you must print out yet another \r\n to signal that the body is coming.

(In other words, it's interpreting your body as a Header because the headers were never terminated)

12
votes

Try this script

#!/usr/bin/env python
import cgi;
import cgitb;cgitb.enable()

print "Content-Type: text/html"
print "" #use this double quote print statement to add a blank line in the script
print "<b>Hello python</b>"

There should be one line space between header and main html content. That's why we have to use extra print statement before starting html tags in script.

1
votes

I had this issue with the flush mechanism when you need to print a file. This code responds to a http request if it is called via e.g. apache2.

import sys

print("Content-type: image/png", end="\r\n\r\n", flush=True)
sys.stdout.buffer.write(bytes(open("file.png","rb").read()))

end="\r\n\r\n" adds an empty line to begin the body

flush=True forces python to print the lines as intended. In my case, the header was printed wrong.