pickle字符串中包含cookie的python请求?

2024-10-03 04:27:20 发布

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

我正在向一个API提交请求,它通常需要几个小时才能完成请求并返回数据。我正在编写一个python解决方案,其中我的脚本将提交请求并将状态信息写入笔记本电脑上的一个文件中,以后需要时可以检索到该文件。在

当我向API提交作业时,API会用一个状态URL来响应,该URL可用于检查作业的状态。但是,由于站点的负载平衡,我还需要从我的初始请求中检索会话cookie,并使用该cookie确保在使用返回的状态URL检查作业状态时命中正确的服务器。在

我可以从API中检索状态URL,也可以使用此代码从请求中检索cookie。请注意,我经常提交多个作业,因此文件中可能有多个状态URL/Cookie:

# Submit the request to the API
rPOST = requests.post(url, auth=(uname, passwd), data=json_data, headers=headers)
CookieMonster = pickle.dumps(rPOST.cookies) # Get the cookie as a string

# Grab the JSON data currently in the file:
with open(statFile, mode='r') as status_json:
    StatusDict = json.load(status_json)
    status_json.close()
# Add new URL and cookie to the JSON and write back to the file:
with open(statFile, mode='w') as status_json:
    StatusDict[(str(json.loads(rPOST.text)[u'link'][u'href']))] = CookieMonster
    json.dump(StatusDict, status_json)
    status_json.close()

submit代码工作正常,但是当我试图使用状态URL检查作业状态时,出现了404错误

^{pr2}$

我的状态文件中的JSON如下所示:

{
    "https://example.com/sfsalk242234": "Pickled cookie string data here",
    "https://example.com/sfsa34532234": "Pickled cookie string data here",
    "https://example.com/23423fsdfssd": "Pickled cookie string data here"
}

这与cookies=CookieMonster参数有关。如果我删除了cookies参数,并多次启动代码,我最终会将负载平衡到正确的服务器并得到响应。但是,当我使用cookies参数时,我从来没有得到响应,总是得到一条HTTP404消息。在

还要注意的是,对于长时间运行的工作,我经常需要断开我的笔记本电脑,睡眠,重启等。。。因此,保持脚本运行以保留原始cookie对象并不是一个可行的选择,这就是为什么我要将状态URL和cookie数据写入磁盘。在

如何正确地存储这样的cookie,然后检索它以在将来的请求中使用?在

更新的解决方案

rPOST = requests.post(url, auth=(uname, passwd), data=json_data, headers=headers)
CookieMonster = rPOST.cookies
with open(statFile, mode='w') as status_json:
    StatusDict[(str(json.loads(rPOST.text)[u'link'][u'href']))] = CookieMonster.items()
    json.dump(StatusDict, status_json)

然后将检索改为如下所示:

# Check each URL and see if my job's are done:
for url, cookies in StatusDict:
    rGET = requests.get(url, auth=(uname, passwd), cookies=dict(cookies))

Tags: 文件theapijsonurldatacookie状态
1条回答
网友
1楼 · 发布于 2024-10-03 04:27:20

我会避免使用pickle,因为requestScookejar在某种程度上是字典的包装器,而requests方法将字典作为cookie的输入。在

with open(statFile, mode='w') as status_json:
    StatusDict[(str(json.loads(rPOST.text)[u'link'][u'href']))] = CookieMonster.items()
    json.dump(StatusDict, status_json)

后来呢

^{pr2}$

相关问题 更多 >