0

我正在使用此脚本向 Deepl API 发出 POST 请求。在这种情况下,文本参数作为数据参数传递。我想将文本作为变量传递,以便可以在其他脚本中使用它,但如果它不是数据参数,我将无法发出发布请求。


url = "https://api.deepl.com/v2/translate?auth_key=xxxx-xxxx-xxx-xxxx-xxxxxxxxx"

querystring = {
    "text" = "When we work out how to send large files by email",
    "target_lang" : "es"
}

response = requests.request("POST", url, data=querystring)

print(response.text)  

是否可以使用文本作为变量来发出此请求?

作为一个更好的示例,此文本来自以前的脚本。如果我使用文本作为数据参数,我不能使用包含文本的前一个变量。如果文本来自以前的变量,我不能在 data 参数中使用这个变量。例如:

脚本前的变量: text = "When we work out how to send large files by email"我想在 POST 请求中使用这个文本变量。

4

1 回答 1

2

我想在 POST 请求中使用这个文本变量。

我很困惑。为什么不在 POST 请求中将此文本用作变量?

url = "https://api.deepl.com/v2/translate?auth_key=xxxx-xxxx-xxx-xxxx-xxxxxxxxx"

text = "When we work out how to send large files by email"

querystring = {
    "text": text,
    "target_lang": "es"
}

response = requests.request("POST", url, data=querystring)

print(response.text)

除此之外-原则上,querystring当变量不包含查询字符串时不要调用它。正确命名事物很重要。

出于 POST 请求的目的,您发布的数据是data, 或 a payload, a body

body = {
    "text": text,
    "target_lang": "es"
}

response = requests.request("POST", url, data=body)

但是甚至根本不创建单独的变量也没有错:

response = requests.request("POST", url, data={
    "text": text,
    "target_lang": "es"
})
于 2021-03-21T11:03:59.427 回答