1

我开始在 Google App Engine 和 webapp2 网络框架中使用 python 自学网络开发的基础知识。

基本上,我想创建一个主页,在那里我将发布所有指向不同项目的链接。每个链接都将指向一个新的 url,相关的 py 文件将在其中运行。

现在,我只想拥有一个指向 Hello World 页面的链接。而已。对于我的一生,我无法理解如何为这个事件编写处理程序(我什至需要一个 hadler 吗?)。有人可以告诉我我做错了什么吗?

我的文件结构是:

+Main Directory (Folder)
    - app.yaml
    - index.py
    +helloworld (Folder)
        __init__.py
        helloworld.py

app.yaml 文件

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

handlers:
- url: /
  script: index.app

- url: /helloworld.*
  script: helloworld.app

- url: /.*
  script: index.app

libraries:
- name: webapp2
  version: latest

index.py

import webapp2

menu=""" <nav>
<ul>
<li> <a href="/helloworld">Hello World</a></li>
</ul>
</nav>
"""

class HomePage (webapp2.RequestHandler):
    def get(self):
        self.response.out.write(menu)

class HelloHandler(webapp2.RequestHandler):
    def get(self):
        pass

app = webapp2.WSGIApplication([('/', HomePage),
                               ('/helloworld', HelloHandler)], debug=True)

和 helloworld.py:

import webapp2

class HelloWorld(webapp2.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello, World!')

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

当我按下 Hello World 链接时,我确实得到了 localhost:8080/helloworld 的引用,但我看到了一个空白页。日志说: ImportError: No module named app

在用户按下链接后,我应该在 index.py 中写什么让 helloworld 运行。请注意 index.py 和 helloworld.py 不在同一个文件夹中。每个项目都有自己的文件夹,因为稍后我将使用 html/css 模板和一些 javascripts。

提前致谢

4

1 回答 1

1

正如 Paul 所说,我还将从一个简单的示例开始,其中包含单个 webapp 应用程序(它仍然可以处理多个 URL)。但是,通过以下更改,您的示例应该可以工作:

app.yaml 文件:

- url: /helloworld.*
  script: helloworld.helloworld.application

helloworld.helloworld.application实际上是指在 helloworld 包中的 helloworld.py 中定义的应用程序变量(在 index.py 中它被命名为 app)。

然后,您可以从 index.py 中删除 HelloWorld 路由,因为/helloworld被路由到 app.yaml 中定义的 helloworld.py:

索引.py:

app = webapp2.WSGIApplication([('/', HomePage)], debug=True)
于 2014-01-27T12:32:07.500 回答