开发者

How to delete/unset a cookie in web.py

In web.py, you can get ac开发者_Go百科cess to the request's cookies with web.webapi.cookies(), and you can set the value of a cookie with web.webapi.setcookie(...). The documentation isn't clear on how one deletes a cookie, however -- do you just setcookie with a value of None?


You're right, it's certainly not obvious from setcookie()'s docstring, or from the online docs, but it is there somewhere:

The third (and optional) argument to web.setcookie(), "expires", allows you to set when you want your cookie to expire. Any negative number will expire the cookie immediately.

For example, here's part of what we do in our sign-out code (delete the user's session cookie):

    web.setcookie('session', '', expires=-1, domain=session_cookie_domain)

Note that you must delete the cookie with the same domain and secure flag as you set it with, otherwise it won't delete. Also, with web.py, you normally use web.setcookie() as a shortcut to web.webapi.setcookie().


web.py doesn't seem to have a way to delete a cookie. If you go through the documentation in the cookbook, it's sparse and doesn't even talk about things like path (so you can set a cookie to a specific location within a domain). So we must turn to the sourcecode. In this, try as I may, I cannot find any reference to a delete,remove, or revoke cookie method.

Having said that, after testing, it is safe to use None to expire a cookie. Here's a quick web app that'll display it.

import web

web.config.debug = False
urls = (
        '/', 'index'
        )

class index:
    def GET(self):
        c = web.cookies().get('test1')
        if c:
            if c=="test":
                print 'this is ' + c
                web.setcookie('test1', 'test2', domain = 'example.com')
            else:
                print c
                web.setcookie('test1', 'test', domain = 'example.com' expires = None)
            return c
        else:
            print "didnt find cookie"       
            web.setcookie('test1', 'test', domain = 'example.com' expires='')
            return 'I set fire to the rain'

app = web.application(urls, globals())

if __name__ == "__main__":
    app.run()

In this the web app first checks if the cookie exists. If it doesn't it sets the cookie 'test1' with the value 'test'. On the next refresh, it will change the value to 'test2'. On the next refresh it sets the value again to 'test' but also expires the cookie. This should result in the next refresh showing 'I set fire to the rain'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜