使用django-tastypie-mongoengine从GridFS中检索图像 [英] Retrieving images from GridFS using django-tastypie-mongoengine

查看:290
本文介绍了使用django-tastypie-mongoengine从GridFS中检索图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中有一个项目,我正在使用mongoengine使用GridFSStorage将图像保存到Mongo数据库中。



所有的确定到目前为止,但问题是...当尝试通过http请求检索图像时,使用由django-tastypie-mongoengine制作的REST API得到这样一个json对象:

  {file:< GridFSProxy:516ed7cf56ba7d01eb09f522>,id 516ed7cf56ba7d01eb09f524,resource_uri:/ api / v1 / pic / 516ed7cf56ba7d01eb09f524 /} 

任何人都知道如何通过http请求从GridFS获取文件?



非常感谢!

解决方案

您需要编写自己的视图,但您可以将其看作是API的一部分。首先,视图:

  def api_image(pk):
obj = get_object_or_404(Model,pk = pk)
image_file = obj.file
返回响应(image_file.read(),
mime_type ='image / png')#或任何MIME类型为

然后,您可以将其映射到您的 urls.py 中:

  url('^ / api / v1 / pic /(?P< pk> \w +)/ file / $',api_image)

确保口味显示在输出中显示您想要的内容:


$ b $
$ b return'/ api / v1 / pic /%s / file /'%(bundle.obj.id)

只需确保假API显示在您的实际API定义之前,您应该全部设置! / p>

I have a project in Django, and I'm using mongoengine to save images into a Mongo database using GridFSStorage.

All ok so far, but the problem is... when trying to retrieve the images via http request, with a REST API made with django-tastypie-mongoengine, I get back a json object like this:

{"file": "<GridFSProxy: 516ed7cf56ba7d01eb09f522>", "id": "516ed7cf56ba7d01eb09f524", "resource_uri": "/api/v1/pic/516ed7cf56ba7d01eb09f524/"}

Does anybody know how could I get the file from GridFS via http request?

Many thanks!

解决方案

You'll need to write your own view, but you can make it seem like it's part of the API. First, the view:

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

Then, you can map it in your urls.py:

   url('^/api/v1/pic/(?P<pk>\w+)/file/$', api_image)

And to make sure tastypie shows what you want in the output:

def dehydrate_file(self, bundle):
    return '/api/v1/pic/%s/file/' % (bundle.obj.id)

Just make sure the fake API view appears ahead of your actual API definitions, and you should be all set!

这篇关于使用django-tastypie-mongoengine从GridFS中检索图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆