flask用session那叫一个方便,封装的不能更好,反观cookie,为人诟病,但实际上,它也易用且强大。

官方文档中,关于cookie的描述篇幅:http://flask.pocoo.org/docs/0.11/quickstart/#cookies

不得不说,真的很少,我建议看API文档响应类:[http://flask.pocoo.org/docs/0.11/api/#response-objects](http://flask.pocoo.org/docs /0.11/api/#response-objects)

关于设置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 cookieMorselobject 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.cometc. 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.

我以我所知扯一扯。。。

1.

set_cookie是Response类的一个方法,所以对于任何“返回”都是可以做附加设置的,我之前在“[Flask使用点滴之访问前后](http://blog.saintic.com/blog/92.htm l)”中就点了下:

另外对于你设定的响应返回 [make_response()](http://flask.pocoo.org/docs/0.11/api/#flask.Flask.m ake_response)的对象,都可以使用set_cookie,比如:

response = make_response(jsonify(success=True))
response = make_response(redirect(url_for("index")))
response = make_response(render_template("xxx.html"))

这些response都可以附加上以返回。

set_cookie的参数,key, value=’’, max_age=None, expires=None, path=’/’, domain=None, secure=None, httponly=False_,_其他的都好理解,我扯一扯max_age和expires。

  • 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.

这两个参数都是设置过期时间的,默认None,也就是一次浏览器会话的时间。

max_age需要int作为秒,它会计算多少秒后,设为过期;

expires需要datetime或timestamp作为值,再计算过期时间。

两个转化的函数供参考:

import datatime, time
def How_Much_Time(seconds=0, minutes=0, hours=0):
    """ 将s、m、h后的时间转化为Y-m-d """
    dt = datetime.datetime.now() + datetime.timedelta(seconds=int(seconds), minutes=int(minutes), hours=int(hours))
    return dt.strftime("%Y-%m-%d")
def Date2Seconds(date):
    """ 将Y-m-d后的时间转化为s(当前时间多少秒)  """
    d = datetime.datetime.strptime(date,"%
Y-%m-%d")
    return time.mktime(d.timetuple()) - time.time()

关于flask cookie登录的demo:[https://github.com/staugur/flask-cookie-login](https://g ithub.com/staugur/flask-cookie-login)

The End.

水平有限,若您发现错误 ,烦请通知我们修改,联系方式在页脚处,也可能GitHub上提issue,谢谢!

·End·