V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
killpanda
V2EX  ›  Python

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

  •  
  •   killpanda ·
    killpanda · 2012-11-26 22:57:43 +08:00 · 3907 次点击
    这是一个创建于 4181 天前的主题,其中的信息可能已经有所发展或是发生改变。
    9 条回复    1970-01-01 08:00:00 +08:00
    BOYPT
        1
    BOYPT  
       2012-11-27 09:23:55 +08:00   ❤️ 1
    =.=b

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

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

    print "Content-type: text/plain"
    print cookie.output()
    print
    killpanda
        4
    killpanda  
    OP
       2012-11-27 10:50:46 +08:00
    @tsuibin
    @Livid
    @BOYPT

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

    这里有关于 Cookie 的细节:

    http://www.nczonline.net/blog/2009/05/05/http-cookies-explained/
    tsuibin
        8
    tsuibin  
       2012-11-28 10:12:39 +08:00   ❤️ 1
    取数据


    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
        9
    BOYPT  
       2012-11-28 12:59:29 +08:00
    @killpanda 所以你应该去看你的web server / framework的文档。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3541 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:23 · PVG 19:23 · LAX 04:23 · JFK 07:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.