0

我正在尝试将聊天添加到我的网站,并将一些代码与我现有的代码集成。当聊天应用程序全部设置在原始 main.app 文件中时,它本身就可以正常工作。但是,当我尝试将相同的代码移动到 handlers.py 文件中,然后在 routes.py 中设置路由时,我收到错误消息,提示模板变量未定义。两种不同的代码在呈现模板的方式上是否存在冲突?他们似乎以不同的方式使用 webapp2,即我的代码呈现这样的模板:

self.render_template('secure_zone.html', **params)

和这样的聊天应用程序:

self.response.out.write(render("main.html",
                                   username=username,
                                   usernameerror=usernameerror,
                                   channel=channelname,
                                   channelerror=channelerror))

两者都可以接受吗?

这是我的 handlers.py 文件:

Routes are setup in routes.py and added in main.py
"""
import httpagentparser
from boilerplate import models
from boilerplate.lib.basehandler import BaseHandler
from boilerplate.lib.basehandler import user_required


class SecureRequestHandler(BaseHandler):
"""
Only accessible to users that are logged in
"""

@user_required
def get(self, **kwargs):
    user_session = self.user
    user_session_object = self.auth.store.get_session(self.request)

    user_info = models.User.get_by_id(long( self.user_id ))
    user_info_object = self.auth.store.user_model.get_by_auth_token(
        user_session['user_id'], user_session['token'])

    try:
        params = {
            "user_session" : user_session,
            "user_session_object" : user_session_object,
            "user_info" : user_info,
            "user_info_object" : user_info_object,
            "userinfo_logout-url" : self.auth_config['logout_url'],
            }
        return self.render_template('secure_zone.html', **params)
    except (AttributeError, KeyError), e:
        return "Secure zone error:" + " %s." % e

这是聊天应用程序的 main.py 文件:

import os
import hashlib
import urllib
import logging
import re
import json

import webapp2
import jinja2
from google.appengine.api import channel as channel_api # 'channel' is kind of ambiguous in     context
from google.appengine.ext import db
from google.appengine.api import memcache

# This section will eventually get moved to a Handler class
template_dir = os.path.join(
    os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(
    loader = jinja2.FileSystemLoader(template_dir),
    autoescape = True)

def render_str(template, **params):
'''Returns a string of the rendered template'''
t = jinja_env.get_template(template)
return t.render(params)

def render(template, **kw):
'''Render using the template and parameters'''
return(render_str(template, **kw))
# End Handler

class Main(webapp2.RequestHandler):
def get(self):
    '''Show connection page'''
    return self.render_template("main.html", channel="#udacity")

def post(self):
    '''Displays chat UI'''
    username = self.request.get('username')
    channelname = self.request.get('channel')
    usernameerror = ""
    if not username:
        usernameerror="Please enter a username"
    elif not re.compile(r'^[a-zA-Z0-9_-]{3,20}$').match(username):
        usernameerror = "Username must consist of 3-20 alphanumeric characters."
    elif get_user(username):
        usernameerror="Username already in use"
    channelerror = ""
    if channelname and not re.compile(r'^#[\w]{3,20}$').match(channelname):
        channelerror="Channel must consist of 3-20 alpha_numeric characters and start with a #"
    if len(usernameerror+channelerror) > 0:
        self.response.out.write(render("main.html",
                                       username=username,
                                       usernameerror=usernameerror,
                                       channel=channelname,
                                       channelerror=channelerror))

app = webapp2.WSGIApplication([
                           ('/', Main),
                           ('/communication', Communication),
                           ('/_ah/channel/connected/?', Connect),
                           ('/_ah/channel/disconnected/?', Disconnect)
                           ], debug=True)
4

2 回答 2

0

您在评论“错误:'Main' 对象没有属性'render_template'”中发布的具体错误是因为在您的 Main 处理程序中,您尝试返回 self.render_template。你应该像这样调用函数:

render_template("main.html", channel="#udacity")

请注意,我没有检查您的其余代码,因此如果您遇到任何其他问题,请发布您遇到的具体错误。

于 2012-12-13T17:03:07.507 回答
0

那是因为你的 webapp2.RequestHandler 没有对应的函数“render_template”

您可以使用添加了 render_template 函数的 BaseHandler 来实现模板渲染

from google.appengine.ext.webapp import template   

class BaseHandler(webapp2.RequestHandler):
    def render_template(self, filename, **template_args):
        path = os.path.join(os.path.dirname(__file__), 'templates', filename)
        self.response.write(template.render(path, template_args))

class Main(BaseHandler):
    def get(self):
        '''Show connection page'''
        return self.render_template("main.html", channel="#udacity")

参考: http: //blog.notdot.net/2011/11/Migrating-to-Python-2-7-part-2-Webapp-and-templates

我刚开始使用 webapp2 + python 2.7 + Jinja2 几天,这也是我遇到的同样的问题。希望这个解决方案可以帮助你;)

于 2013-09-27T04:42:47.723 回答