I’m trying to add a cookie to a webpage using python’s Cookie so I have:
def cookie():
#create cookie1 and cookie2 here using Cookie.SimpleCookie()
print cookie1
print cookie2
print "Content-Type: text/html"
print
cookie()
try:
cookie= Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
user= cookie["user"].value
print user
except (Cookie.CookieError, KeyError):
print 'no cookie'
page= open('example.html', 'r').read()
print page
Now the problem is cookie1 and cookie2 are printed in the page itself and can be seen when the script is run. And thus the cookie is not saved and the ‘no cookie’ in except is printed. What am I doing wrong?
1- your code doesn’t make sense. cookie1 and cookie2 are not defined in the first function.
2- It looks like you’re trying to print stuff using the old cgi library, where you do headers, a blank line, then page content. Cookies are also sent as HTTP headers by the web server, and sent back as HTTP headers by the browser. They don’t appear on the web page. So you’d need to have the “set-cookie” data before the blank line.
Unless you have to use the CGI module, I’d look into other solutions. CGI is basically of dead – it’s an old , limiting, standard; it can be a huge hassle to configure the server; the performance was never great; and there are better options.
Most (if not all) modern web development with Python uses the WSGI protocol. ( How Python web frameworks, WSGI and CGI fit together , http://www.python.org/dev/peps/pep-0333/ )
Flask and Bottle are two very simple WSGI frameworks. (Pryamid and Django are two more advanced ones). Aside from a ton of very important features , they will allow you easily specify the HTML Response and the HTTP Headers ( including cookies ) that go along with it, before the framework passes on the payload to the server. This
http://flask.pocoo.org/docs/quickstart/
http://bottlepy.org/docs/dev/tutorial.html
if i had to use cgi though, i’d probably do something like this: ( pseudocode )
keep in mind though – with the old cgi standard, you print the headers than the html — which means if your content generation affects header values (like cookies), you need to be able to overwrite that before “printing”.