如何在python / jinja的html页面上显示图像

时间:2015-05-23 06:24:24

标签: python-2.7 google-app-engine jinja2 blobstore internal-server-error

我已在 model.py 中创建了课程Blog,并且其属性photoBlobkeyProperty。 我的问题是如何在html页面上显示这张照片..所有我得到的只是关键。我不太了解Jinja和python所以请帮助.. :)

{% if blog.photo == None %}
    <img src="static/css/img/photo.jpg" /><br/>
{% elif blog.photo %}
    <span>{{blog.photo.key.get()}}</span><br/>
{% endif %}

第一部分正在运作,但是其他部分正在给我

Internal Server Error(UndefinedError: 'google.appengine.api.datastore_types.BlobKey object' has no attribute 'key')

如果我删除key.get()部分,那么它会向我提供该照片的blobkey 请帮助..

1 个答案:

答案 0 :(得分:0)

这是我处理blobstore图像的方法。

1个处理图像的处理程序:

class AvatarDownloadHandler(BaseHandler):
    """
    Handler for Serve User's Avatar
    """

    def get(self):

        params = {}

        if self.request.get('id') != '':
            logging.info('loading image from id: %s' % self.request.get('id'))
            user_info = self.user_model.get_by_id(long(self.request.get('id')))
            if user_info != None:
                if user_info.picture:
                    self.response.headers['Content-Type'] = 'image/png'
                    self.response.out.write(user_info.picture)
                else:
                    self.response.headers['Content-Type'] = 'text/plain'
                    self.response.out.write('No image')
        else:
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.out.write('No image ID')

有了这个处理程序,然后在Jinja / HTML方面我只使用ID参数调用下载处理程序的路由URL,即:

给定路线:

RedirectRoute('/img/', handlers.AvatarDownloadHandler, name='img-download', strict_slash=True),

JINJA / HTML使用:

<img src="/img/?id=5671617594130432">

1个用于上传图片的处理程序:

class AvatarUploadHandler(BaseHandler):
    """
    Handler for Edit User's Avatar
    """
    @user_required
    def post(self):
        """ Handles upload"""

        params = {}
        if not self.user:
            return self.render_template('home.html', **params)
        if not self.form.validate():
            message = _(messages.saving_error)
            self.add_message(message, 'danger')
            return self.redirect_to('edit-profile')
        picture = self.request.get('picture')
        user_info = self.user_model.get_by_id(long(self.user_id))
        if user_info != None:
            # Transform the image
            avatar = images.resize(picture, width=200, height=200, crop_to_fit=True, quality=100)
            user_info.picture = avatar
            user_info.put()
            message = _(messages.saving_success)
            self.add_message(message, 'success')
            self.redirect_to('edit-profile')

        message = _(messages.saving_error)
        self.add_message(message, 'danger')
        return self.redirect_to('edit-profile')


    @webapp2.cached_property
    def form(self):
        f = forms.AvatarForm(self)
        return f