How to delete / delete cookie in web.py

In web.py you can access the request cookies using web.webapi.cookies() , and you can set the cookie value with web.webapi.setcookie(...) . The documentation is not clear how to delete a cookie, however, are you just a setcookie with a value of None?

+4
source share
2 answers

You are right, this, of course, is not obvious from the setcookie() docstring or from online documents, but there somewhere :

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

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

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

Please note that you must delete the cookie with the same domain and protected flag as you set it, otherwise it will not delete. Also, with web.py, you usually use web.setcookie() as a shortcut to web.webapi.setcookie() .

+8
source

Web.py has no way to delete a cookie. If you look at the documentation in a cookbook , it is sparse and doesn't even talk about things like a path (so you can set a cookie in a specific place within the domain). Therefore, we must refer to the source code . In this, try how I can, I can’t find a link to the method of deleting, deleting or recalling cookies.

Having said that after testing it’s safe to use None for cookie expiration. Here is a quick web application that will 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 application first checks to see if a cookie exists. If it is not, it sets the cookie 'test1' with the value 'test'. On the next update, it will change the value to "test2". The next time it updates, it again sets the value to "test", but the cookie also expires. This should lead to the next update showing that "I set fire to the rain."

-1
source

Source: https://habr.com/ru/post/1346103/


All Articles