-1

I am trying to write a script in python which uses the Cookie library to set cookies. I have written the following method:

import uuid
import Cookie
import sys
import os

def send_cookie(key, value, max_age):
    cookie = Cookie.SimpleCookie()
    cookie[key]=value
    cookie[key]['max-age']=max_age
    print cookie.output()

The problem is when I call this method multiple times for example, send_cookie('foo',123,1000), send_cookie('foo2',12345,1000). I would 'assume' that these cookies are stored onto my computer. When I print the os.environ['HTTP_COOKIE'], I dont't see any of the cookies I set in there.

1 Answer 1

0

No, the Cookie module only helps you model the abstract concept of a cookie, and perhaps generate Set-Cookie headers. An additional module cookielib can handle collections of cookies, but neither will set a HTTP_COOKIE environment header.

The documentation is quite clear on this:

The Cookie module defines classes for abstracting the concept of cookies, an HTTP state management mechanism. It supports both simple string-only cookies, and provides an abstraction for having any serializable data-type as cookie value.

The HTTP_COOKIE environment variable is something a CGI server would set based on an incoming HTTP request. You certainly could generate such an environment variable from the Cookie object, but the act of creating such an object does not affect the environment on its own.

If you are actually using this function in a CGI script, then the cookie.output() should be part of the HTTP headers; make sure you haven't already sent the double line separator signalling to the CGI server that your headers are done.

6
  • But when I print the cookie.output(), wouldn't my browser store that cookie.
    – user136638
    Commented Jun 14, 2014 at 16:23
  • And the next time I open the script, my browser should pass that stored cookie into os.environ['HTTP_COOKIE']?
    – user136638
    Commented Jun 14, 2014 at 16:23
  • @user136638: Not unless you send that output to your browser as a HTTP response. Commented Jun 14, 2014 at 16:24
  • @user136638: if a browser has received a valid cookie, then the browser will follow the normal cookie rules and send it back to the origin server, yes. Commented Jun 14, 2014 at 16:25
  • @user136638: but your question doesn't have any context to show that you are actually interacting with a browser through a CGI script. Commented Jun 14, 2014 at 16:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.