我从 Java REST 背景转为使用 Google App Engine
的 Python
。我在使用带有路径参数的 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)
最佳答案
查看 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!
关于google-app-engine - 如何使用 webapp2 解析路径参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676458/