我正在尝试使用Python中的Google App Engine构建基本博客模型。但是,我想我的代码出了问题,当我尝试在一个页面上显示所有发布的博客条目时,我收到了404错误。这是python代码:
import os
import re
import webapp2
import jinja2
from string import letters
from google.appengine.ext import db
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))
def post_key(name = "dad"):
return db.Key.from_path('blog', name)
class Blogger(db.Model):
name = db.StringProperty()
content = db.TextProperty()
created = db.DateTimeProperty(auto_now_add = True)
def render(self):
self._render_text = self.content.replace('\n', '<br>')
return render_str("post.html", p = self)
class MainPage(Handler):
def get(self):
self.response.write("Visit our blog")
class BlogHandler(Handler):
def get(self):
posts = db.GqlQuery("SELECT * FROM Blogger order by created desc")
self.render("frontblog.html", posts = posts)
class SubmitHandler(Handler):
def get(self):
self.render("temp.html")
def post(self):
name = self.request.get("name")
content = self.request.get("content")
if name and content:
a = Blogger(name = name, content = content, parent = post_key())
a.put()
self.redirect('/blog/%s' % str(a.key().id()))
else:
error = "Fill in both the columns!"
self.render("temp.html", name = name, content = content, error = error)
class DisplayPost(Handler):
def get(self, post_id):
po = Blogger.get_by_id(int(post_id))
if po:
self.render("perma.html", po = po)
else:
self.response.write("404 Error")
app = webapp2.WSGIApplication([('/', MainPage),
('/blog', BlogHandler),
('/blog/submit', SubmitHandler),
('/blog/([0-9]+)', DisplayPost)], debug=True)
发布我的内容后,它会被重定向到永久链接。但是,这是我提交帖子时出错的错误:
404 Not Found
The resource could not be found
这是frontblog.html源代码,以防有用:
<!DOCTYPE html>
<html>
<head>
<title>CS 253 Blog</title>
</head>
<body>
<a href="/blog">
CS 253 Blog
</a>
<div id="content">
{% block content %}
{%for post in posts%}
{{post.render() | safe}}
<br></br>
{%endfor%}
{% endblock %}
</div>
</body>
</html>
基本上,我没有被重定向到永久链接页面。什么似乎是问题?
答案 0 :(得分:1)
当你创建帖子时,你给它一个父母(不知道为什么)。但是当你得到它时,你只能通过ID这样做,而不考虑父ID。在数据存储区中,键实际上是一个由所有父类和ID /名称组成的路径,然后是当前实体的路径,并获取需要传递完整路径的对象。
这里可能的解决方案:
Blogger.get_by_id(post_id, parent=parent_key())
- 显然这仅在父级始终相同时才有效; Blogger.get(key)
- 您还需要更改路由正则表达式以接受字母数字字符,例如'/blog/(\w+)'
,并更改重定向到'/blog/%s' % a.key()
。