I'm trying to encode an object in a Python script and set it as a cookie so I can read it with client-side JavaScript.
我正在尝试在Python脚本中编码对象并将其设置为cookie,以便我可以使用客户端JavaScript来读取它。
I've run into problems every way I've tried to do this. Generally, the cookie is formatted in a way that makes JSON.parse() break.
我试图做的每一种方式都遇到了问题。通常,cookie的格式是使JSON.parse()中断的方式。
My current script:
我目前的剧本:
cookie = Cookie.SimpleCookie()
data = {"name": "Janet", "if_nasty": "Ms. Jackson"}
cookie['test'] = json.dumps(data)
self.response.headers.add_header("Set-Cookie", cookie.output(header=''))
... which results in
...导致
test="{\"name\": \"janet\"\054 \"if_nasty\": \"Ms. Jackson\"}"
on the client.
在客户端上。
I don't really want to introduce a hack-y solution to replace instances of commas when they appear. Any ideas how I can pass complex data structures (both by setting and reading cookies) with Python?
我真的不想在它们出现时引入一个hack-y解决方案来替换逗号实例。有关如何通过Python传递复杂数据结构(通过设置和读取cookie)的任何想法?
3 个解决方案
#1
2
I also wanted to read a cookie (that had been set on the server) on the client. I worked around the issue by base64 encoding the JSON String, however there are a few small gotchas involved with this approach as well.
我还想在客户端上读取cookie(已在服务器上设置)。我通过base64编码JSON字符串解决了这个问题,但是这种方法也涉及到一些小问题。
1: Base64 strings end with 0-2 equal signs, and these were being converted into the string \075. My approach is to revert those characters into equal characters on the client.
1:Base64字符串以0-2等号结尾,这些字符串被转换为字符串\ 075。我的方法是在客户端上将这些字符恢复为相同的字符。
2: The base64 string is being enclosed in double quote characters in the cookie. I remove these on the client.
2:base64字符串用cookie中的双引号字符括起来。我在客户端上删除了这些。
Server:
nav_json = json.dumps(nav_data)
nav_b64=base64.b64encode(nav_json)
self.response.set_cookie('nav_data', nav_b64)
Client:
var user_data_base64= $.cookie('nav_data');
// remove quotes from around the string
user_data_base64 = user_data_base64.replace(/"/g,"");
// replace \075 with =
user_data_base64 = user_data_base64.replace(/\\075/g,"=");
var user_data_encoded=$.base64.decode( user_data_base64 );
var user_data = $.parseJSON(user_data_encoded);
I am using 2 jquery plugins here: https://github.com/carlo/jquery-base64 and https://github.com/carhartl/jquery-cookie
我在这里使用2个jquery插件:https://github.com/carlo/jquery-base64和https://github.com/carhartl/jquery-cookie
Note: I consider this a hack: It would be better to re-implement the python code that encodes the cookie in javascript, however this also has the downside that you would need to notice and port and changes to that code.
注意:我认为这是一个hack:最好重新实现在javascript中编码cookie的python代码,但是这也有一个缺点,你需要注意并移植和更改该代码。
I have now moved to a solution where I use a small html file to set the cookie on the client side and then redirect to the actual page requested. Here is a snippet from the JINJA2 template that I am using:
我现在已经转移到一个解决方案,我使用一个小的html文件在客户端设置cookie,然后重定向到请求的实际页面。这是我正在使用的JINJA2模板的片段:
<script type="text/javascript">
var nav_data='{% autoescape false %}{{nav_data}}{% endautoescape %}';
$.cookie('nav_data', nav_data, { path: '/' });
window.location.replace("{{next}}")
</script>
Note 2: Cookies are not ideal for my use case and I will probably move on to Session or Local Storage to reduce network overhead (although my nav_data is quite small - a dozen characters or so.)
注意2:Cookie不适合我的用例,我可能会继续使用Session或Local Storage来减少网络开销(尽管我的nav_data非常小 - 大约十几个字符。)
#2
0
not sure a cookie is the best way of doing this? see the getting started guide for info rendering data to the client
不确定cookie是最好的方法吗?请参阅信息呈现数据入门指南到客户端
#3
0
On the Python side:
在Python方面:
-
json.dumps
the string - escape spaces - just call
.replace(' ', '%20')
- Call
urllib.quote_plus()
then write the string to the cookie
json.dumps字符串
逃生空间 - 只需要调用.replace('','%20')
调用urllib.quote_plus()然后将字符串写入cookie
On the JavaScript side:
在JavaScript方面:
- read the cookie
- pass it through
decodeURIComponent()
-
JSON.parse
it
读取cookie
通过decodeURIComponent()传递它
This seems to be the cleanest way I've found.
这似乎是我发现的最干净的方式。
#1
2
I also wanted to read a cookie (that had been set on the server) on the client. I worked around the issue by base64 encoding the JSON String, however there are a few small gotchas involved with this approach as well.
我还想在客户端上读取cookie(已在服务器上设置)。我通过base64编码JSON字符串解决了这个问题,但是这种方法也涉及到一些小问题。
1: Base64 strings end with 0-2 equal signs, and these were being converted into the string \075. My approach is to revert those characters into equal characters on the client.
1:Base64字符串以0-2等号结尾,这些字符串被转换为字符串\ 075。我的方法是在客户端上将这些字符恢复为相同的字符。
2: The base64 string is being enclosed in double quote characters in the cookie. I remove these on the client.
2:base64字符串用cookie中的双引号字符括起来。我在客户端上删除了这些。
Server:
nav_json = json.dumps(nav_data)
nav_b64=base64.b64encode(nav_json)
self.response.set_cookie('nav_data', nav_b64)
Client:
var user_data_base64= $.cookie('nav_data');
// remove quotes from around the string
user_data_base64 = user_data_base64.replace(/"/g,"");
// replace \075 with =
user_data_base64 = user_data_base64.replace(/\\075/g,"=");
var user_data_encoded=$.base64.decode( user_data_base64 );
var user_data = $.parseJSON(user_data_encoded);
I am using 2 jquery plugins here: https://github.com/carlo/jquery-base64 and https://github.com/carhartl/jquery-cookie
我在这里使用2个jquery插件:https://github.com/carlo/jquery-base64和https://github.com/carhartl/jquery-cookie
Note: I consider this a hack: It would be better to re-implement the python code that encodes the cookie in javascript, however this also has the downside that you would need to notice and port and changes to that code.
注意:我认为这是一个hack:最好重新实现在javascript中编码cookie的python代码,但是这也有一个缺点,你需要注意并移植和更改该代码。
I have now moved to a solution where I use a small html file to set the cookie on the client side and then redirect to the actual page requested. Here is a snippet from the JINJA2 template that I am using:
我现在已经转移到一个解决方案,我使用一个小的html文件在客户端设置cookie,然后重定向到请求的实际页面。这是我正在使用的JINJA2模板的片段:
<script type="text/javascript">
var nav_data='{% autoescape false %}{{nav_data}}{% endautoescape %}';
$.cookie('nav_data', nav_data, { path: '/' });
window.location.replace("{{next}}")
</script>
Note 2: Cookies are not ideal for my use case and I will probably move on to Session or Local Storage to reduce network overhead (although my nav_data is quite small - a dozen characters or so.)
注意2:Cookie不适合我的用例,我可能会继续使用Session或Local Storage来减少网络开销(尽管我的nav_data非常小 - 大约十几个字符。)
#2
0
not sure a cookie is the best way of doing this? see the getting started guide for info rendering data to the client
不确定cookie是最好的方法吗?请参阅信息呈现数据入门指南到客户端
#3
0
On the Python side:
在Python方面:
-
json.dumps
the string - escape spaces - just call
.replace(' ', '%20')
- Call
urllib.quote_plus()
then write the string to the cookie
json.dumps字符串
逃生空间 - 只需要调用.replace('','%20')
调用urllib.quote_plus()然后将字符串写入cookie
On the JavaScript side:
在JavaScript方面:
- read the cookie
- pass it through
decodeURIComponent()
-
JSON.parse
it
读取cookie
通过decodeURIComponent()传递它
This seems to be the cleanest way I've found.
这似乎是我发现的最干净的方式。