But for some reason, my program is not assigning or recognising an
assigned cookie & outputing the line "You have been here x times". I
have gone over my code for like 2 hours now I cant figure out what is
going wrong??
Can you help me figure out whats wrong? I have my own cgi server that
just runs on my machine so its not that its the code to recognise/
assign a cookie
[code]#!/usr/bin/env python
import Cookie
import cgi
import os
HTML_template = """
<html>
<head>
</head>
<body>
<p> %s </p>
</body>
</html>
"""
def main():
# Web Client is new to the site so we need to assign a cookie to
them
cookie = Cookie.SimpleCookie()
cookie['SESSIONID'] = '1'
code = "No cookie exists. Welcome, this is your first visit."
if 'HTTP_COOKIE' in os.environ:
cookie = Cookie.SimpleCookie(os.environ['HTTP_COOKIE'])
# If Web client has been here before
if cookie.has_key('SESSIONID'):
cookie['SESSIONID'].value = int(cookie['SESSIONID'].value)
+1
code = "You have been here %s times." %
cookie['SESSIONID'].value
else:
cookie = Cookie.SimpleCookie()
cookie['SESSIONID'] = '1'
code = "I Have a cookie, but SESSIONID does not exist"
print "Content-Type: text/html\n"
print HTML_template % code
if __name__ == "__main__":
main()
[/code]
Hi,
You are confusing the cookie sent by the browser to the server - you
get it by os.environ['HTTP_COOKIE'] - and the one sent by the server
to the browser : it it sent in the response headers
You can change method main() like this :
def main():
# defaut cookie to send if web Client is new to the site
set_cookie = Cookie.SimpleCookie()
set_cookie['SESSIONID'] = 1
code = "No cookie exists. Welcome, this is your first visit."
if 'HTTP_COOKIE' in os.environ:
cookie = Cookie.SimpleCookie(os.environ['HTTP_COOKIE'])
if cookie.has_key('SESSIONID'):
# web client has been here before : increment number of
visits
set_cookie['SESSIONID'] = int(cookie['SESSIONID'].value)
+1
code = "You have been here %s times." %
cookie['SESSIONID'].value
else:
code = "I Have a cookie, but SESSIONID does not exist"
print "Content-Type: text/html"
print set_cookie.output() # send cookie to web client
print
print HTML_template % code
- Pierre