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

标签 python django

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

相关文章:

python - 在生产环境中管理 django 项目的推荐方法是什么(在 apache 服务器中)

python - Django:在此服务器上找不到请求的 URL

python : Removing a List from List of List?

python - 如何下载本地镜像集以与 Keras 一起使用?

python - 如何按子列表的内容对子列表列表进行排序,其中子列表包含字符串和 bool 值?

django - 静态 CSS 和图像未在 Django 中加载

mysql - 比较django queryset中的两个字段

python - matplotlib 修剪刻度标签

Python:运行一个进程/线程,即使在主进程完成后仍继续运行

Django : SimpleListFilter queryset