os.environ
dictionary:
from os import environ ip_address = environ.get('REMOTE_ADDR')
id=cust123
.www.amazon.co.uk
:
GET /index.html
HTTP/1.1 200 OK
Set-Cookie: id=cust123; path=/; domain=.amazon.co.uk
…
www.amazon.co.uk
again
(or the amazon.co.uk
domain)
GET /index.html
Cookie: id=cust123
HTTP/1.1 200 OK
Set-Cookie: id=cust123;
expires=Sun, 17-Jan-2040 19:14:07 GMT;
path=/; domain=.amazon.co.uk
…
HTTP/1.1 200 OK
Set-Cookie: id=cust123; path=/; domain=.amazon.co.uk
…
SimpleCookie
object, and print it:
from http.cookies import SimpleCookie cookie = SimpleCookie() cookie['id'] = 'cust123' cookie['id']['expires'] = 157680000 print(cookie) print('Content-Type: text/html') print()
environ
dictionary
SimpleCookie
object
with the cookie data, and then do things with that data
from os import environ from http.cookies import SimpleCookie cookie = SimpleCookie() http_cookie_header = environ.get('HTTP_COOKIE') if not http_cookie_header: # the client did not send a cookie else: cookie.load(http_cookie_header) # now you can do things with the cookie
count_visits_by_cookie.py
: a simple example#!/usr/local/bin/python3 from cgitb import enable enable() from os import environ from http.cookies import SimpleCookie cookie = SimpleCookie() http_cookie_header = environ.get('HTTP_COOKIE') if not http_cookie_header: cookie['num_visits'] = 1 else: cookie.load(http_cookie_header) if 'num_visits' not in cookie: cookie['num_visits'] = 1 else: cookie['num_visits'] = int(cookie['num_visits'].value) + 1 cookie['num_visits']['expires'] = 157680000 print(cookie) print('Content-Type: text/html') print() print(""" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Welcome!</title> </head> <body> <p> You have visited this page %s times. </p> </body> </html>""" % (cookie['num_visits'].value))