4

我来自 Java REST 背景到Pythonon Google App Engine's. 我需要一些使用webapp2路径参数的帮助。下面是 Java 如何读取请求的示例。有人会将代码翻译成python如何读取它webapp2吗?

// URL: my_dogs/user_id/{user_id}/dog_name/{a_name}/breed/{breed}/{weight}

@Path("my_dogs/user_id/{user_id}/dog_name/{a_name}/breed/{breed}/{weight}")
public Response getMyDog(
    @PathParam("user_id") Integer id,
    @PathParam("a_name") String name,
    @PathParam("breed") String breed,
    @PathParam("weight") String weight
){

//the variables are: id, name, breed, weight.
///use them somehow

}

我已经浏览了 google 上的示例(https://developers.google.com/appengine/docs/python/gettingstartedpython27/usingwebapp)。但我不知道如何扩展简单

app = webapp2.WSGIApplication([('/', MainPage),
                           ('/sign', Guestbook)],
                          debug=True)
4

1 回答 1

5

看看 webapp2 中的 URI 路由。在这里,您可以匹配/路由 URI 并获取参数。这些关键字参数将传递给您的处理程序:http ://webapp2.readthedocs.io/en/latest/guide/routing.html#the-url-template

这是一个带有一个参数 {action} 的 helloworld 示例:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import webapp2

class ActionPage(webapp2.RequestHandler):

    def get(self, action):

        self.response.headers['Content-Type'] = 'text/plain'        
        self.response.out.write('Action, ' + action)

class MainPage(webapp2.RequestHandler):

    def get(self):

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

app = webapp2.WSGIApplication([
        webapp2.Route(r'/<action:(start|failed)>', handler=ActionPage),
        webapp2.Route(r'/', handler=MainPage),                    
], debug=True)

还有你的 app.yaml:

application: helloworld
version: 1
runtime: python27
api_version: 1
threadsafe: false

handlers:
- url: (.*)
  script: helloworld.app

libraries:
- name: webapp2
  version: latest

当我尝试时,这在 SDK 中运行良好

http://localhost:8080/start   # result: Action, start
or
http://localhost:8080         # result: Hello, webapp2 World!
于 2012-12-03T03:11:12.277 回答