我正在关注Google App Engine tutorial(这是他们的complete demo code on GitHub)并希望:
我无法理解:
A)如何编写问候语发布时调用的重定向代码,以便重定向到 / greeting / numeric-id 等网址。
B)如何编写用户重定向到的详细信息视图和模板页面,以便显示问候ID 和图像。
这是一个显示我想要做的事情的图表:
这是 guestbook.py :
import os
import urllib
from google.appengine.api import images
from google.appengine.api import users
from google.appengine.ext import ndb
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext import blobstore
import jinja2
import webapp2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
DEFAULT_GUESTBOOK_NAME = 'default_guestbook'
def guestbook_key(guestbook_name=None):
"""Constructs a Datastore key for a Guestbook entity with name."""
return ndb.Key('Guestbook', guestbook_name or 'default_guestbook')
class Author(ndb.Model):
"""Sub model for representing an author."""
identity = ndb.StringProperty(indexed=False)
email = ndb.StringProperty(indexed=False)
class Greeting(ndb.Model):
"""A model for representing an individual Greeting entry."""
author = ndb.StructuredProperty(Author)
date = ndb.DateTimeProperty(auto_now_add=True)
avatar = ndb.BlobProperty(indexed=False, required=True)
other = ndb.BlobProperty(indexed=False, required=True)
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
guestbook_name = self.request.get('guestbook_name')
greetings = Greeting.query(
ancestor=guestbook_key(guestbook_name)) \
.order(-Greeting.date) \
.fetch(10)
self.response.out.write("""
<form action="/sign?%s"
enctype="multipart/form-data"
method="post">
<label>Avatar:</label>
<input type="file" name="avatar"/><br>
<label>Other Image:</label>
<input type="file" name="other"/><br>
<input type="submit" value="Submit">
</form>
</body>
</html>""" % (urllib.urlencode({'guestbook_name': guestbook_name})))
class Image(webapp2.RequestHandler):
""" Handle image stored as blobs of bytes.
No idea how the template knows to select a particular one. """
def get(self):
avatar_greeting_key = ndb.Key(urlsafe=self.request.get('avatar_id'))
other_greeting_key = ndb.Key(urlsafe=self.request.get('other_id'))
avatar_greeting = avatar_greeting_key.get()
other_greeting = other_greeting_key.get()
if avatar_greeting.avatar:
self.response.headers['Content-Type'] = 'image/png'
self.response.out.write(avatar_greeting.avatar)
elif other_greeting.other:
self.response.headers['Content-Type'] = 'image/png'
self.response.out.write(other_greeting.other)
else:
self.response.out.write('No image')
class Guestbook(webapp2.RequestHandler):
def post(self):
guestbook_name = self.request.get('guestbook_name',
DEFAULT_GUESTBOOK_NAME)
greeting = Greeting(parent=guestbook_key(guestbook_name))
if users.get_current_user():
greeting.author = Author(
identity=users.get_current_user().user_id(),
email=users.get_current_user().email())
avatar = self.request.get('avatar')
avatar = images.resize(avatar, 100, 100)
other = self.request.get('other')
other = images.resize(other, 400, 300)
greeting.avatar = avatar
greeting.other = other
greeting.put()
query_params = {'guestbook_name': guestbook_name}
self.redirect('/greeting/%d' % greeting.key.id())
class Detail(webapp2.RequestHandler):
""" Individual greeting. """
def get(self, *args, **kwargs):
guestbook_name = self.request.get('guestbook_name', DEFAULT_GUESTBOOK_NAME)
greeting = Greeting.get_by_id(args[0],
parent=guestbook_key(guestbook_name))
template_values = {
'greeting': greeting,
}
template = JINJA_ENVIRONMENT.get_template('detail.html')
self.response.write(template.render(template_values))
app = webapp2.WSGIApplication([
('/', MainPage),
('/img', Image),
('/sign', Guestbook),
('/greeting/(\d+)', Detail),
], debug=True)
我的 detail.html 模板:
<!DOCTYPE html>
{% autoescape true %}
<html>
<head>
<title>Greeting {{ greeting.id }}</title>
</head>
<body>
<h2>Greeting {{ greeting.id }}</h2>
Avatar: <img src="/img?avatar_id={{ greeting.key.urlsafe() }}">
<br>
Other: <img src="/img?other_id={{ greeting.key.urlsafe() }}">
</body>
</html>
{% endautoescape %}
我的 app.yaml ,以防它有用:
runtime: python27
api_version: 1
threadsafe: true
# Handlers match in order, put above the default handler.
handlers:
- url: /stylesheets
static_dir: stylesheets
- url: /.*
script: guestbook.app
libraries:
- name: webapp2
version: latest
- name: jinja2
version: latest
错误:
Traceback (most recent call last):
File "/Users/simon/Projects/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
File "/Users/simon/Projects/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
File "/Users/simon/Projects/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "/Users/simon/Projects/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__
return handler.dispatch()
File "/Users/simon/Projects/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "/Users/simon/Projects/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/Users/simon/Projects/guestbook/guestbook.py", line 111, in get
self.response.write(template.render(template_values))
File "/Users/simon/Projects/google-cloud-sdk/platform/google_appengine/lib/jinja2-2.6/jinja2/environment.py", line 894, in render
return self.environment.handle_exception(exc_info, True)
File "/Users/simon/Projects/guestbook/detail.html", line 9, in top-level template code
Avatar: <img src="/img?avatar_id={{ greeting.key.urlsafe() }}">
UndefinedError: 'None' has no attribute 'key'
非常感谢任何帮助,甚至更好的示例代码。 GAE / webapp2博客教程包含详细的示例代码和列表视图和模板,但是GAE BlobStore的数据结构可能不适合博客吗?
更新 如果我添加在Dan的答案中提供的python检查代码,我得到500错误而不是堆栈跟踪,如果我尝试模板检查,我得到一个空白的问候页面。我用我的完整代码和解释我想要做的图表更新了这个问题。
答案 0 :(得分:2)
我将从B
开始:
该错误表示greeting
值为None
,导致在模板呈现期间jinja2尝试在greeting.key
中展开{{ greeting.key.urlsafe() }}
时出现异常。
一个选项是重新安排处理程序代码,以防止在不满足必要条件时呈现该模板,可能是这样的:
...
greeting = Greeting.get_by_id(args[0])
if not greeting or not isinstance(greeting.key, ndb.Key):
# can't render that template, invalid greeting.key.urlsafe()
webapp2.abort(500)
return
template_values = {
'greeting': greeting,
}
template = JINJA_ENVIRONMENT.get_template('detail.html')
self.response.write(template.render(template_values))
...
或者你可以用适当的检查来包装引用变量的模板区域(恕我直言,更难和更脆弱,tho-python比jinja2更适合这种逻辑),这些都是这样的:
{% if greeting and greeting.key %}<img src="/img?avatar_img_id={{ greeting.key.urlsafe() }}">{% endif %}
现在到A
。
简而言之 - 这不是一个好主意,主要是因为您尝试在网址中使用的数字ID是不唯一,除了同一个父实体下的问候语!。这在某种程度上解释了为什么问候无效导致B
答案出错。
greeting = Greeting.get_by_id(args[0])
将返回None
,除非您还创建了一个问候实体,其中包含您传递的ID args[0]
和没有父级!
为了通过ID获取您创建的问候语:
greeting = Greeting(parent=guestbook_key(guestbook_name))
你需要打电话:
greeting = Greeting.get_by_id(args[0],
parent=guestbook_key(guestbook_name))
如果你想继续朝着同一个方向,你也可以在问候语URL中对guestbook_name
进行编码,这样你就可以获得所需的父键,也许就是这样:
/guestbook/<guestbook_name>/greeting/<numeric-id>.
您还需要仔细查看图像处理。您有架构不一致性:在图表和模型中,您同时将头像和另一个图像附加到单个问候实体,但在Image
处理程序中,每个图像都附加到单独的问候语。处理程序也根本不映射到图像的URL(根据架构决策,还需要对定位适当图像所需的数据进行额外编码)。
在你完成所有工作之前,我担心你还有很多工作要做,而不仅仅是适合单个SO问题。退一步,重新思考你的架构,将它分成更小的部分,一次只关注一个部分并开始运行。熟悉各种技术后,您可以立即更好地解决整个问题。