2

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 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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")

enter image description here

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.