基于Python Web框架中的Accept标头的路由请求 [英] Route requests based on the Accept header in Python web frameworks

查看:202
本文介绍了基于Python Web框架中的Accept标头的路由请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些经验与不同的Web框架(Django,web.py,金字塔和CherryPy),我想知道哪一个将更容易,希望更干净地实现一个路由调度程序到另一个视图/处理程序基于Accept标题和HTTP方法,例如:

 接受:application / json 
POST / post /

的处理方式与:

 接受:text / html 
POST / post /

所以请求被路由到MIMEapplication / json和HTTP方法POST的相应处理程序的特定视图。



我知道如何在CherryPy中实现类似的功能,但是由于我直接调用特定方法而不是从调度程序自动调用,所以我不能使用CherryPy工具来进行内部重定向。另一个选择是从头开始实现一个全新的调度程序,但这是最后一个选项。



我知道在URL中使用扩展名的替代方法,如 /post.json /post/.json ,但我希望保持相同的URL?

解决方案

如果您正在寻找的是一个框架,可以轻松实现,然后使用 金字塔



金字塔视图定义是使用谓词,而不仅仅是路由,只有当所有谓词匹配时,视图才匹配。一个这样的谓词是 accept 谓词,它完全符合你想要的;使视图切换取决于接受标题简单易用:

  from pyramid.view import view_config 

@view_config(route_name ='some_api_name',request_method ='POST',accept ='application / json')
def handle_someapi_json(request):
#return JSON

@view_config(route_name ='some_api_name',request_method ='POST',accept ='text / html')
def handle_someapi_html(request):
#return HTML


I have some experience with different web frameworks (Django, web.py, Pyramid and CherryPy), and I'm wondering in which one will it be easier and hopefully cleaner to implement a route dispatcher to a different "view/handler" based on the "Accept" header and the HTTP method e.g.:

Accept: application/json
POST /post/

is handled different than:

Accept: text/html
POST /post/

So the request gets routed to the particular view of the corresponding handler of the MIME "application/json" and the HTTP method "POST".

I do know how to implement something like that in CherryPy, but I lose the use of the CherryPy tools for the internal redirection of the request because I'm calling the specific method directly instead of automagically from the dispatcher. Another option is to implement a full new dispatcher from scratch, but that's the last option.

I'm aware of the alternative to use extensions in the url like /post.json or /post/.json, but I'm looking to keep the same url?

解决方案

If all you are looking for is one framework that can do this easily, then use pyramid.

Pyramid view definitions are made with predicates, not just routes, and a view only matches if all predicates match. One such predicate is the accept predicate, which does exactly what you want; make view switching depending on the Accept header easy and simple:

from pyramid.view import view_config

@view_config(route_name='some_api_name', request_method='POST', accept='application/json')
def handle_someapi_json(request):
    # return JSON

@view_config(route_name='some_api_name', request_method='POST', accept='text/html')
def handle_someapi_html(request):
    # return HTML

这篇关于基于Python Web框架中的Accept标头的路由请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆