Problem checking an existing browser cookie

Peter Otten __peter__ at web.de
Mon Aug 30 12:21:09 EDT 2010


Nik the Greek wrote:

>> Perhpas its doenst get loaded like that?
>>
>> # initialize cookie
>> cookie = SimpleCookie()
>> cookie.load( os.environ.get('HTTP_COOKIE', '') )
>> mycookie = cookie.get('visitor')
> 
> Please someone else has an idea on how this to work?

Add a print statement to verify that HTTP_COOKIE does indeed have a visitor.
Or use the stuff below as a template.

Here is a minimal script to set the visitor:

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

import cgi
import Cookie
import os
import sys

form = cgi.FieldStorage()
name = form.getfirst("name", "Unknown")

cookie = Cookie.SimpleCookie()
cookie["visitor"] = name

sys.stdout.write(cookie.output())
sys.stdout.write("\r\nContent-type: text/plain\r\n\r\n")
print "Hello, your new name is", name

Invoke it with the equivalent of 

http://localhost:8000/cgi-bin/set_visitor.py?name=Nikos

for your website. Then proceed with a small script to show the visitor's 
name:

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

import cgi
import Cookie
import os
import sys

cookie = Cookie.SimpleCookie()
cookie.load(os.environ.get("HTTP_COOKIE"))

visitor = cookie.get("visitor")
if visitor is None:
    visitor_name = "Unknown"
else:
    visitor_name = visitor.value

sys.stdout.write("Content-type: text/plain\r\n\r\n")
print "Hello,", visitor_name
print
print
print "HTTP_COOKIE=%r" % os.environ.get("HTTP_COOKIE")

which you can invoke with the equivalent of

http://localhost:8000/cgi-bin/show_visitor.py

With some luck you should see your name and can proceed to adapt your script 
accordingly.

Peter



More information about the Python-list mailing list