我正在尝试发出POST请求,从响应中提取变量,并使用python请求库将该变量传递到GET请求。
我的问题是当我使用f字符串将该变量传递到第二个请求时,我收到了来自服务器的500响应。但是,如果我手动将变量复制/粘贴到第二个请求中并再次运行程序(不使用f字符串),我将获得200响应并获得所需的数据。
我的意思是:
#First request:
REQ = 'http://myURL.com/post-request'
r = requests.post(REQ, headers=headers, data=data)
#this returns a 200 response with my unique ID which I need to pass into the next request
response = r.json() #convert it to json
myId = response['uniqueId'] #let's say the ID is 12345
REQ2 = f'http://myURL.com/get-request?uniqueId={myId}'
r2 = requests.get(REQ2, headers=headers)
#^this request returns a 500 response
#However, If I make that same request again and just type my id 12345 directly into the url:
REQ2 = 'http://myURL.com/get-request?uniqueId=12345'
r2 = requests.get(REQ2, headers=headers)
#I get a 200 response with the data I need.
我还确保这两个请求中的URL实际上是一个字符串,并且我已经测试以确保r2.url == REQ2
是True
。我不明白为什么当我使用f字符串时它不工作。
我也试过用"params="传递变量在我的get请求中,正如请求文档所建议的,但这并没有什么不同。我也试过使用。format字符串代替,但仍然没有运气。
你写了U比较r2.url == REQ2
但实际上是一样的。你应该比较一下REQ2 == 'http://myURL.com/get-request?uniqueId=12345'
我确定返回将是False
。在这之后print(REQ2.encode())
回报会让你大吃一惊。这是因为response['uniqueId']
可以返回一个列表或元组或其他东西。确保你的myId
确实是你所需要的。好运。