使用python eve添加未经验证的字典以及图像

时间:2017-06-28 01:26:28

标签: eve

我想在mongoDB中导入图像以及任何字典。字典应该提供图像标签,其中我在定义模式时无法知道哪些类型,数字和名称。 我试图在前夕添加字典但没有成功:

curl -F"attr={\"a\":1}"  -F "img_id=2asdasdasd" -F "img_data=@c:\path\
1.png;type=image/png" http://127.0.0.1:5000/images
{"_status": "ERR", "_issues": {"attr": "must be of dict type"}, "_error": {"message": "Insertion failure: 1 document(s)
contain(s) error(s)", "code": 422}}

我的架构定义如下:

'schema': {
    #Fixed attributes
        'original_name': {
            'type': 'string',
            'minlength': 4,
            'maxlength': 1000,
        },
        'img_id': {
            'type': 'string',
            'minlength': 4,
            'maxlength': 150,
            'required': True,

            'unique': True,
        },
        'img_data': {
            'type': 'media'
        },
    #Additional attributes
        'attr': {
            'type': 'dict'

        }
    }

有可能吗?是否应该修复dicts的架构?

修改 我想先添加图像,然后添加字典,但在PATCH请求中出错:

C:\Windows\SysWOW64>curl -X PATCH -i  -H "Content-Type: application/json" -d "{\
"img_id\":\"asdasdasd\", \"attr\": {\"a\": 1}}" http://localhost:5000/images/asd
asdasd
HTTP/1.0 405 METHOD NOT ALLOWED
Content-Type: application/json
Content-Length: 106
Server: Eve/0.7.4 Werkzeug/0.9.4 Python/2.7.3
Date: Wed, 28 Jun 2017 22:55:54 GMT

{"_status": "ERR", "_error": {"message": "The method is not allowed for the requested URL.", "code": 405}}

1 个答案:

答案 0 :(得分:0)

我已针对相同情况在Github上发布了一个问题。不过我已经找到了解决方法。

覆盖dict验证器:

class JsonValidator(Validator):

    def _validate_type_dict(self, field, value):
        if type(value) is dict:
            pass
        try:
            json.loads(value)
        except:
            self._error(value, "Invalid JSON")

app = Eve(validator=JsonValidator)

接下来,添加一个插入钩子:

def multi_request_json_parser(documents):
    for item in documents:
        if 'my_json_field' in item.keys():
            item['my_json_field'] = json.loads(item['my_json_field'])

app.on_insert_myendpoint += multi_request_json_parser

必须覆盖dict验证器,否则由于验证错误,不会调用插入挂钩。