2012-12-11 48 views
0

我正在嘗試向我的網站添加聊天,並將一些代碼與我現有的代碼集成在一起。聊天應用程序在原始main.app文件中設置完成後可以正常工作。但是,當我嘗試將相同的代碼移動到handlers.py文件中,然後在routes.py中設置路由時,我收到錯誤,指出模板變量未定義。這兩種不同的代碼在呈現模板的方式上是否存在衝突?他們似乎可以用不同的webapp2的,也就是我的代碼將呈現這樣的模板:將聊天集成到(webapp2 + python 2.7 + Jinja2)

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) 
+0

請發佈你所看到的錯誤。 – Sologoub

+0

@Sologoub感謝您的迴應。所以錯誤是錯誤:'主'對象沒有'render_template'屬性。你怎麼看? – dilanmac

回答

0

您在評論「錯誤發佈特定的錯誤: '主'對象沒有屬性'render_template'「是因爲在你的主處理程序中,你嘗試返回self.render_template。你應該只調用該函數是這樣的:

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

請注意,我沒有檢查你的代碼的其餘部分,因此,如果您遇到任何其他問題,請發表你得到的特定錯誤。

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幾天,那是我遇到的同樣的問題。 希望這個解決方案可以幫助你;)