2011-08-13 3 views
4

나는 Route 메커니즘을 사용하여 webapp2 프레임 워크를 배우고 있습니다.webapp2. 선택적 앞부분이있는 부분

내 응용 프로그램이이 같은 URI를 수용하도록되어 :

/poll/abc-123 
/poll/abc-123/ 
/poll/abc-123/vote/  # post new vote 
/poll/abc-123/vote/456 # view/update a vote 

설문 조사 선택적 그래서 위의 모든 이런 식으로도 작동한다, 범주로 구성 될 수있다

/mycategory/poll/abc-123 
/mycategory/poll/abc-123/ 
/mycategory/poll/abc-123/vote/ 
/mycategory/poll/abc-123/vote/456 

내 잘못된 구성 :

app = webapp2.WSGIApplication([ 
    webapp2.Route('/<category>/poll/<poll_id><:/?>', PollHandler), 
    webapp2.Route('/<category>/poll/<poll_id>/vote/<vote_id>', VoteHandler), 
], debug=True) 

질문 : 구성을 어떻게 수정합니까?

가능한 경우 GAE CPU 시간/호스팅 비용에 맞게 최적화해야합니다. 예를 들어, 각 항목에 대해 두 줄을 추가하면 범주별로 하나의 줄과 범주가없는 줄이 더 빨리 나타납니다.

답변

7

webapp2는 공통 접두어를 다시 사용할 수있는 메커니즘을 가지고 있지만이 경우에는 다릅니다 같이, 그 경로를 중복되지 않도록 할 수 없습니다

app = webapp2.WSGIApplication([ 
    webapp2.Route('/poll/<poll_id><:/?>', PollHandler), 
    webapp2.Route('/poll/<poll_id>/vote/<vote_id>', VoteHandler), 
    webapp2.Route('/<category>/poll/<poll_id><:/?>', PollHandler), 
    webapp2.Route('/<category>/poll/<poll_id>/vote/<vote_id>', VoteHandler), 
], debug=True) 

을 당신은 많은 경로를 추가하는 방법에 대한 걱정한다. 그들은 정말로 싸고 일치합니다. 수만 명이 아니라면 경로 수를 줄이는 것이 중요하지 않습니다.

작은 메모 : 첫 번째 경로는 선택적 끝 슬래시를 허용합니다. 대신 옵션을 사용하여 RedirectRoute을 사용하면 하나만 허용하고 다른 쪽을 액세스하는 경우 리디렉션 할 수 있습니다. 이것은 잘 설명되어 있지 않지만 잠시 동안 주변에있었습니다. explanation in the docstring을 참조하십시오.

+0

고마워요, 로드리고! – zengabor

1

@moraes 위에 무료 응답으로 내 솔루션을 추가 할 예정입니다.
다음과 같은 문제가있는 다른 사람들은보다 완전한 답을 얻을 수 있습니다. 또한

  • Optional Parameter Problem
  • Trailing Slash Problem
    1. , 나는 하나의 정규식 얼마나 노선 모두 /entity/create/entity/edit/{id}을 알아 냈어.
      다음은 다음 URL 패턴을 지원하는 경로입니다.

      1. /
      2. /myentities
      3. /myentities/
      4. /myentities//
      5. /myentities를 만들 생성/
      6. /myentities/편집/{ENTITY_ID}
      SITE_URLS = [ 
          webapp2.Route(r'/', handler=HomePageHandler, name='route-home'), 
      
          webapp2.Route(r'/myentities/<:(create/?)|edit/><entity_id:(\d*)>', 
           handler=MyEntityHandler, 
           name='route-entity-create-or-edit'), 
      
          webapp2.SimpleRoute(r'/myentities/?', 
           handler=MyEntityListHandler, 
           name='route-entity-list'), 
      ] 
      
      app = webapp2.WSGIApplication(SITE_URLS, debug=True) 
      

      아래는 내입니다.내 모든 핸들러가 상속합니다.

      class BaseHandler(webapp2.RequestHandler): 
          @webapp2.cached_property 
          def jinja2(self): 
           # Sets the defaulte templates folder to the './app/templates' instead of 'templates' 
           jinja2.default_config['template_path'] = s.path.join(
            os.path.dirname(__file__), 
            'app', 
            'templates' 
           ) 
      
           # Returns a Jinja2 renderer cached in the app registry. 
           return jinja2.get_jinja2(app=self.app) 
      
          def render_response(self, _template, **context): 
           # Renders a template and writes the result to the response. 
           rv = self.jinja2.render_template(_template, **context) 
           self.response.write(rv) 
      

      는 아래 구글 앱 엔진 데이터 저장소 API에 대한 get() 메소드 서명 내 MyEntityHandler 파이썬 클래스입니다.

      class MyEntityHandler(BaseHandler): 
          def get(self, entity_id, **kwargs): 
           if entity_id: 
            entity = MyEntity.get_by_id(int(entity_id)) 
            template_values = { 
             'field1': entity.field1, 
             'field2': entity.field2 
            } 
           else: 
            template_values = { 
             'field1': '', 
             'field2': '' 
            } 
          self.render_response('my_entity_create_edit_view_.html', **template_values) 
      
      
      
          def post(self, entity_id, **kwargs): 
           # Code to save to datastore. I am lazy to write this code. 
      
           self.redirect('/myentities')