【问题标题】:File upload to python-eve using requests使用请求将文件上传到 python-eve
【发布时间】:2015-04-12 23:12:06
【问题描述】:

我正在尝试使用请求库将图片上传到 python-eve 服务器。为此,我发送了一个 multipart/form-data 请求。这似乎是我的架构的问题,如下所示:

schema = {
    'name': {
        'type': 'string',
        'required': True
    },
    'description': {
        'type': 'string'
    },
    'picture': {
        'type': 'media'
    },
     'properties': {
         'type' : 'dict'
     }
}

请求如下所示:

import requests

file = open('/home/user/Desktop/1500x500.jpeg', 'rb')
payload = {'name': 'hello', 'properties': {'status': 'on_hold'}}
r = requests.post("http://localhost:5001/node", data=payload, files={'picture': file})

我得到的是 ResourceInvalid 异常:

ResourceInvalid: Failed. Response status: 422. Response message: UNPROCESSABLE ENTITY. Error message: {"_status": "ERR", "_issues": {"properties": "must be of dict type"}, "_error": {"message": "Insertion failure: 1 document(s) contain(s) error(s)", "code": 422}}

有什么解决办法吗?我是否遗漏了有关请求格式的内容?

【问题讨论】:

    标签: python python-requests eve


    【解决方案1】:

    这样的东西应该可以正常工作:

    import requests
    
    file = open('/home/user/Desktop/1500x500.jpeg', 'rb')
    payload = {'name': 'hello'}
    
    r = requests.post("http://localhost:5001/node", data=payload, files={'picture': file})
    

    【讨论】:

    • 可行,但失败的是:payload = {'name': 'hello', 'properties': {'prop1': 'value', 'prop2': 'other'}} r = requests.post("localhost:5001/node", data=payload, files={'picture': file}) 值是字典。
    • properties 字段的定义是什么?
    • 在模式中只是一个类型'dict'。我目前没有强制执行任何内容/验证。
    • hmm 然后确保为端点设置allow_unknown 属性。如果您使用的是 Cerberus 0.8.2,您可以选择为该字段设置 allow_unknown。 HTH。
    【解决方案2】:

    我刚刚收到了类似的issue。我建议您尝试以这种方式更改您的代码:将您的字典转储到一个 json 对象中,并添加一个标头来描述您发送的内容。

    import requests
    import json
    
    file = open('/home/user/Desktop/1500x500.jpeg', 'rb')
    payload = {'name': 'hello', 'properties': {'status': 'on_hold'}}
    headers = {'Content-type': 'application/json; charset=utf-8'}
    r = requests.post("http://localhost:5001/node", data=json.dumps(payload), files={'picture': file}, headers=headers)
    

    【讨论】:

    • 是的,这很可能是问题所在。谢谢。
    • 感谢您的建议!这些代码在你那正常吗?根据我一直在阅读的内容,在使用 application/json Content-type 进行请求时,您无法发送文件对象(二进制数据)。唯一的方法是对文件进行 base64 编码并以这种方式发送,但这让 Eve 感到困惑。如果您设法让该代码运行,请告诉我,因为对我来说它失败了。
    猜你喜欢
    • 2017-09-02
    • 2016-11-10
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 2019-05-20
    • 1970-01-01
    • 2014-04-29
    相关资源
    最近更新 更多