代码之家  ›  专栏  ›  技术社区  ›  Carlos Ferreira

Watson发现服务Python添加文档错误:内容类型无效。应为“multipart/form data”

  •  1
  • Carlos Ferreira  · 技术社区  · 6 年前

    导入Watson Developer Cloud Python SDK

    from watson_developer_cloud import DiscoveryV1
    

    从Slack doc\u url获取pdf,这是一个私有url

    r = requests.get(doc_url, headers={'Authorization': 'Bearer {}'.format(slack_token) })
    logging.debug("read_pdf headers %s " %r.headers )
    logging.debug("read_pdf content-type %s " %r.headers['content-type'] )
    

    将文件暂时保存在云文件系统中

    with open(doc_name, 'wb' ) as f:
      f.write(r.content)
    filepath = os.path.join(os.getcwd(), '.', doc_name )
    logging.debug('filepath %s' %filepath)
    logging.debug('filepath assertion %s' %os.path.isfile(filepath) )
    

    discovery = DiscoveryV1(
    username=DS_USERNAME,
    password=DS_PASSWORD,
    version="2017-10-16"
    )
    

    在发现实例中添加pdf文档

    with open(filepath, 'rb') as fileinfo:
      add_doc = discovery.add_document(ENVIRONMENT_ID, COLLECTION_ID, file_content_type=r.headers['content-type'])
    

    read_pdf headers {'Content-Type': 'application/pdf', 'Content-Length': '149814'
    WatsonApiException: Error: Invalid Content-Type. Expected 'multipart/form-data', got 'application/octet-stream', Code: 400 , X-dp-watson-tran-id: gateway02-732476861 , X-global-transaction-id: ffea405d5ba1ad632ba8b5bd
    

    开发人员代码示例在Github中被注释掉。

    https://github.com/watson-developer-cloud/python-sdk/blob/master/examples/discovery_v1.py

    1 回复  |  直到 6 年前
        1
  •  3
  •   Bruce Adams    6 年前

    哦,天哪。这是一个糟糕的错误信息。

    给你的电话少了什么 discovery.add_document() file file=fileinfo 这样地:

    with open(filepath, 'rb') as fileinfo:
      add_doc = discovery.add_document(ENVIRONMENT_ID,
                                       COLLECTION_ID,
                                       file=fileinfo,
                                       file_content_type=r.headers['content-type'])
    

    供参考, here is some Python code 它的工作原理和你的目标非常相似。

    推荐文章