python - 为什么请求没有发送数据?

标签 python post python-requests python-3.6

我做了简单的服务器。

该服务器正在返回原始数据。 因此,当我在 Chrome Extension to Server 中使用 ReSTLet Client 时,我可以返回我的 json post 数据。

但是,Python Requests 模块是没有返回的。 我认为请求没有发送数据。

Python 3.6.8 请求2.21.0 PHP 7

在 PHP 中:

<?php
print_r($_POST);
?>

在Python中:

    try:
        task = self.q.get_nowait()
        # json_data = json.dumps(task)
        if 'picture' in task['data']:
            filename = task['data']['picture']
        else:
            filename = ''

        try:
            task['uuid'] = self.uuid
            if filename == '':
                url = 'http://server_domin/upload_nopic.php'
                data = json.dumps(task)
                print('task: ' + data)
                r = requests.post(url, data=data)
                print("Response: %s" % r.json())
            else:
                url = 'http://server_domin/upload.php'
                files = {'file': open('./images/' + filename, 'rb')}
                print('task: ' + json.dumps(task))
                r = requests.post(url, files=files, data=json.dumps(task))
                print("Response: %s" % r.json())

            # print("Response: %s" % str(r.text()))

        except Exception as ex:
            print("Upload Failure. ", filename, ex)
            traceback.print_stack()
            traceback.print_exc()

    except queues.QueueEmpty:
        pass

我在发送前检查了数据(变量),并在发送后检查了响应。 数据保存正常,但响应收到空数据。

在变量数据中:

{
  "data": {
    "utc": 1563862224,
    "accel": {
      "ax": -2.3630770385742186,
      "ay": 6.636727001953124,
      "az": 6.009446166992187
    },
    "gyro": {
      "gx": -4.137404580152672,
      "gy": -0.1297709923664122,
      "gz": 0.2366412213740458
    },
    "angle": {
      "ax": -14.785298705742603,
      "ay": 45.78478003457668,
      "az": 49.535035853061935
    },
    "temp": 26.459411764705884
  },
  "uuid": "ac2bbe96-5c2d-b960-6b88-40693bfb6a39"
}

requests.text()中:

'' or Array()

最佳答案

远程服务器可能需要 JSON 作为输入。

既然你使用

data = json.dumps(task)
requests.post(url, data=data)

requests.post(url, files=files, data=json.dumps(task))

如果不设置 Content-Type: application/json header ,远程服务器可能无法理解您的 HTTP 请求。

<小时/>

当您想要发送 JSON 时,请使用 json=data,而不是 data=dataIt will set自动适合您的Content-Type

示例:

data = {
    "uuid": "ac2bbe96-5c2d-b960-6b88-40693bfb6a39",
    "utc": 1563862224
    # ... other data
}
r = requests.post(url, json=data)
print(r.status_code, r.text)  # it is always a good idea to check response HTTP status code

关于python - 为什么请求没有发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57157992/

相关文章:

python - 根据 DataFrame 中的值计数保留具有前 n 个项目的所有行

python - 如何对看不见的文本数据进行分类?

python - `is` 和 `==` 之间的区别?

php - 当按下第二个提交按钮时,变量中的值消失

javascript - 我可以在发布表单输入时重定向到新的 php 文件吗?

python - 统计一个词的出现次数

python - 使用Python多处理池时系统内存不足?

java - 如何在 RETROFIT 中同时 POST ArrayList 和 String?

python - urllib3:抛出 MaxRetryError 时如何获取响应?

python - 自定义 Retry 类设置 BACKOFF_MAX 时出现异常