Python http服务器 - 无法读取cookie

时间:2017-04-25 10:48:35

标签: python http cookies server

我已经创建了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。

1 个答案:

答案 0 :(得分:2)

面向未来的读者:

这是在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内部。 访问cookie的正确方法如下:

cookie_string = s.headers.get('Cookie')

它将解析客户端发送的标头,并为您提供相应的cookie字符串。