Max*_* L. 2 javascript python cookies json flask
我在 Flask 中设置了一个 cookie,如下所示:
response.set_cookie('notice', value = json.dumps(someObject), max_age=None)
Run Code Online (Sandbox Code Playgroud)
如果我在服务器上打印 json.dumps(someObject) 我得到:
{"message": "hello", "type": "success"}
Run Code Online (Sandbox Code Playgroud)
在客户端它变成:
"{\"message\": \"hello\"\054 \"type\": \"success\"}"
Run Code Online (Sandbox Code Playgroud)
我想在 javascript 客户端上解码它到底是什么格式?
我想对其进行解码并将其传递给 angular.fromJson(),看起来至少有(\"的)未转义要做,但我很惊讶地看到 \054(用于逗号)
Werkzeug 库引用了 cookie 值,以便在Cookie
标头中安全使用;这包括引用任何逗号、分号、双引号和反斜杠:
cookie_quoting_map = {
b',' : b'\\054',
b';' : b'\\073',
b'"' : b'\\"',
b'\\' : b'\\\\',
}
Run Code Online (Sandbox Code Playgroud)
字母、数字和字符之外的任何其他内容也!#%&'~_`><@,:/$*+-.^|)(?}{=
被编码为八进制代码点。如果cookie 中有任何转义值,则整个 cookie 也被双引号包围。
如果您需要访问 JavaScript 中的 cookie 值,则必须再次对其进行解码。以斜杠和 3 位数字开头的值是八进制值;一个String.replace()
电话应该做:
cookie_quoting_map = {
b',' : b'\\054',
b';' : b'\\073',
b'"' : b'\\"',
b'\\' : b'\\\\',
}
Run Code Online (Sandbox Code Playgroud)
演示:
> // recreate properly escaped value
> var cookie = "\"{\\\"message\\\": \\\"hello\\\"\\054 \\\"type\\\": \\\"success\\\"}\""
> cookie
""{\"message\": \"hello\"\054 \"type\": \"success\"}""
> decode_flask_cookie(cookie)
"{"message": "hello", "type": "success"}"
> JSON.parse(decode_flask_cookie(cookie))
Object {message: "hello", type: "success"}
Run Code Online (Sandbox Code Playgroud)