Skip to main content
 首页 » 编程设计

python之我正在使用 Pylons 并遇到 response.set_cookie 问题

2025年05月04日8txw1958

我在想 Pylons 的一个版本是不同的,但我找不到一种简单的方法来判断我运行的是什么版本。在第一个示例中,我相当确定它是 0.9.7 及更高版本,使用 webob 设置 cookie。此环境将 @ 符号设置为\100。正如您在其他环境中看到的那样,执行完全相同的操作会正确设置值。如果您需要更多信息请告诉我,我们将不胜感激。

较新版本的 Pylons(我认为)设置值不正确

response.set_cookie('email', 'user@domain.com', max_age=3600) 
response.headers 
ResponseHeaders([('Content-Type', 'text/html; charset=utf-8'), ('Content-Length','0'), 
 ('Pragma', 'no-cache'), ('Cache-Control', 'no-cache'), ('Set-Cookie', 
'email="user\\100domain.com"; expires="Fri, 03-Jun-2011 21:07:07 GMT"; Max-Age=3600; Path=/')]) 

测试环境正常/预期工作

response.set_cookie('email', 'user@domain.com', max_age=3600) 
response.headers 
HeaderDict([('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', '0'), 
('Pragma', 'no-cache'), ('Cache-Control', 'no-cache'), ('Set-Cookie',  
'email=user@domain.com; expires="Fri, 03-Jun-2011 21:07:35 GMT"; Max-Age=3600; Path=/')]) 

请您参考如下方法:

这是因为 webob 版本较新。

pylons 0.9.7 中的 webob 包是 ~0.9.8,它不会转义 cookie 值。

从那时到现在,webob 开始转义值,这导致您的"new"版本失败。如果您深入研究 webob 代码库(较新版本),就会发现这种情况发生在 Cookie 的 serialize() 方法中,它确保正确转义值。旧版本直接设置这些值,并没有在序列化时转义。

我有一个类似的设置,0.9.7 在 vi​​rtualenv 中运行,所以能够在我的系统上重现这个行为。

就您使用同一版本的方法而言,它们也应该对请求中的值进行转义,这样事情应该没问题。