Search code examples
pythoncgisetcookie

set cookie with cgi-python scripts


I'm trying to response from the server with a set-cookie header

my cgi script begins as follows

#!/usr/bin/env python

import json
from collections import defaultdict
import cgi
import cgitb; cgitb.enable()  # for troubleshooting
from MySQL import sql

form = cgi.FieldStorage()
mode = form.getvalue('mode')

print """Content-type: text/html\r\n"""
print """Set-Cookie: name=12345\r\n\r\n"""

However, when checking the response from the server on my Chrome..the debugger doesn't show any set-cookie header in the response part, and the set-cookie header is printed in the response part as part of the text, unlike the content-type header...

Any idea what I did wrong?

Thanks guys


Solution

  • The problem is that you are appending two newlines instead of one to the end of your "Content-Type" header, which is the standard separator between HTTP headers and body.

    You should instead be emitting \r\n at the end of each header value (as opposed to \n\n)

    When you are done emitting headers, you should print one extra \r\n to begin your message body.

    EDIT: Additionally, you should either be using sys.stdout.write(...) or appending a trailing comma to your print statement to avoid its inserting the implicit newline. E.g.,

    print "Header: Value\r\n",