gpt4 book ai didi

Python session 不适用于多个请求

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:46 25 4
gpt4 key购买 nike

我是Python新手,所以请原谅我的缺乏良心..

Requirement : Need to process a list of strings through a rest api call

问题:使用 Requests,我能够成功进行 api 调用并完成工作。使用请求没有任何问题,除了想研究使用 session 是否会加快我的处理速度,因为我在每个请求中传递身份验证。

跟踪了多个使用 session 的线索,但仍然收到 HTTP 400 - 错误请求。

引用:Python Requests and persistent sessions

这是我试图使其工作的代码,任何帮助都会非常有帮助:

import requests
from requests.auth import HTTPBasicAuth

with open('list.txt') as f:
lines = f.read().splitlines()

s = requests.Session()
r = s.get("https://ucdeploy.domain.com/rest/state", auth=HTTPBasicAuth('username', 'password'))

if r:
print("Logged in Successfully")
else:
print("Login Failed ==> " + str(r))
exit()

for cmp in lines:
print("Processing - " + cmp.strip())
payload = '{"name":"' + cmp.strip() + '","description":"","templateId":"141e248c-ca02-4f51-a873-c07acd5366cd",' \
'"templateVersion":"","componentType":"STANDARD","sourceConfigPlugin":"",' \
'"importAutomatically":"false","useVfs":"true","defaultVersionType":"FULL",' \
'"importAgentType":"inherit","inheritSystemCleanup":"true",' \
'"runVersionCreationProcess":"false","properties":{},"teamMappings":[{' \
'"teamId":"bf3c4566-160b-4d79-b47e-5f2bbc1ffbb0"}]}'

response = s.put("https://ucdeploy.domain.com/rest/deploy/component", data=payload)
if response:
print("Successfully Processed")
else:
print("Failed ==> " + str(response))
exit()

输出:

Logged in Successfully
Processing - Component1
Failed ==> <Response [400]>

最佳答案

确定了有效负载格式的问题。

由于某种原因,下面的串联代码不起作用:

payload = '{"name":"' + cmp.strip() + '","description":"","templateId":"141e248c-ca02-4f51-a873-c07acd5366cd",' \
'"templateVersion":"","componentType":"STANDARD","sourceConfigPlugin":"",' \
'"importAutomatically":"false","useVfs":"true","defaultVersionType":"FULL",' \
'"importAgentType":"inherit","inheritSystemCleanup":"true",' \
'"runVersionCreationProcess":"false","properties":{},"teamMappings":[{' \
'"teamId":"bf3c4566-160b-4d79-b47e-5f2bbc1ffbb0"}]}'

使用以下内容更新了有效负载串联并且它有效:

componentname = '{"name":"' + cmp.strip()
payload = componentname + '","description":"","templateId":"141e248c-ca02-4f51-a873-c07acd5366cd",' \
'"templateVersion":"","componentType":"STANDARD","sourceConfigPlugin":"",' \
'"importAutomatically":"false","useVfs":"true","defaultVersionType":"FULL",' \
'"importAgentType":"inherit","inheritSystemCleanup":"true",' \
'"runVersionCreationProcess":"false","properties":{},"teamMappings":[{' \
'"teamId":"bf3c4566-160b-4d79-b47e-5f2bbc1ffbb0"}]}'

我希望这对某人有帮助。

关于Python session 不适用于多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57981186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com