【问题标题】:Convert curl command with form files into python requests将带有表单文件的 curl 命令转换为 python 请求
【发布时间】:2020-04-24 04:03:09
【问题描述】:

我有以下 curl 命令:

curl -X POST "_my_username_:_my_password_@10.2.25.209:5601/api/saved_objects/_import" -H "kbn-xsrf: true" --form file=@V:kibana\IndexPatterns\events.ndjson

效果很好(将索引模式导入弹性搜索),但我正在尝试将其转换为 Python 请求。我尝试了几种方法,包括以下几种:

files = {'file': '@' + args.kibana_index_pattern_path}
res = requests.post("http://{0}:{1}@{2}:5601/api/saved_objects/_import".format(args.elastic_username, args.elastic_password, args.kibana_host),
                    headers={'kbn-xsrf': 'true'}, data=files)


files = {'file': '@' + args.kibana_index_pattern_path}
res = requests.post("http://{0}:{1}@{2}:5601/api/saved_objects/_import".format(args.elastic_username, args.elastic_password, args.kibana_host),
                    headers={'kbn-xsrf': 'true', 'Content-Type': 'text/plain'}, files=files)

使用或不使用@ 的不同组合,文件作为单个字符串而不是字典等。我不断收到错误请求和无效内容类型的错误(例如:{'message': 'Unsupported Media Type', 'error': 'Unsupported Media Type', 'statusCode': 415})。

请注意,有一些工具可以将 curl 转换为请求,但我尝试过的所有工具都无法识别文件参数,要么忽略它,要么抛出异常。但是,该命令本身有效。

我在这里做错了什么?

【问题讨论】:

  • 你能分享你遇到的错误吗?
  • 一种方法是查看工具生成的请求。使用 curl -v 将为您提供 HTTP 请求的所有标头。考虑查看请求模块的调试信息(以某种方式)并将其与工作的 curl 请求进行比较。然后,您可以将精力集中在丢失的(或不同的)HTTP 标头上。如果您不知道如何从 requests 获取调试信息(我还不知道),您可以考虑进行数据包捕获以查看 HTTP 标头。
  • @AMC 有很多错误,具体取决于我尝试的变体,但最常见的错误是:{'message': 'Unsupported Media Type', 'error': 'Unsupported Media Type', 'statusCode':第415章
  • @RonenNess Victor S 的解决方案有效吗?
  • @AMC 不幸的是它没有工作。身份验证正常问题是由于某种原因添加的文件。谢谢。

标签: python elasticsearch curl python-requests


【解决方案1】:

尝试以下方法:

import requests
from requests.auth import HTTPBasicAuth

username = '_my_username_'
password = '_my_password_'
headers = {'kbn-xsrf': 'true'}
upload_url = "http://10.2.25.209:5601/api/saved_objects/_import"
files = {'file': open('V:\algotec\analytics\install\Kibana\IndexPatterns\events.ndjson', 'rb')}

r = requests.post(upload_url, headers=headers, auth=HTTPBasicAuth(username, password), files=files)
print(r.status_code)

如果您收到带有此错误的错误请求

错误:'错误请求',消息:'请求必须包含 kbn-xsrf 标题。'

按照如下修改头部信息,然后重试。

headers = {
  'Content-Type': 'application/x-ndjson',
  'kbn-xsrf': 'anything',
  'Accept': 'application/x-ndjson'
}

【讨论】:

  • 嗨,维克多,不幸的是它不起作用,ES 需要一个字符串文件而不是二进制文件。 PS。身份验证正常问题是由于某种原因添加的文件。
  • @RonenNess 您收到的响应代码和消息是什么?
  • {'message':'不支持的媒体类型','错误':'不支持的媒体类型','statusCode':415})。关于 auth - 我们以相同的方式使用其他 api 并且 auth 在那里工作,这是唯一给我们带来问题的 api,可能是因为文件。谢谢
  • @RonenNess 你在使用 ES 6.0 吗?
  • @RonenNess 问题在于内容类型:elastic.co/guide/en/elasticsearch/reference/current/…。我已更新标头以包含换行分隔的 JSON (NDJSON),这是正在发送的内容。如果再次失败,我的建议是删除“Accept”,然后删除“kbn-xsrf”,直到您离开 Content-Type。一个反复试验的问题,直到。
猜你喜欢
  • 2018-10-21
  • 2018-09-27
  • 2020-08-15
  • 2017-07-12
  • 1970-01-01
  • 2016-05-20
  • 2016-08-04
  • 2016-09-28
  • 2017-05-25
相关资源
最近更新 更多