代码之家  ›  专栏  ›  技术社区  ›  Henrik Joreteg

使用django在应用程序引擎上存储图像

  •  5
  • Henrik Joreteg  · 技术社区  · 16 年前

    我正在尝试使用django在谷歌应用引擎的db.blobproperty字段中上载和保存一个调整过大小的图像。

    处理请求的视图的相关部分如下所示:

    image = images.resize(request.POST.get('image'), 100, 100)
    recipe.large_image = db.Blob(image)
    recipe.put()
    

    这似乎是文档中示例的逻辑django等价物:

    from google.appengine.api import images
    
    class Guestbook(webapp.RequestHandler):
      def post(self):
        greeting = Greeting()
        if users.get_current_user():
          greeting.author = users.get_current_user()
        greeting.content = self.request.get("content")
        avatar = images.resize(self.request.get("img"), 32, 32)
        greeting.avatar = db.Blob(avatar)
        greeting.put()
        self.redirect('/')
    

    (来源: http://code.google.com/appengine/docs/python/images/usingimages.html#Transform )

    但是,我一直收到一个错误,上面写着:NotImageError/清空图像数据。

    并指这一行:

    image = images.resize(request.POST.get('image'), 100, 100)
    

    我找不到图像数据。似乎没有上传,但我不知道为什么。我的表单包含enctype=“multipart/form data”和所有这些。我认为我引用图像数据的方式有问题。”request.post.get(“image”)“但是我不知道如何引用它。有什么想法吗?

    事先谢谢。

    2 回复  |  直到 14 年前
        1
  •  9
  •   Henrik Joreteg    16 年前

    在“医生”的指导下,我解决了这个问题。首先,与应用引擎捆绑在一起的Django的默认版本是0.96版本,从那时起,框架处理上传文件的方式就发生了变化。但是,为了保持与旧应用程序的兼容性,您必须明确地告诉应用程序引擎使用django 1.1,如下所示:

    from google.appengine.dist import use_library
    use_library('django', '1.1')
    

    你可以多读一些 in the app engine docs .

    好的,下面是解决方案:

    from google.appengine.api import images
    
    image = request.FILES['large_image'].read()
    recipe.large_image = db.Blob(images.resize(image, 480))
    recipe.put()
    

    然后,要再次从数据存储服务动态图像,请为以下图像构建一个处理程序:

    from django.http import HttpResponse, HttpResponseRedirect
    
    def recipe_image(request,key_name):
        recipe = Recipe.get_by_key_name(key_name)
    
        if recipe.large_image:
            image = recipe.large_image
        else:
            return HttpResponseRedirect("/static/image_not_found.png")
    
        #build your response
        response = HttpResponse(image)
        # set the content type to png because that's what the Google images api 
        # stores modified images as by default
        response['Content-Type'] = 'image/png'
        # set some reasonable cache headers unless you want the image pulled on every request
        response['Cache-Control'] = 'max-age=7200'
        return response
    
        2
  •  3
  •   erlando    14 年前

    您可以通过request.files[字段名称]访问上载的数据。

    http://docs.djangoproject.com/en/dev/topics/http/file-uploads/


    在我看来,更多地阅读谷歌的图像API,你应该这样做:

    from google.appengine.api import images
    
    image = Image(request.FILES['image'].read())
    image = image.resize(100, 100)
    recipe.large_image = db.Blob(image)
    recipe.put()
    

    请求.files['image'].read()) 应该能用,因为它应该是姜戈的 上传文件 实例。