我正在使用mongoengine,flask,connexion和swagger 2.0编写照片Web应用程序来定义我的API。我们的想法是拥有一个关于发布照片的摄影师和关于照片的其他API的API。
我正在为照片API定义我的yaml文件。我们有两种方法发布(上传照片)并使用照片的ID来检索它。
swagger: '2.0'
info:
title: Photo service API
version: "0.1"
paths:
/photo:
post:
tags:
- "Photo"
operationId: photo_service.post_photo
summary: Add a new photo
consumes:
- multipart/form-data
parameters:
- name: photo_name
in: formData
description: "file to upload"
required: true
type: string
- name: photo_file
in: formData
description: "file to upload"
required: true
type: file
responses:
201:
description: New photo added
schema:
properties:
photo_file:
type: object
description: Information about the photo
409:
description: Photo already exists
/photo/{photo_id}:
get:
tags:
- "Specific photo"
operationId: photo_service.get_photo
summary: Get specific photo.
produces:
- image/png
parameters:
- $ref: '#/parameters/photo_id'
responses:
200:
description: Return the requested photo.
schema:
type: file
404:
description: Photo does not exist.
Photo类非常简单,可用于测试目的:
class Photo(Document):
photo_name = StringField(max_length=120, required=True)
photo_file = ImageField()
我编写了以下函数,这些函数对应于Yaml文件的Operation Id字段中调用的函数:
def get_photo(photo_id):
try:
ph = mongo_get_photo(photo_id)
except (Photo.DoesNotExist, InvalidId) as e:
return 'Not Found', 404
except pymongo.errors.ServerSelectionTimeoutError as sste:
return 'Mongo unavailable', 503
return ph
def post_photo(photo_name,photo_file):
try:
ph = mongo_add (photo_name,photo_file)
return 'Created', 201, {'location': '/photo/' + str(ph.id)}
except pymongo.errors.ServerSelectionTimeoutError as sste:
return 'Mongo unavailable', 503
因为我使用mongodb作为数据库。我正在使用包装器向我的db发出请求:
@robustify.retry_mongo
def mongo_add(photo_name,photo_file):
ph = Photo(photo_name = photo_name)
ph.photo_file.put(photo_file)
ph.save()
return ph
@robustify.retry_mongo
def mongo_get_photo(photo_id):
ph = Photo.objects(id=ObjectId(photo_id)).first()
photo = ph.photo_file.read()
return photo
我的问题是POST方法似乎有效。每当我尝试发布png图片时,我都会创建一个200代码响应。但是get方法不起作用。这似乎是mongodb处理文件的方式的问题。这是我在函数mongo_get_photo中读取图像文件的方式有问题吗?有人知道吗?
最好将图像存储为字符串,方法是先将其转换为基数为64的
谢谢!