【问题标题】:How to serve file from gridfs in django development environment?如何在 django 开发环境中从 gridfs 提供文件?
【发布时间】:2013-01-24 09:05:56
【问题描述】:

我需要在我的 django + mongoengine 项目中提供来自 GridFS 的文件。有没有开箱即用的解决方案?

【问题讨论】:

    标签: django mongoengine gridfs


    【解决方案1】:

    @login_required def view_posts(请求): post_data = Post.objects(user=request.user)

    return render(request, 'posts.html', { 'post_data' : post_data } )
    

    @login_required def show_image(请求,_md5): post_data = Post.objects(user=request.user)

    image = None
    for post in post_data:
        if _md5 == post.image.md5:
            image = post.image.read()
            break
    
    return HttpResponse(image.read(), content_type="image/" + post.image.format)
    

    【讨论】:

      【解决方案2】:

      在 Django 中我应该如何做到这一点并不是很明显,但这就是我最终要做的。

      我在views.py 中创建了一个show_image 函数,它传递感兴趣图像的md5 并将其作为HttpResponse 返回。在这种情况下,帖子数据由用户过滤,但通常您可能不需要。此外,我的 show_image 代码效率很低,我相当肯定有办法使用 mongoengine 进行查询,这比遍历查找 md5 的图像更有效。 urls.py 传递图像的 md5,然后调用 show_image 并返回标签所需的 HttpResponse/url。

      models.py

      from mongoengine import *
      
      class Post(Document):
          image = ImageField()
      

      views.py

      @login_required
      def view_posts(request):
          post_data = Post.objects(user=request.user)
      
          return render(request, 'posts.html', { 'post_data' : post_data } )
      
      @login_required
      def show_image(request, _md5):
          post_data = Post.objects(user=request.user)
      
          image = None
          for post in post_data:
              if _md5 == post.image.md5:
                  image = post.image.read()
                  break
      
          return HttpResponse(image, content_type="image/" + post.image.format)
      

      urls.py

          url(r'posts/images/(?P<_md5>\w+)$', 'project.views.show_image', name='show_image'),
      

      模板/posts.html

      <div id="posts">
          {% for post in post_data %}
          <dl class="dl-horizontal">
              <dd>{{ post.image.uploadDate }}</dd>
              <img src="images/{{ post.image.md5 }}" />
          </dl>
          {% endfor %}
      </div>
      

      【讨论】:

      • 注意:这可以修改为使用对象 ID 而不是 md5,这可能会使它更通用。
      猜你喜欢
      • 2012-01-26
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 2012-03-25
      • 2018-10-11
      相关资源
      最近更新 更多