Broken Images - Google App Engine

2019-08-09 03:07发布

问题:

Firstly, I realize this is a fairly common question on here, and I have looked at numerous other similar StackOverflow questions, and none of the answers have solved the problem.

Basically, once users submit images -> they are posted as blank images - and when I click the src of the images I am lead to a blank page. What's wrong with my code?

Here's a mashup of bits and pieces of my code from various files

<div class="card-image"><img src="/image?img_id={{card.key()}}"></img>

class Card(db.Model):
    image = db.BlobProperty(required = True)

class Image(MainHandler):
    def get(self):
        card = db.get(self.request.get('img_id'))
        if card.image:
            self.response.headers['Content-Type'] = 'image/png'
            self.response.out.write(card.image)
        else:
            self.response.out.write('No image')
 class Gallery(MainHandler):
       image = db.Blob(images.resize(self.request.get('image'), 32, 32))
       #later in the code, a Card is constructed.

回答1:

Your code looks fine to me. Are you sure your model contains the image data?

Second. There is a better, faster and cheaper way you can serve your images. Google can serve the images for you, almost for FREE and with runtime sizing, using App Engine's High-Performance Image Serving System. To use this, you have to use the blobstore and use get_serving_url.

Here is an example of a serving url:

https://lh6.ggpht.com/1HjICy6ju1e2GIg83L0qdliUBmPHUgKV8FP3QGK8Qf2pHVBfwkpO_V38ifAPm-9m20q_3ueZzdRCYQNyDE3pmA695iaLunjE=s0

UPDATE

If you are new to the blobstore, my advise is to start uploading and serving images from the blobstore. See the code examples in the doc.

After this works, you can optimize and use get_serving_url. You only have to get this serving url once and save in the datastore, so you can use in in your html img tag.

Here is a code example to get a serving url for a blobstore blob, where the blob reference is saved in the datastore:

class Dynamic(db.Model):                                                                        # key : name
    name = db.StringProperty() 
    blob_ref = blobstore.BlobReferenceProperty()
    serving_url = db.LinkProperty()

dyn= Dynamic.get_by_key_name(key_name)
try :                                                                               # get url with size = 0, do not save it
    dyn.serving_url = images.get_serving_url(dyn.blob_ref, size=None, secure_url=True)
except DeadlineExceededError : 
    try :             # sometimes this request fails, retry. This always works fine
        dyn.serving_url = images.get_serving_url(dyn.blob_ref, size=None, secure_url=True)
    except DeadlineExceededError :
        logging.error('Image API get_serving_url deadline error after retry' %(dyn.key().name()))                        
                return None
    dyn.put()