Python Server 端最简单获取 Cookie 的方法是?

2012 年 11 月 26 日
 killpanda
4421 次点击
所在节点    Python
9 条回复
BOYPT
2012 年 11 月 27 日
=.=b

Cookies是浏览器作为Header发给http服务器的。
一般web框架都会带了getCookies方法,一般是request对象的,各个框架都大同小异。(和python一点关系都没有)
Livid
2012 年 11 月 27 日
Cookie 就是客户端发送的请求中 Set-Cookie: 后面的那一行,用 urlencode 方式编码的一个字典。
tsuibin
2012 年 11 月 27 日
import Cookie
cookie = Cookie.SimpleCookie()

cookie["uname"]= "demo"
cookie["pwd"] = "demo"

print "Content-type: text/plain"
print cookie.output()
print
killpanda
2012 年 11 月 27 日
@tsuibin
@Livid
@BOYPT

感谢,目前手头的这个东西用的是 Paste Web Server。感觉对我这样的初学者来说,弄起来太费力了。目前就是想在服务器端把浏览器里的 Cookie 取出来,可是依然做不到。
sNullp
2012 年 11 月 27 日
@Livid cookie不是urlencode(dict)出来的吧,分隔符是;不是&
sNullp
2012 年 11 月 27 日
@Livid 另外Set-Cookie: 是服务端发送的,客户端发送的应该是Cookie:
Livid
2012 年 11 月 27 日
对,@sNullp 的解答更准确。

这里有关于 Cookie 的细节:

http://www.nczonline.net/blog/2009/05/05/http-cookies-explained/
tsuibin
2012 年 11 月 28 日
取数据


import Cookie
import os

print "Content-type: text/plain\n"

try:
cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])

print "name= " + cookie["name"].value
print "pwd= " + cookie["pwd"].value
except (Cookie.CookieError, KeyError):
print "cookie not set!"
BOYPT
2012 年 11 月 28 日
@killpanda 所以你应该去看你的web server / framework的文档。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/53378

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX