【问题标题】:Using variable as data parameter in a POST request with Deepl API在使用 Deepl API 的 POST 请求中使用变量作为数据参数
【发布时间】:2021-03-21 19:03:59
【问题描述】:

我正在使用此脚本向 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 请求中使用这个文本变量。

【问题讨论】:

  • 我可能对您已删除的question 有答案。可以取消删除吗?
  • 嗨@Corralien!我找到了解决方案。还是谢谢!
  • 好吧,没关系:)

标签: python google-colaboratory deepl


【解决方案1】:

我想在 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,或 payloadbody

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

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

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

response = requests.request("POST", url, data={
    "text": text,
    "target_lang": "es"
})

【讨论】:

  • 哦,好的。这现在完美无缺。谢谢!。我正在学习使用 python 来调用不同的 API。有时最简单的事情会变成最难做的事情。原谅我的无知。也感谢关于如何命名数据的注释,我会记住的。我将此答案标记为正确。
  • @Folleloide 这一切都很好,我并不是真的在嘲弄你。 :) 这只是一种温和的推动,而不是更多。
  • ...接下来,创建一个以(text, target_lang)为参数并返回翻译结果的函数。
猜你喜欢
  • 1970-01-01
  • 2017-03-15
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
  • 2019-12-05
  • 1970-01-01
相关资源
最近更新 更多