Python的flask框架设置cookies与获取cookies

作者:Davidszhou   来源:SEO优化博客   时间:2017-10-18 03:33:52   点击:

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与获取cookies

Python的flask框架设置cookies与获取cookies

Python的flask框架设置cookies与获取cookies

上面讲到python的flask如何设置与获得,下面讲下如何删除cookies,根据手册设置‘expires’有效日期值可以做到删除,将‘expires’值设置成0即删除了cookies,代码如下:

        mresponse.set_cookie('name','',expires=0)

Python菜鸟,学习:共同学习,共同分享,共同进步的过程

TAGS:python , flask , cookies

来自Davids zhou博客原创文章请尊重作者:http://www.zongk.com/zongk/101.html转载请标注此链接

网站统计
文章总数:129
今天发布:0
软件资源数:18