欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

让python的Cookie.py模块支持冒号做key的方法

程序员文章站 2022-06-03 08:39:34
为了做好兼容性,只能选择兼容:冒号。 很简单,修改一下cookie.morsel 复制代码 代码如下: #!/usr/bin/python # -*- coding: ut...
为了做好兼容性,只能选择兼容:冒号。

很简单,修改一下cookie.morsel
复制代码 代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""morselhook, fix cookie.cookieerror: illegal key value: ys-tab:entrance:e
"""

import cookie
import string

_morsel = cookie.morsel

class morselhook(_morsel):
"""
>>> import inspect
>>> (inspect.getargspec(morselhook.set)[3])[0]
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+-.^_`|~:"
>>> cookie = cookie.simplecookie()
>>> cookie.load("ys-tab:entrance:e=abc; webpy_session_id=75eb60dcc83e2d902146af0bb7f47afe61fbd2b2")
>>> print cookie
set-cookie: webpy_session_id=75eb60dcc83e2d902146af0bb7f47afe61fbd2b2;
set-cookie: ys-tab:entrance:e=abc;
"""
def set(self, key, val, coded_val, legalchars=cookie._legalchars+':', idmap=string._idmap, translate=string.translate):
return super(morselhook, self).set(key, val, coded_val, legalchars, idmap, translate)

cookie.morsel = morselhook

# 在你需要使用到cookie的地方先让上面的代码执行一遍


if __name__ == '__main__':
import doctest
doctest.testmod()