目前正在尝试使用Python中的Google App Engine创建基本博客。这是我正在使用的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(parent = post_key(), name = name, content = content)
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(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)
然而,当我尝试在我的本地服务器上运行此代码时,这是我得到的错误:
File "F:\Python 2.7\engineapp1\HelloApp\appapp\main.py", line 66, in <module>
('/blog/([0-9]+)', DisplayPost)], debug=True)
TypeError: 'tuple' object is not callable
这里似乎有什么问题?
答案 0 :(得分:8)
您忘记添加逗号。
('/blog/submit', SubmitHandler) <---- missed comma over here
('/blog/([0-9]+)', DisplayPost)], debug=True)
在这种情况下,它就像一个函数,你将一个参数传递给一个元组,导致元组不可调用的错误。
('/blog/submit', SubmitHandler)(parameter)
答案 1 :(得分:4)
该行缺少逗号:
('/blog/submit', SubmitHandler)
应该是:
('/blog/submit', SubmitHandler),
如果没有逗号,则您('/blog/submit', SubmitHandler)('/blog/([0-9]+)', DisplayPost)
会尝试将('/blog/submit', SubmitHandler)
作为一个函数调用'/blog/([0-9]+)'
和DisplayPost
作为参数。因为那不是一个函数,而是一个元组,你会得到那个错误。