无法使用Django的set_cookie方法设置Cookie。

huangapple go评论65阅读模式
英文:

Not able to set cookie using django set_cookie

问题

我正在尝试使用Django的set_cookie方法设置Cookie。
我将字典转换为字符串,然后将其设置在名为'blah'的Cookie中。
Cookie已设置,但我注意到逗号被替换为\054

Python代码

x = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
}
response.set_cookie('blah', json.dumps(x)) 
return response

在Chrome中的显示:

"{\"key1\": \"value1\"4 \"key2\": \"value2\"4 \"key3\": \"value3\"}"

请提供任何可能遗漏的指针 - 请建议。

django==4.2

英文:

I am trying to set cookie using django set_cookie.
I am converting dict to string and then setting it in a cookie named 'blah'.
The cookie gets set, but I see that the commas are replaced with \054.

Python code

        x = {
            "key1": "value1",
            "key2": "value2",
            "key3": "value3",
        }
        response.set_cookie('blah', json.dumps(x)) 
        return response

How I see it in chrome:

"{\"key1\": \"value1\"4 \"key2\": \"value2\"4 \"key3\": \"value3\"}"

Any pointer what am I missing - please suggest.

django==4.2

答案1

得分: 0

什么都没有。事实上,这与逗号完全相同。确实,'\054' == ','

> '\054' == ','
true

这只是显示字符串的方式,但内容完全相同。确实,如果我们解析JSON数据块,我们会得到:

> JSON.parse("{\"key1\": \"value1\"\054 \"key2\": \"value2\"\054 \"key3\": \"value3\"}");
{ key1: 'value1', key2: 'value2', key3: 'value3' }

因此,它将其解析为正确的JavaScript对象。您可以将其与字符串字面量 'foo'"foo" 进行比较,两者都是相同值的表示,就像 '\40'' ' 也是相同的一样。

英文:

> Any pointer what am I missing - please suggest.

Nothing. Indeed, this is exactly the same as a comma. Indeed, '\054' == ',':

> '4' == ','
true

It is just how it shows a string, but the content is exactly the same. Indeed, if we thus would parse the JSON blob, we get:

> JSON.parse("{\"key1\": \"value1\"4 \"key2\": \"value2\"4 \"key3\": \"value3\"}");
{ key1: 'value1', key2: 'value2', key3: 'value3' }

So it parses it to the right JavaScript object. You can compare it to a string literal with 'foo' and "foo", both are presentations of the same value, just like '\40' and ' ' are the same as well.

huangapple
  • 本文由 发表于 2023年6月25日 20:38:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76550426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定