推荐学习书目
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 · Nov 26, 2012 · 4591 views
    This topic created in 4940 days ago, the information mentioned may be changed or developed.
    9 replies    1970-01-01 08:00:00 +08:00
    BOYPT
        1
    BOYPT  
       Nov 27, 2012   ❤️ 1
    =.=b

    Cookies是浏览器作为Header发给http服务器的。
    一般web框架都会带了getCookies方法,一般是request对象的,各个框架都大同小异。(和python一点关系都没有)
    Livid
        2
    Livid  
    MOD
    PRO
       Nov 27, 2012   ❤️ 1
    Cookie 就是客户端发送的请求中 Set-Cookie: 后面的那一行,用 urlencode 方式编码的一个字典。
    tsuibin
        3
    tsuibin  
       Nov 27, 2012   ❤️ 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
       Nov 27, 2012
    @tsuibin
    @Livid
    @BOYPT

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

    这里有关于 Cookie 的细节:

    http://www.nczonline.net/blog/2009/05/05/http-cookies-explained/
    tsuibin
        8
    tsuibin  
       Nov 28, 2012   ❤️ 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  
       Nov 28, 2012
    @killpanda 所以你应该去看你的web server / framework的文档。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2820 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 08:45 · PVG 16:45 · LAX 01:45 · JFK 04:45
    ♥ Do have faith in what you're doing.