在Python中将反斜杠添加到我的cookie中

Lev*_*evi 7 python

我正在使用Python的SimpleCookie,我遇到了这个问题,我不确定它是否与我的语法或什么有关.此外,这是我的Python类的课堂作业,所以它的目的是教授Python,所以这远不是我在现实世界中这样做的方式.

无论如何,基本上我将信息输入保存在cookie中的表单中.我正在尝试使用输入的新信息附加到上一个cookie.但由于某些原因,在第三次输入数据时,cookie突然变为"\".我不知道他们来自哪里.

这是我得到的输出类型:

"\"\\"\\\\"测试:更多\\\\":rttre \\":更多\":更多"

#!/usr/local/bin/python

import cgi,os,time,Cookie
#error checking
import cgitb
cgitb.enable()

if 'HTTP_COOKIE' in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split('; ')
    for myCookie in cookies:
        myCookie = myCookie.split('=')
        name = myCookie[0]
        value = myCookie[1]
        if name == 'critter' :
            hideMe = value

#import critterClass

#get info from form
form = cgi.FieldStorage()
critterName = form.getvalue('input')
input2 = form.getvalue('input2')
hiddenCookie = form.getvalue('hiddenCookie')
hiddenVar = form.getvalue('hiddenVar')

#make cookie
cookie = Cookie.SimpleCookie()

#set critter Cookie
if critterName is not None:
    cookie['critter'] = critterName
#If already named
else:
    #if action asked, append cookie
    if input2 is not None:
        cookie['critter'] = hideMe+":"+input2
    else:
        cookie['critter'] = "default"

print cookie


print "Content-type: text/html\n\n"



if ((critterName is None) and (input2 is None)):
    print """
    <form name="critter" id="critter" method="post" action="critter.py">
    <label for="name">Name your pet: <input type="text" name="input" id="input" /></label>
    <input type="submit" name="submit" id="submit" value="Submit" />
    </form>
    """
else:
    formTwo ="""
    <form name="critter2" id="critter2" method="post" action="critter.py">
    <label for="name">%s wants to: <input type="text" name="input2" id="input2" /></label>
    <input type="hidden" name="hiddenVar" id="hiddenVar" value="%s" />
    <input type="submit" name="submit" id="submit" value="Submit" />
    </form>
    [name,play,feed,mood,levels,end]
    """
    print formTwo % (critterName,critterName)

if 'HTTP_COOKIE' in os.environ:
    cookies = os.environ['HTTP_COOKIE']
    cookies = cookies.split('; ')
    for myCookie in cookies:
        myCookie = myCookie.split('=')
        name = myCookie[0]
        value = myCookie[1]
        if name == 'critter' :
            print "name"+name
            print "value"+value
Run Code Online (Sandbox Code Playgroud)

gim*_*mel 3

正如其他人所解释的,反斜杠是转义您插入到 cookie 值中的双引号字符。这里起作用的(隐藏)机制是类SimpleCookie。该BaseCookie.output()方法返回适合作为 HTTP 标头发送的字符串表示形式。它将在双引号字符和反斜杠字符之前插入转义字符(反斜杠) 。

print cookie
Run Code Online (Sandbox Code Playgroud)

语句激活BaseCookie.output().

在您的字符串每次通过 cookie 的output()方法时,都会增加反斜杠(从第一对引号开始)。

>>> c1=Cookie.SimpleCookie()
>>> c1['name']='A:0'
>>> print c1
Set-Cookie: name="A:0"
>>> c1['name']=r'"A:0"'
>>> print c1
Set-Cookie: name="\"A:0\""
>>> c1['name']=r'"\"A:0\""'
>>> print c1
Set-Cookie: name="\"\\\"A:0\\\"\""
>>> 
Run Code Online (Sandbox Code Playgroud)