【问题标题】:I am trying to write a python script to GET and POST to octoprint我正在尝试编写一个 python 脚本来 GET 和 POST 到 octoprint
【发布时间】:2017-09-06 21:10:35
【问题描述】:

我正在尝试将 REST API 与 Octoprint 一起使用

我的代码如下:

import requests
import json


api_token = '7598509FC2184985B2B230AEE22B388F'
api_url_base = 'http://10.20.10.189/'

api_url = '{}{}'.format(api_url_base, 'api/job')

headers = {
         'Content-Type': 'application/json',
         'apikey': api_token,
         '"command"': '"pause"',
         '"action"': '"pause"'
          }

response = requests.post(api_url, headers=headers)

print(response)

我的结果是

<Response [400]>

我现在有点不知所措

【问题讨论】:

  • 一个 HTTP 400“错误请求”响应告诉您由于语法无效,服务器无法理解该请求。您的请求中的某些内容格式不正确。

标签: python-3.x rest octoprint


【解决方案1】:

我从未使用过 octoprint 和 requests。这是文档和知识的最佳答案,通常您必须将标头和 POST 数据分开。

import requests
import json


api_token = '7598509FC2184985B2B230AEE22B388F'
api_url_base = 'http://10.20.10.189/'

api_url = '{}{}'.format(api_url_base, 'api/job')

headers = {
         'Content-Type': 'application/json',
         'X-Api-Key': api_token # the name may vary.  I got it from this doc: http://docs.octoprint.org/en/master/api/job.html
          }
data = {
         'command': 'pause', # notice i also removed the " inside the strings
         'action': 'pause'
          }

response = requests.post(api_url, headers=headers, data=data)

print(response)

【讨论】:

    【解决方案2】:

    我正在做类似的事情。

    这段代码是函数:

    import json
    import urllib3
    
    ip_address = '192.168.1.55'
    apikey = 'CA54B5013E8C4C4B8BE6031F436133F5'
    url = "http://" + ip_address + '/api/job'
    http = urllib3.PoolManager()
    
    r = http.request('POST', 
                     url,
                     headers={'Content-Type': 'application/json', 
                              'X-Api-Key': apikey},
                     body=json.dumps({'command': 'pause',
                                      'action': 'pause'}))
    

    【讨论】:

      【解决方案3】:

      我也一直在处理这个问题(Octoprint API)。网址库3 这里的例子是功能性的,但是当我将它移植到 python3 请求时,我得到了 .

      response = requests.post(api_url, headers=headers, data=data)
      

      神奇之处在于(json=data)

      response = requests.post(api_url, headers=headers, json=data)
      

      【讨论】:

        猜你喜欢
        • 2021-02-06
        • 1970-01-01
        • 2012-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-20
        • 2021-10-02
        相关资源
        最近更新 更多