GAE请求处理程序路径

时间:2013-10-11 17:12:43

标签: python google-app-engine

我正在尝试构建一个简单的GAE应用程序,并希望将不同的部分存储在不同的python文件中。例如,我想要一个像:

的URI

XXX / appspot.com /书籍/书/ 42

我的app.yaml

application: bookshop
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

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

- url: .*
  script: main.application

libraries:
- name: webapp2
  version: "2.5.2"

我的books.py文件:

import webapp2

class BookHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('BookHandler')

app = webapp2.WSGIApplication([
    ('/.*/book', BookHandler)
], debug=True)

当我尝试URI时,我得到一个空白屏幕,而不是消息BookHandler。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

以下是您的app.yaml应该是什么(请注意 books /.* 而不是图书/ * )...另外,我认为它一定是个拼写错误,但它必须是 main.app 而不是main.application:

application: bookshop
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

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

- url: .*
  script: main.app

libraries:
- name: webapp2
  version: "2.5.2"

以下是您的books.py应该是什么样的(我假设您想使用部分网址作为参数?):

import webapp2

class BookHandler(webapp2.RequestHandler):
    def get(self, bookid):
        self.response.write('BookHandler' + bookid)

app = webapp2.WSGIApplication([
                               ('/books/(.*)/book', BookHandler)
                               ], debug=True)

编辑:如果您希望自己的网址为/ books / book / 42(就像您在问题中所说的那样),只需将处理程序定义更改为:

app = webapp2.WSGIApplication([
                                   ('/books/book/(.*)', BookHandler)
                                   ], debug=True)

祝你的书店好运! :)

答案 1 :(得分:0)

我首先将您的路线与您的处理程序分开。首先创建一个“routes.py”文件,然后添加应用程序的路由。

from webapp2 import Route

ROUTES = [
    Route('/books/book/<book_id:\d+>', handler='handlers.books.BooksHandler')
]

请注意,我在这里所做的更改是books.py文件现在包含在“处理程序”模块中。您在此模块中的“books.py”文件可能如下所示:

import webapp2


class BooksHandler(webapp2.RequestHandler):

    def get(self, book_id):
        self.response.write('This is the Book Handler %s' % book_id)

最后一步是正确配置webapp2 wsgi应用程序和yaml文件:

main.py:

import webapp2
from routes import ROUTES

app = webapp2.WSGIApplication(ROUTES, debug=True)

的app.yaml:

application: bookshop
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: .*
  script: main.app

libraries:
- name: webapp2
  version: "2.5.2"