Django如何将URL映射到基于类的视图函数?

时间:2016-12-02 05:41:01

标签: python django

在基于类的视图中,HTTP方法映射到类方法名称。下面,使用get方法和名为get方法的url定义了GET请求的处理程序。我的问题是url如何映射到get方法?

url(r'^hello-world/$', MyView.as_view(), name='hello_world'),

class MyView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse("Hello, World")

2 个答案:

答案 0 :(得分:3)

网址映射到get方法,它映射到视图。它取决于以正确的方式引导django的请求方法。

如果您正在谈论实际代码,请在视图上使用dispatch方法。

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

答案 1 :(得分:2)

为什么不看一下代码。

http://ccbv.co.uk/projects/Django/1.10/django.views.generic.base/View/

您将看到as_view()方法(在urls.py中调用)在第67行:

   return self.dispatch(request, *args, **kwargs)

dispatch()方法依次在第85行调用get(假设它是GET请求):

if request.method.lower() in self.http_method_names:
    handler = getattr(self, request.method.lower(),   self.http_method_not_allowed)