Google App Engine с Django получить элемент по ключу из шаблона в представление - PullRequest
1 голос
/ 23 июня 2011

У меня небольшая проблема с механизмом приложений Google. Я хочу получить изображения из хранилища данных, моя функция работает на 100 процентов, если я ввожу ключ в код с другой стороны, если я получу в качестве параметра, это даст мне BadKeyError

вот форма

        {% for image in image.all %}
            <li>{{ image.title }}  </li>
            <img src='getImage?key={{image.key}}' height="100" />   

сопоставлено с

def getImage(request,key):
image = Image()
request.encoding = 'koi8-r'
image = db.get(key) 
#build your response
response = HttpResponse(image.blob)
# 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  

1 Ответ

0 голосов
/ 23 июня 2011

Я создал нечто похожее на то, чего вы хотите достичь .. Надеюсь, это поможет

image.py

import os
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
class Profile(db.Model):
                image=db.BlobProperty()
class disp_image(webapp.RequestHandler):       
                def get(self): 
                    key = self.request.get('key')
                    image = Profile.get(key)
                    self.response.headers['Content-Type'] = "image/png"
                    return self.response.out.write(image.image)
class MainPage(webapp.RequestHandler):
    def get(self):
        image = self.request.get('image')
        pro=Profile()
        if image:   
            pro.image = db.Blob(image)
            import logging
            logging.info('persisted')
            pro.put()
        prof=Profile().all()

        return self.response.out.write(template.render('view.html',{'prof':prof}))
    def post(self):
        return MainPage.get(self)
application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/disp', disp_image)
], debug=True)
def main():
  run_wsgi_app(application)
if __name__ == '__main__':
  main()

view.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/">
<input type="file" name='image'/>
<input type='submit' value="submit"/>
{% for prof in prof %}
<img src="/disp?key={{prof.key}}" />
{% endfor %}
</form>
</body>
</html>

app.yaml

application: sample-app
version: 1
runtime: python
api_version: 1

handlers:
- url: /.*
  script: image.py

url

>>> req.host
'localhost:80'
>>> req.host_url
'http://localhost'
>>> req.application_url
'http://localhost/blog'
>>> req.path_url
'http://localhost/blog/article'
>>> req.url
'http://localhost/blog/article?id=1'
>>> req.path
'/blog/article'
>>> req.path_qs
'/blog/article?id=1'
>>> req.query_string
'id=1'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...