cyr*_*joe 3 python django cherrypy flask pyramid
我对不同的Web框架(Django,web.py,Pyramid和CherryPy)有一些经验,我想知道哪一个更容易,希望更清洁,将路由调度程序实现到基于的不同"视图/处理程序" "Accept"标头和HTTP方法,例如:
Accept: application/json
POST /post/
Run Code Online (Sandbox Code Playgroud)
处理不同于:
Accept: text/html
POST /post/
Run Code Online (Sandbox Code Playgroud)
因此,请求被路由到MIME"application/json"和HTTP方法"POST"的相应处理程序的特定视图.
我确实知道如何在CherryPy中实现类似的东西,但我失去了使用CherryPy工具进行请求的内部重定向,因为我直接调用特定方法而不是调度程序自动调用.另一个选择是从头开始实现一个全新的调度程序,但这是最后一个选项.
我知道在url中使用扩展名的替代方法,/post.json或者/post/.json,但我希望保留相同的网址?
Mar*_*ers 12
如果您正在寻找的是一个可以轻松完成此任务的框架,那么请使用pyramid.
金字塔视图定义是使用谓词而不仅仅是路由进行的,并且视图仅在所有谓词匹配时才匹配.一个这样的谓词是accept谓词,它完全符合你的要求; 根据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
Run Code Online (Sandbox Code Playgroud)
我需要在Django中执行此操作,因此我编写了一块中间件以使其成为可能:http : //baltaks.com/2013/01/route-requests-based-on-the-http-accept-header-in -django
这是代码:
# A simple middleware component that lets you use a single Django
# instance to serve multiple versions of your app, chosen by the client
# using the HTTP Accept header.
# In your settings.py, map a value you're looking for in the Accept header
# to a urls.py file.
# HTTP_HEADER_ROUTING_MIDDLEWARE_URLCONF_MAP = {
# u'application/vnd.api-name.v1': 'app.urls_v1'
# }
from django.conf import settings
class HTTPHeaderRoutingMiddleware:
def process_request(self, request):
try:
for content_type in settings.HTTP_HEADER_ROUTING_MIDDLEWARE_URLCONF_MAP:
if (request.META['HTTP_ACCEPT'].find(content_type) != -1):
request.urlconf = settings.HTTP_HEADER_ROUTING_MIDDLEWARE_URLCONF_MAP[content_type]
except KeyError:
pass # use default urlconf (settings.ROOT_URLCONF)
def process_response(self, request, response):
return response
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1983 次 |
| 最近记录: |