You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

首次使用webapp2与jinja2遇SyntaxError报错求助

问题根源

你遇到的错误是因为webapp2版本与Python 3不兼容。except Exception, e: 是Python 2的异常捕获语法,Python 3要求使用except Exception as e:,而你安装的webapp2是仅支持Python 2的旧版本,所以在Python 3环境下运行会触发语法错误。

解决步骤
  1. 确认Python版本
    打开终端运行以下命令,确认你当前使用的是Python 3:

    python --version
    # 或者
    python3 --version
    
  2. 安装兼容Python 3的webapp2版本
    使用pip安装支持Python 3的webapp2测试版:

    pip install webapp2==3.0.0b1
    
  3. 修正代码中的两处小问题

    • 拼写错误: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:45:34