Skip to main content
 首页 » 编程设计

python之Django 如何将 url 映射到基于类的 View 函数

2025年05月04日41langtianya

在基于类的 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") 

请您参考如下方法:

url 不映射到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)