首次使用webapp2与jinja2遇SyntaxError报错求助
问题根源
你遇到的错误是因为webapp2版本与Python 3不兼容。except Exception, e: 是Python 2的异常捕获语法,Python 3要求使用except Exception as e:,而你安装的webapp2是仅支持Python 2的旧版本,所以在Python 3环境下运行会触发语法错误。
解决步骤
确认Python版本
打开终端运行以下命令,确认你当前使用的是Python 3:python --version # 或者 python3 --version安装兼容Python 3的webapp2版本
使用pip安装支持Python 3的webapp2测试版:pip install webapp2==3.0.0b1修正代码中的两处小问题
- 拼写错误:
JINJA_ENVIROMENT应该改为JINJA_ENVIRONMENT(单词拼写错误,少了一个字母N) - 请求处理方法错误:webapp2的请求处理器需要通过
get()/post()等方法响应HTTP请求,你写的appear_template()不会被框架自动调用,需要修改为:class MainHandler(webapp2.RequestHandler): def get(self): template = JINJA_ENVIRONMENT.get_template('index.html') self.response.write(template.render(jinja_var))
- 拼写错误:
修正后的完整代码
import os import jinja2 import webapp2 from jinja2 import select_autoescape JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader('templates'), autoescape=select_autoescape() ) jinja_var = { 'title': 'this is a test content page' } class MainHandler(webapp2.RequestHandler): def get(self): template = JINJA_ENVIRONMENT.get_template('index.html') self.response.write(template.render(jinja_var)) app = webapp2.WSGIApplication([ ('/.*', MainHandler), ], debug=True)
内容的提问来源于stack exchange,提问作者Old Dude
相关产品推荐
相关产品推荐

