【问题标题】:How can I modify a Curl Command to run in Python with data loaded in a JSON file如何修改 Curl 命令以在 Python 中运行并在 JSON 文件中加载数据
【发布时间】:2021-06-19 22:02:26
【问题描述】:

我在下面使用以下 Curl 命令:(它适用于我)

curl "https://myeducationcompany.instructure.com/api/v1/courses/9391/quizzes/196242/questions" --trace q.output -X POST -d @q1.json -H "Content-type: application/json" -H "Authorization: Bearer myBeareToken"

但我试图将这个 Curl 命令更改为 python 脚本

然后我使用这个站点 https://curl.trillworks.com/#python 将我的 Curl 调用转换为 python 脚本。

这是网站为我创建的脚本:

import requests

headers = {
  'Content-type': 'application/json',
  'Authorization': 'Bearer myBeareString',
}

data = open('q1.json')
response = requests.post('https://myeducationcompany.instructure.com/api/v1/courses/9391/quizzes/196242/questions', headers=headers, data=data)

但脚本不工作,我收到错误:

raise ConnectionError(err, request=request) 
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))

当我尝试在没有“数据”参数的情况下运行脚本时,

response = requests.post('https://myeducationcompany.instructure.com/api/v1/courses/9391/quizzes/196242/questions', headers=headers)

脚本运行良好。我得到了 HTTP 代码 200。

我在 Stackoverflow 上的另一个回复中读到,Curl 中的参数“-d @q1.json”与 Python 上的“data = open('q1.json')”函数不同

我尝试在 postman 中传递 JSON 文件的内容,但没有成功。

我能够将我的 Curl 命令转换为 Python 或如何在 Postman 中使用它。

我该怎么做?

ps:这是“q1.json”文件的内容

{
  "question": {
    "question_name": "Pergunta",
    "question_text": "<link rel=\"stylesheet\" href=\"https://instructure-uploads.s3.amazonaws.com/account_117480000000000001/attachments/582887/pucminas_subacc_graduacao_iceg_administracao.mobile.css\"><span>Em uma escala de 0 a 10 (sendo 0 a menor e 10 a maior nota), quanto você indicaria esta disciplina para um amigo?</span>",
    "question_type": "multiple_choice_question",
    "points_possible": 0.0,
    "answers": {
      "0": {
        "answer_text": "10",
        "answer_weight": 100
      },
      "1": {
        "answer_text": "9",
        "answer_weight": 0
      },
      "2": {
        "answer_text": "8",
        "answer_weight": 0
      },
      "3": {
        "answer_text": "7",
        "answer_weight": 0
      }
    }
  }
}

【问题讨论】:

  • 可能需要改成data = open('q1.json').read()
  • 我本来打算建议 data=data.read() 之类的东西,但没有意识到 Requests 实际上允许类似文件的对象作为 data 参数的值。
  • data 并没有提到允许 str 对象;也许类文件对象必须以二进制模式打开(假设文件本身使用预期的编码)? (你会认为 Requests 可以自己处理对字符串的编码,但也许不是。)
  • @fsimonjetz 您的建议对我有用。谢谢。
  • @chepner 就像 fsimonjetz 的建议一样,它也适用于我。

标签: python curl


【解决方案1】:

基于@fsimonjetz 和@chepner 的建议

这段代码对我有用

data = open('q1.json').read()

data = open('q1.json')
data=data.read()

两个代码给我的结果是一样的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-13
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 2020-09-06
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多