3

我刚刚开始使用 webapp2 框架和 jinja2 模板在 python 中使用谷歌应用引擎。我似乎无法启动并运行我的第一个非常简单的脚本。我想要的只是让脚本为 index.html 文件提供服务(位于同一目录中)。

这是 app.yaml 文件:

libraries
- name: webapp2
  version: latest
- name: jinja2
  version: latest

application: practice
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: practice.application

这是练习.py:

import os
import webapp2
from jinja2 import Enviroment, FileSystemLoader

loader = jinja2.FileSystemLoader(os.path.dirname(__FILE__)
env = jinja2.Enviroment(loader)

class MainPage(webapp2.RequestHandler):
    def get(self):
        template = env.get_template('index.html')
        self.response.write(template.render())

application = webapp2.WSGIApplication([
 ('/', MainPage),
 ], debug=True)

更新:我从 Google 应用引擎启动器在本地运行它。当我尝试打开文件时,我收到带有描述的服务器错误

The website encountered an error while retrieving http://localhost:9080/. It may be
down for maintenance or configured incorrectly."
4

2 回答 2

1

这就是您的代码无法运行的原因:

  • 您的 app.yaml 格式错误
  • 环境拼写错误
  • 您在第 5 行缺少右括号
  • 你还没有导入 jinja2 库
  • 变量__ FILE __未声明

这是我认为您的代码应如下所示的内容:

应用程序.yaml

application: practice
version: 1
runtime: python27
api_version: 1
threadsafe: true

libraries:
- name: webapp2
  version: latest
- name: jinja2
  version: latest

handlers:
- url: /.*
  script: practice.application

练习.py

import jinja2
import os
import webapp2

loader = jinja2.FileSystemLoader(os.path.dirname(__file__))
env = jinja2.Environment(loader=loader)

class MainPage(webapp2.RequestHandler):
    def get(self):
        template = env.get_template('index.html')
        self.response.write(template.render())

application = webapp2.WSGIApplication([
 ('/', MainPage),
 ], debug=True)

我建议您执行以下操作以使您的生活更轻松:

希望这可以帮助您上路。

快乐编码:)

于 2013-06-14T07:34:35.713 回答
0

In webapp2 you should use app instead of application, so last line should look like this:

app = webapp2.WSGIApplication([('/', MainPage),], debug=True)
于 2013-08-29T08:43:55.570 回答