django - 使用 Django 在 App Engine 上存储图像

标签 django google-app-engine

我正在尝试使用 Django 在 Google App Engine 的 db.BlobProperty 字段中上传和保存调整大小的图像。

我处理请求的 View 的相关部分如下所示:

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')"但我不知道如何引用它。有什么想法吗?

提前致谢。

最佳答案

在“hcalves”的指导下,我解决了这个问题。首先,与 App Engine 捆绑在一起的默认 Django 版本是 0.96 版,并且框架处理上传文件的方式从那时起发生了变化。但是,为了保持与旧应用程序的兼容性,您必须像这样明确告诉 App Engine 使用 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

关于django - 使用 Django 在 App Engine 上存储图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1616890/

相关文章:

允许粗体和斜体元素的 Django 模板标签

python - 如何将 url 中的变量传递给 Django ListView

javascript - 如何在谷歌应用程序引擎项目中包含.js文件

Python/Django - 从对象变量值中获取带有索引的列表值

python - 有没有办法在不生成缩略图的情况下使用 sorl-thumbnail url?

google-app-engine - Go 的 Google App Engine 数据存储区没有 != 过滤器

python - 使用ndb和python从GAE中通过URL传递的自动分配的ID中检索 key

Firebase + 数据存储 = need_index

java - Google App Engine 数据存储区-主键

python - 将查询集数据传递给另一个查询 django