google-app-engine - 如何使用 webapp2 解析路径参数

标签 google-app-engine python-2.7 webapp2 path-parameter

我从 Java REST 背景转为使用 Google App EnginePython。我在使用带有路径参数的 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/

相关文章:

android - 部署到 App Engine 问题 - 您必须登录才能执行此操作

google-app-engine - 如何将数据批量上传到 Google App Engine Datastore?

python - 用于身份验证和登录的 Webapp2

python - 如何使用 webapp2 从表单中获取信息?

python - 与 Google App Engine 上的 NDB 的多对多关系

使用 GAE 和 Google Cloud SQL 的 PhP

java - Google App Engine Java 低级数据存储区 API

python-2.7 - 找不到 py_module_initializer!在 Rust 中构建 Python 模块时

c++ - 乘以二维矩阵。 用pycuda

python - 制作随机电话号码 xxx-xxx-xxxx