无法在python CGI中从浏览器检索cookies

2024-04-20 12:09:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python CGI脚本,通过它我可以设置cookies(通过使用SimpleCookie()库)并执行其他功能,比如发送回对html页面的响应。你知道吗

我无法检索浏览器中设置的Cookie。下面是我的代码。你知道吗

#!/usr/bin/python3

import cgi
import cgitb
from pymongo import MongoClient
from bson.json_util import dumps
import json
from http import cookies
import datetime
import uuid
import os

cgitb.enable(display=0, logdir="/tmp/superBowl/")

form = cgi.FieldStorage()

client = MongoClient('localhost', 2017)

db = client['Superbowl']
users = db['users']

username = form.getvalue('name')
password = form.getvalue('password')


if (users.find_one({'username': username, 'password': password})is not None):
    userInfo = json.loads(dumps(users.find_one({"username": username})))
    users.find_one_and_update({"username": username}, {"$set": {"loggedIn": "true"}})
    expires = datetime.datetime.utcnow() + datetime.timedelta(hours=6)
    C = cookies.SimpleCookie()
    C["session"] = str(uuid.uuid4())
    C["session"]['Expires'] = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")
    print(C.output(attrs=None, header='Set-Cookie:', sep='\r\n'))    
    print ('Content-Type: application/json\n\n')

    #getting cookie
    if 'HTTP_COOKIE' in os.environ:
        cookies = os.environ['HTTP_COOKIE']
        #print(json.dumps(cookies))
        #cookies = cookies.split('; ')

    # for cookie in cookies:
    #     cookie = cookie.split('=')
    #     handler[cookie[0]] = cookie[1]
    #print(json.dumps(handler))
        print(cookies)
    else:
        print("no cookies")

    #print (dumps(users.find_one({"username": username})))


else:
    print ('Content-Type: application/json\n\n')
    print (dumps({"username": "404"}))

    #print("You are unregistered !")

print语句在chrome的网络中打印响应&我希望至少看到设置了哪些cookie。你知道吗

它确实打印了session=一些uuid值,我没有设置它,但是它只打印了一次。在进一步调试之后,甚至连这个都停止打印了。你知道吗

我假设"HTTP_COOKIE"现在实际上没有进入os.environ。你知道吗

另外,现在看来cookies并不是每次都能被检索到,我需要刷新几次,然后才能被检索到。而且返回的uuid与我设置的不一样。你知道吗

p.p.S我使用了请求库&它返回空的"<RequestsCookieJar[]>"


Tags: fromimportjsondatetimeuuidoscookieusername