在基于类的 View 中,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")
最佳答案
网址不映射到get方法,它映射到 View 。由请求方法来引导 django 以正确的方式进行。
如果您谈论的是实际代码,则为 dispatch
View 上的方法。
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)
关于python - Django 如何将 url 映射到基于类的 View 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40925524/