在Google App Engine中使用Python入门指南

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

以下是practice.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."

你需要描述出现了什么问题?是出现了错误,没有响应,还是从服务器得到的响应不符合您的预期? - Tim Hoffman
这是部署的代码还是本地运行?你的 urls.py 文件里有什么内容? - John Lyon
你如何启动本地的Google App Engine Launcher?看看你从哪里启动它,看看是否可以找到某种日志,并将其输出放在这里。 - moowiz2020
2个回答

1

以下是您的代码无法运行的原因:

  • 您的app.yaml格式不正确
  • 拼写错误的环境变量
  • 第5行缺少一个闭合括号
  • 您没有导入jinja2库
  • 变量__FILE__未声明

以下是我认为您的代码应该是这样的:

app.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

practice.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)

我建议你按照以下步骤来使你的生活更加容易: 希望这可以帮助你上路。
愉快编程 :)

非常感谢您详细的答复!您提供的建议完美地解决了我的问题。正如您所看到的,我在Python和Web编程方面非常新手,感谢您花时间帮助我纠正初级错误。 - user2484764

0
webapp2 中,你应该使用 app 而不是 application,因此最后一行应该是这样的:
app = webapp2.WSGIApplication([('/', MainPage),], debug=True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接