Python Flask:使用 Cookie


#Python Flask Web 框架#


本文讲述在 Python Flask Web 框架中如何使用 Cookie。

Cookie是存储在客户端的记录访问者状态的数据。具体原理,请见 http://zh.wikipedia.org/wiki/Cookie 。 常用的用于记录用户登录状态的session大多是基于cookie实现的。

cookie可以借助flask.Response来实现。下面是一个示例。

建立Flask项目

按照以下命令建立Flask项目HelloWorld:

mkdir HelloWorld
mkdir HelloWorld/static
mkdir HelloWorld/templates
touch HelloWorld/server.py

代码

修改HelloWorld/server.py

from flask import Flask, request, Response, make_response
import time

app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'hello world'


@app.route('/add')
def login():
    res = Response('add cookies')
    res.set_cookie(key='name', value='letian', expires=time.time()+6*60)
    return res


@app.route('/show')
def show():
    return request.cookies.__str__()


@app.route('/del')
def del_cookie():
    res = Response('delete cookies')
    res.set_cookie('name', '', expires=0)
    return res


if __name__ == '__main__':
    app.run(port=5000, debug=True)

由上可以看到,可以使用Response.set_cookie添加和删除cookie。expires参数用来设置cookie有效时间,它的值可以是datetime对象或者unix时间戳,笔者使用的是unix时间戳。

res.set_cookie(key='name', value='letian', expires=time.time()+6*60)

上面的expire参数的值表示cookie在从现在开始的6分钟内都是有效的。

要删除cookie,将expire参数的值设为0即可:

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

set_cookie()函数的原型如下:

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. Parameters:

     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.

运行与测试

运行HelloWorld/server.py

$ python3 HelloWorld/server.py

使用浏览器打开http://127.0.0.1:5000/add,浏览器界面会显示

add cookies

下面查看一下cookie,如果使用firefox浏览器,可以用firebug插件查看。打开firebug,选择Cookies选项,刷新页面,可以看到名为name的cookie,其值为letian

在“网络”选项中,可以查看响应头中类似下面内容的设置cookie的HTTP「指令」:

Set-Cookie: name=letian; Expires=Sun, 29-Jun-2014 05:16:27 GMT; Path=/

在cookie有效期间,使用浏览器访问http://127.0.0.1:5000/show,可以看到:

{'name': 'letian'}

本节源码

源码


( 本文完 )