简体   繁体   English

Django相当于rails respond_to

[英]Django equivalent of rail respond_to

In Rails, I can use respond_to to define how the controller respond to according to the request format. 在Rails中,我可以使用respond_to来定义控制器如何根据请求格式进行响应。

in routes.rb 在routes.rb中

 map.connect '/profile/:action.:format', :controller => "profile_controller" 

in profile_controller.rb 在profile_controller.rb中

def profile
      @profile = ...
      respond_to do |format|
        format.html {  }
        format.json {  }

      end
end

Currently, in Django, I have to use two urls and two actions: one to return html and one to return json. 目前,在Django中,我必须使用两个URL和两个动作:一个返回html,一个返回json。

url.py: url.py:

urlpatterns = [
    url(r'^profile_html', views.profile_html),
    url(r'^profile_json', views.profile_json),
]

view.py 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)

With this approach, the code for the logic becomes duplicate. 使用这种方法,逻辑代码变得重复。 Of course I can define a method to do the logic calculations but the code is till verbose. 当然,我可以定义一个方法来进行逻辑计算,但代码直到详细。

Is there anyway in Django, I can combine them together? 在Django还有,我可以将它们组合在一起吗?

Yes, you can for example define a parameter, that specifies the format: 是的,您可以定义一个参数,指定格式:

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)

Now we can define the urls.py with a specific format parameter: 现在我们可以使用特定的格式参数定义urls.py

urlpatterns = [
    url(r'^profile_(?P<format>\w+)', views.profile),
]

So now Django will parse the format as a regex \\w+ (you might have to change that a bit), and this will be passed as the format parameter to the profile(..) view call. 所以现在Django会将格式解析为正则表达式\\w+ (您可能需要更改一下),这将作为format参数传递给profile(..)视图调用。

Note that now, a user can type anything, for example localhost:8000/profile_blabla . 请注意,现在,用户可以键入任何内容,例如localhost:8000/profile_blabla You can thus further restrict the regex. 因此,您可以进一步限制正则表达式。

urlpatterns = [
    url(r'^profile_(?P<format>(json|html))', views.profile),
]

So now only json and html are valid formats. 所以现在只有jsonhtml是有效的格式。 The same way you can define an action parameter (like your first code fragment seems to suggest). 您可以像定义action参数一样(就像您的第一个代码片段似乎建议的那样)。

From your use of serializer classes, you are obviously using Django Rest Framework. 从使用序列化程序类开始,您显然正在使用Django Rest Framework。 Therefore you should let that library do the work here, via its use of renderers - see the documentation . 因此,您应该让该库通过使用渲染器来完成这项工作 - 请参阅文档

In your case you want to switch between JSONRenderer and TemplateHTMLRenderer, and DRF will automatically detect which one to use based on either the Accept header or the file extension in the URL. 在您的情况下,您希望在JSONRenderer和TemplateHTMLRenderer之间切换,DRF将根据Accept标头或URL中的文件扩展名自动检测要使用的是哪一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM