我在Django有一个项目,我正在使用mongoengine使用GridFSStorage将图像保存到Mongo数据库中。
到目前为止一切都还好,但问题是......当试图通过http请求检索图像时,使用django-tastypie-mongoengine制作的REST API,我得到了一个像这样的json对象:
{"file": "<GridFSProxy: 516ed7cf56ba7d01eb09f522>", "id": "516ed7cf56ba7d01eb09f524", "resource_uri": "/api/v1/pic/516ed7cf56ba7d01eb09f524/"}
有谁知道如何通过http请求从GridFS获取文件?
非常感谢!
答案 0 :(得分:1)
您需要编写自己的视图,但您可以将其视为API的一部分。首先,观点:
def api_image(pk):
obj = get_object_or_404(Model, pk=pk)
image_file = obj.file
return Response(image_file.read(),
mime_type='image/png') # or whatever the MIME type is
然后,您可以将其映射到urls.py
:
url('^/api/v1/pic/(?P<pk>\w+)/file/$', api_image)
并确保tastypie在输出中显示您想要的内容:
def dehydrate_file(self, bundle):
return '/api/v1/pic/%s/file/' % (bundle.obj.id)
只需确保假API视图出现在实际API定义之前,您应该全部设置!
答案 1 :(得分:0)
保罗的提示非常有用。在这里,我完全以tastypie方式实现了上传和下载图像。
你去..
<强> 1。压倒deseriazer以支持&#39; multipart&#39;
class MultipartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultipartResource, self).deserialize(request, data, format)
<强> 2。模型类
class Research(Document):
user = ReferenceField(User)
academic_year = StringField(max_length=20)
subject = StringField(max_length=150)
topic = StringField(max_length=50)
pub_date = DateTimeField()
authored = StringField(max_length=20)
research_level = StringField(max_length=20)
paper_presented = BooleanField()
thesis_written = BooleanField()
proof_image = ImageField()
第3。资源类
class ResearchResource(MultipartResource, MongoEngineResource):
class Meta:
queryset = Research.objects.all()
list_allowed_methods = ['get','post']
resource_name = 'research'
authentication = SessionAuthentication()
authorization = Authorization()
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/$" % self._meta.resource_name,
self.wrap_view('dispatch_list'), name="api_dispatch_list"),
#url to download image file.
url(r"^(?P<resource_name>%s)/(?P<pk>\w+)/file/$"% self._meta.resource_name,
self.wrap_view('get_image'), name="api_get_image"),
]
#Preparing image url dynamically
def dehydrate_proof_image(self, bundle):
return '/api/v1/%s/%s/file/' % (self._meta.resource_name,bundle.obj.id)
#view will call based on image url to download image.
def get_image(self, request, **kwargs):
obj = Research.objects.get(id=kwargs['pk'])
image_file = obj.proof_image
return HttpResponse(image_file.read(), content_type="image/jpeg"))
希望这对将来的每个人都非常有用。 :)