我已经制作了 python 服务器,我想创建、发送和接收 cookie。我在接收它们时遇到问题,当我在 Chrome 上访问它时,我可以看到 cookie 已创建。我读过它应该出现在 os.environ 中,但它从来没有出现过。这是我的代码:
import os
import time
import Cookie
import BaseHTTPServer
from multiprocessing import Process
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(s):
#creating cookie
c = Cookie.SimpleCookie()
c['api'] = 'token'
c['api']['expires'] = 3*60*60
s.send_response(200)
#sending cookie
s.wfile.write(c)
s.wfile.write('\r\n')
s.send_header("Access-Control-Allow-Origin", "*")
s.send_header("Access-Control-Expose-Headers", "Access-Control-Allow-Origin")
s.send_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
s.end_headers()
#reading cookies
if 'HTTP_COOKIE' in os.environ:
cookie_string = os.environ.get('HTTP_COOKIE')
c = Cookie.SimpleCookie()
c.load(cookie_string)
try:
data=c['api'].value
print "cookie data: "+data
except:
print "The cookie was not set or has expired"
else:
print 'The cookie was not set'
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
''
if __name__ == '__main__':
httpd = ThreadedHTTPServer(('', 8666), MyHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
在我访问我的网站后,正在创建 cookie,但 os.environ 中从来没有 HTTP_COOKIE。
最佳答案
对于 future 的读者:
这是在 python3 中解析 cookie 的方法:
from http.server import BaseHTTPRequestHandler
from http.cookies import SimpleCookie
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
cookies = SimpleCookie(self.headers.get('Cookie'))
# then use somewhat like a dict, e.g:
username = cookies['username'].value
回答OP的问题:
问题是您在错误的位置寻找 cookie。
使用以下几行,您可以检查计算机的操作系统环境变量(如果名为 HTTP_COOKIE
):
if 'HTTP_COOKIE' in os.environ:
cookie_string = os.environ.get('HTTP_COOKIE')
但是运行 python 服务器没有理由创建操作系统范围的环境变量。
相反,您必须查看派生自的 BaseHTTPRequestHandler
内部。
正确的访问cookies的方法如下:
cookie_string = s.headers.get('Cookie')
它将解析客户端发送的 header 并为您提供相应的 cookie 字符串。
关于Python http服务器-无法读取cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43608581/