【问题标题】:routing 2 urls to 1 handler将 2 个 url 路由到 1 个处理程序
【发布时间】:2011-10-21 21:00:28
【问题描述】:

我正在尝试在龙卷风上实现某种 API,我有这样的问题: 是否可以将两个 url 路由到一个按方法分隔的处理程序。

class Handler():
   def get(self):
       #only for the first url
   def post(self):
       #only for the secornd url
handlers = [
   (r"/url1",Handler), #only GET are allowed
   (r"/url2",Handler), #only POST are allowed
]

因此,如果有人尝试将 POST 发送到第一个 url,他应该会看到错误消息

【问题讨论】:

    标签: python url-routing tornado


    【解决方案1】:

    您可以使用@ee_vin 的答案来执行此操作。但是,在这种情况下,为什么不创建两个处理程序呢?它更简单:

    class OneHandler():
       def get(self):
           #only for the first url
    
    class TwoHandler():
       def post(self):
           #only for the second url
    
    handlers = [
       (r"/url1",OneHandler), #only GET are allowed
       (r"/url2",TwoHandler), #only POST are allowed
    ]
    

    任何发布到第一个 URL 或获取第二个 URL 的人都会收到方法不受支持的错误。

    【讨论】:

      【解决方案2】:

      实现您想要做的事情的一种方法是在您的网址中使用正则表达式并检查您的方法处理程序中的属性。

      要映射的网址示例

      url_patterns = [
          # here we want to map url1 url2 and url
          (r"/url([1|2])/", OneAndTwoHandler),
      ]
      

      以及对应的handler示例

      class OneAndTwoHandler(CustomRequestHandler):
          def get(self, my_param, *args, **kwargs):
              if my_param == '2':
                  raise HTTPError(405)
              # code for only the first url here...
      
          def post(self, entry, *args, **kwargs):
              if my_param == '1':
                  raise HTTPError(405)
              # code for only the first url here...
      

      我会将 'my_param' 选项映射到字典以保持清晰,并避免我在需要更改这些值或想要添加新 URL 时深入处理程序。

      my_dict_urls = {
          'get': (1,2,3,4),
          'post': (3,5)
      }
      
      if int(my_param) not in my_dict_urls.get('get'):
          # ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-20
        • 1970-01-01
        • 2013-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-14
        相关资源
        最近更新 更多