0

我的代码如下。它仅加载第一个图像表单“帖子”数据库。我怎样才能从数据库中加载所有图像????

import webapp2
import os
import jinja2
from google.appengine.ext import db
from google.appengine.api import images

神社模板代码

template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
                           autoescape = True)

class Handler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render_str(self, template, **params):
        t = jinja_env.get_template(template)
        return t.render(params)

    def render(self, template, **kw):
        self.write(self.render_str(template, **kw))

html图片上传

form="""
<form action="/" enctype="multipart/form-data" method="post">
          <div><label>Avatar:</label></div>
          <div><input type="file" name="img"/></div>
          <input type="submit" value="switch">
          </form>
"""

图像数据库

class Greeting(db.Model):
    avatar = db.BlobProperty() 
    created = db.DateTimeProperty(auto_now_add = True)

这是为了形象。但它只加载第一个图像表单“帖子”数据库。如何从数据库中加载所有图像?

class Image(Handler):
    def get(self):
        posts = db.GqlQuery("select * from Greeting order by created desc")
        for post in posts:

            self.response.headers['Content-Type'] = 'image/jpg'
            self.response.out.write(post.avatar)

MainHandler 并调整图像大小

class MainHandler(Handler):
    def get(self):
        self.response.out.write(form)
    def post(self):
        avatar = images.resize(self.request.get('img'), 400, 400)
        greeting = Greeting()
        greeting.avatar = db.Blob(avatar)
        greeting.put()    


app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/img', Image),],
                               debug=True)
4

1 回答 1

1

而不是for post in posts在处理程序调用 Image 时通过您的jinja2模板迭代帖子 ()。使用 . 将帖子传递到您的模板self.response.out.write(posts)

jinja2 模板:

{% for post in posts %}
    {{post}}
{% endfor %}
于 2012-11-18T00:56:18.847 回答