Cookie.py troubles.

B

Ben Hearsum

I'm confused about the way Cookie.load outputs cookies. Is there a way I
can tell it to give me the value of a key?

I set my cookie like this:

mycookie = Cookie.SimpleCookie()
mycookie['key'] = "foobar"

print mycookie
print("Content-Type: text/html\n\n")
print("meow")

Now, to retrieve it, the documentation says I parse the HTTP_COOKIE
environment variable. Makes sense to me. But when I print it out I get
"Set-Cookie: key=foobar;". I was thinking of parsing it with cgi.parse_qs,
but even if i do print(mycookie.output(header="")) there's still a ; at
the end of the cookie.

Here's what I use to print them out:

cookie = Cookie.SimpleCookie()
cookie.load(os.environ['HTTP_COOKIE'])

print("Content-Type: text/html\n\n")
print(mycookie.output(header=""))

Output:

key=foobar;


Can anyone provide any advice?

- Ben Hearsum
 
J

John J. Lee

Ben Hearsum said:
I set my cookie like this:

mycookie = Cookie.SimpleCookie()
mycookie['key'] = "foobar"

print mycookie
print("Content-Type: text/html\n\n")
print("meow")

Now, to retrieve it, the documentation says I parse the HTTP_COOKIE
environment variable. Makes sense to me. But when I print it out I get
"Set-Cookie: key=foobar;". I was thinking of parsing it with cgi.parse_qs,
but even if i do print(mycookie.output(header="")) there's still a ; at
the end of the cookie.

Why do you want to parse Set-Cookie if you're writing a CGI script?

Set-Cookie is what the server sends to the client. HTTP_COOKIE is set
by the server, not by Python, to the value than was sent by the client
to the server. I guess SimpleCookie has a __str__ method that makes
it print out Set-Cookie: key=foobar; -- seems like useful behaviour.
Here's what I use to print them out:

cookie = Cookie.SimpleCookie()
cookie.load(os.environ['HTTP_COOKIE'])

Yep, in comes the Cookie: header, I presume SimpleCookie parses it,
and then...

print("Content-Type: text/html\n\n")
print(mycookie.output(header=""))

You send the cookie back to the client again.

Output:

key=foobar;

This seems to contradict what you said before ("key=foobar;"
vs. "Set-Cookie: key=foobar;").



John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top