python的flask框架设置cookies与获取cookies
Python的flask设置是通过response对象来操作,需要response返回之前,通过response.set_cookie来设置,实例代码(注意from flask import make_response):
def index():
response = make_response(render_template('index.html', foo=42))
response.set_cookie('name','davidszhou')
return response
解释:
1、make_response:
flask.make_response(*args)
Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.
英文比较坡脚,直接百度翻译:
有时需要在视图中设置额外的标头。因为视图不必返回响应对象,但可以返回一个值,它通过自身本身被转换为响应对象,因此向它添加头变得很棘手。可以调用这个函数,而不是使用返回,您将得到一个响应对象,您可以使用它来附加头文件。
2、set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)
Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too.
参数:
key – the key (name) of the cookie to be set.
value – the value of the cookie.
max_age – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.
expires – should be a datetime object or UNIX timestamp.
domain – if you want to set a cross-domain cookie. For example, domain=".example.com" will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it.
path – limits the cookie to a given path, per default it will span the whole domain.
设置了cookies 如何获取cookies呢?根据Werkzeug手册:
cookies:
A dict with the contents of all cookies transmitted with the request.
得知获得cookies内容使用flask的Request对象的cookies方法,实例代码:
name=request.cookies.get('name')
这样就获得了cookies内的键'name'的值内容
运行实例截图:
上面讲到python的flask如何设置与获得,下面讲下如何删除cookies,根据手册设置‘expires’有效日期值可以做到删除,将‘expires’值设置成0即删除了cookies,代码如下:
mresponse.set_cookie('name','',expires=0)
Python菜鸟,学习:共同学习,共同分享,共同进步的过程
来自Davids zhou博客原创文章请尊重作者:http://www.zongk.com/zongk/101.html转载请标注此链接
Davids zhou | 站点地图 | | | 皖ICP备14017762号 如有侵犯您权利点击上面QQ -Powered By 帝国CMS -davids.zhou#qq.com(#换@)
Davidszhou个人博客主要记录在网站建设、SEO优化、python开发、PHP开发中遇到问题记录保存,作为他人参考学习教程