【问题标题】:Python JSON GET Request Like cURLPython JSON GET 请求类似于 cURL
【发布时间】:2019-06-04 19:48:59
【问题描述】:

我有一个想要移植到 Python 的 cURL 命令。

curl -XGET "http://localhost:9200/nuix-7674bc4a60b74ea7bac8996a98b0cb94;item;schema-version=1/_search" -H 'Content-Type: application/json' -d'
{
  "query": {
    "regexp": {
      "content": "(p)hotos"
    }
  }
}'

它成功返回一个非错误响应。

这是我在 Python 3.6 中使用 requests 包所尝试的。

import requests
import json

# api-endpoint
url = "http://localhost:9200/nuix-7674bc4a60b74ea7bac8996a98b0cb94;item;schema-version=1/_search"

# headers
headers = {'Content-type': 'application/json'}

# Define JSON String
params = """
{
    "query": {
        "regexp":{
            "content": "(p)hotos"
        }
    }
}
"""

params = json.loads(params)
print(params)

# sending get request and saving the response as response object
response = requests.get(url=url, params=params, headers=headers)

# extracting data in json format
data = response.json()
print(data['hits']['total'])
print('DONE')

回复response._content 指出此错误:

b'{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"request [/nuix-7674bc4a60b74ea7bac8996a98b0cb94;item;schema-version=1/_search] contains unrecognized parameter: [query]"}],"type":"illegal_argument_exception","reason":"request [/nuix-7674bc4a60b74ea7bac8996a98b0cb94;item;schema-version=1/_search] contains unrecognized parameter: [query]"},"status":400}'

设置params的正确方法是什么?

【问题讨论】:

  • 在Windows中使用cURL,需要像这样调整引号:curl -XGET "http://localhost:9200/nuix-7674bc4a60b74ea7bac8996a98b0cb94;item;schema-version=1/_search" -H "Content-Type: application/json" -d "{\"query\": {\"regexp\": {\"content\": \"(p)hotos\"}}}"

标签: python json elasticsearch curl get


【解决方案1】:

requests 期望 dict 作为 params 而不是字符串。我不确定这是你的问题,但你可以尝试重写为:

params = {
    "query": {
        "regexp":{
            "content": "(p)hotos"
        }
    }
}

查看文档中的此部分以了解演练:http://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls

【讨论】:

    【解决方案2】:

    解决方法是使用json参数,而不是params

    response = requests.get(url=url, json=params, headers=headers)
    

    我可能已经将 JSON 字符串重写为字典,但我正在使用一个工具——自动生成 cURL 有效负载的 Kibana。此解决方案允许我将 JSON 有效负载复制并粘贴到我的 Python 脚本中。

    【讨论】:

      猜你喜欢
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 2014-02-15
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多