将 2 个 URL 路由到 1 个处理程序
我正在尝试在龙卷风上实现某种 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,他应该会看到错误消息
I'm trying to implement some sort of API on tornado and I have such question:
is it possible to route two urls to one handler separating by method.
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
]
So if someone trying to send POST to the first url he should see error message
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用@ee_vin 的答案来执行此操作。但是,在这种情况下,为什么不创建两个处理程序呢?这要简单得多:
任何发布到第一个 URL 或获取第二个 URL 的人都会收到方法不支持的错误。
You can use @ee_vin's answer to do this. However, in this situation, why not create two handlers? It's much simpler:
Anyone posting to the first URL or GETting the second would get a method not supported error.
实现您想要做的事情的一种方法是在您的网址中使用正则表达式并检查方法处理程序中的属性。
要映射的 url 示例
以及相应处理程序的示例,
我会将“my_param”选项映射到字典,以保持清晰,并避免在需要更改这些值或添加新 url 时深入处理程序。
One way to achieve what you want to do is to use regex in your url and check for the attribute in your methods handler.
Example of urls to map
And an example of the corresponding handler
I would map 'my_param' options to a dictionary to keep things clear and to avoid me to dive into the handler if I need to change these values or if I want to add new urls.