我想在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}}
Run Code Online (Sandbox Code Playgroud)
我的架构定义如下:
'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'
}
}
Run Code Online (Sandbox Code Playgroud)
有可能吗?是否应该修复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}}
Run Code Online (Sandbox Code Playgroud)
小智 0
我已经在Github上发布了一个针对同样情况的问题。不过我有一个解决方法。
覆盖字典验证器:
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)
Run Code Online (Sandbox Code Playgroud)
接下来,添加一个插入钩子:
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
Run Code Online (Sandbox Code Playgroud)
字典验证器必须被覆盖,否则插入钩子将不会由于验证错误而被调用。