I am writing a script in python using cgi package. I need to send response of either HTTP/1.1 200 OK\n or HTTP/1.1 404 Not Found\n based on some checks in my code. If I print one of the above line as the first line of my response my apache server logs an error and returns 500 Internal server error The relevant part of the error message logged in this case is malformed header from script 'helo.py': Bad header: HTTP/1.1 200 OK\n Can anyone guide me what am I doing wrong here.
2 Answers
Do you print only these lines? According to the CGI spec, you must define Content-Type.
print "Content-Type: text/html\r\n\r\n";
If you want to emit status, please use Status header instead (this is CGI, not HTTP header).
So
print "Status: 404 Not Found\r\n"
print "Content-Type: text/html\r\n\r\n"
This will do the trick.
Comments
Based on the answer of Sergey I would like to add that for Python 3 you just need the following:
print("Status: 404 Not Found")
print("Content-Type: application/json;charset=utf-8\n")
Minimal example to show that the above method works
#!/usr/bin/env python3
print("Status: 404 Not Found")
print("Content-Type: application/json;charset=utf-8\n")
print("Hello")
1 Comment
fangio
I use this code above but I always get 200 as Status. Do I need to enable or import something else to make this work? Because my code works if everything goes well, in other words if I always can return a 200 status and some json.dump, my code works
