Ruby on rails Django等效铁路响应
在Rails中,我可以使用respond_来定义控制器如何根据请求格式进行响应 在routes.rb中Ruby on rails Django等效铁路响应,ruby-on-rails,json,django,equivalent,respond-to,Ruby On Rails,Json,Django,Equivalent,Respond To,在Rails中,我可以使用respond_来定义控制器如何根据请求格式进行响应 在routes.rb中 map.connect '/profile/:action.:format', :controller => "profile_controller" 在profile_controller.rb中 def profile @profile = ... respond_to do |format| format.html { }
map.connect '/profile/:action.:format', :controller => "profile_controller"
在profile_controller.rb中
def profile
@profile = ...
respond_to do |format|
format.html { }
format.json { }
end
end
目前,在Django中,我必须使用两个URL和两个操作:一个返回html,一个返回json
url.py:
urlpatterns = [
url(r'^profile_html', views.profile_html),
url(r'^profile_json', views.profile_json),
]
view.py
def profile_html (request):
#some logic calculations
return render(request, 'profile.html', {'data': profile})
def profile_json(request):
#some logic calculations
serializer = ProfileSerializer(profile)
return Response(serializer.data)
通过这种方法,逻辑的代码变得重复。当然,我可以定义一个方法来进行逻辑计算,但是代码非常冗长
在Django有没有其他东西,我可以把它们结合起来 是的,例如,您可以定义一个参数,用于指定格式:
def profile(request, format='html'):
#some logic calculations
if format == 'html':
return render(request, 'profile.html', {'data': profile})
elif format == 'json':
serializer = ProfileSerializer(profile)
return Response(serializer.data)
因此,现在Django将把格式解析为regex\w+
(您可能需要对此进行一些更改),并将其作为格式参数传递给概要文件(…)
视图调用
请注意,现在用户可以键入任何内容,例如localhost:8000/profile_blabla
。因此,您可以进一步限制正则表达式
urlpatterns = [
url(r'^profile_(?P<format>(json|html))', views.profile),
]
urlpatterns=[
url(r'^profile_u(?P(json | html)),views.profile),
]
所以现在只有
json
和html
是有效的格式。与定义action
参数的方法相同(就像您的第一个代码片段所建议的那样)。从您对序列化程序类的使用来看,您显然是在使用Django Rest框架。因此,您应该让该库通过使用渲染器来完成这里的工作-请参阅
在您的情况下,您希望在JSONRenderer和TemplateHTMLRenderer之间切换,DRF将根据URL中的Accept头或文件扩展名自动检测要使用哪一个
urlpatterns = [
url(r'^profile_(?P<format>(json|html))', views.profile),
]