Storing Images on App Engine using Django

前端 未结 2 798
野趣味
野趣味 2021-02-03 15:08

I\'m trying to upload and save a resized image in a db.BlobProperty field on Google App Engine using Django.

the relevant part of my view that process the request looks

2条回答
  •  爱一瞬间的悲伤
    2021-02-03 15:48

    After some guidance from "hcalves" I figured out the problem. First of all, the default version of Django that comes bundled with App Engine is version 0.96 and how the framework handles uploaded files has changed since then. However in order to maintain compatibility with older apps you have to explicitly tell App Engine to use Django 1.1 like this:

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

    You can read more about that in the app engine docs.

    Ok, so here's the solution:

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

    Then, to serve the dynamic images back again from the datastore, build a handler for images like this:

    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
    

提交回复
热议问题