Как разобрать путь-параметр с webapp2

Я пришел из Java REST фона для Python на 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)

1 ответ

Решение

Посмотрите на маршрутизацию URI в webapp2. Здесь вы можете сопоставить / направить URI и получить аргументы. Эти ключевые аргументы передаются вашему обработчику: http://webapp2.readthedocs.io/en/latest/guide/routing.html.

Вот пример 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!
Другие вопросы по тегам