简体   繁体   English

什么是 Django 视图中的“请求”

[英]what is “request” in Django view

In the Django tutorial for the first app in Django we have在 Django 中第一个应用程序的 Django 教程中,我们有

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

And then the urls.py has然后 urls.py 有

from django.conf.urls import url

from polls import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

Now my question is what is the "request" parameter passed to the index function, also when the function index is called in urls.py it is not passed and variables it is just called as views.index in the line url(r'^$', views.index, name='index'),现在我的问题是传递给索引函数的“请求”参数是什么,当函数索引在 urls.py 中被调用时,它不会被传递,而变量它只是在url(r'^$', views.index, name='index'),

The request parameter is a HttpRequest object, which contains data about the request (see the docs for django 3.2 ). request 参数是一个HttpRequest对象,它包含有关请求的数据(请参阅django 3.2文档)。

In your urls file, you are not calling the view.index function, just listing a reference to it.在您的 urls 文件中,您没有调用view.index函数,只是列出了对它的引用。 Django then calls the function when a matching request comes in and passes the HttpRequest object as a parameter.然后,当匹配的请求传入时,Django 会调用该函数,并将HttpRequest对象作为参数传递。

This doesn't directly answer your question, but I suggest you watch this video:这并不能直接回答您的问题,但我建议您观看此视频:

A Scenic Drive through the Django Request-Response Cycle 通过 Django 请求-响应循环的风景驱动器

This is a PyCon talk Dan Langer gave this year and showed how request and response work under the hood.这是 Dan Langer 今年在 PyCon 上的演讲,展示了请求和响应是如何在幕后工作的。

From Django Docs .来自 Django文档 Request came from User that want to load page.请求来自想要加载页面的用户。

When a page is requested, Django creates an HttpRequest object that contains metadata about the request.当请求一个页面时,Django 创建一个 HttpRequest 对象,其中包含有关请求的元数据。 Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function.然后 Django 加载适当的视图,将 HttpRequest 作为第一个参数传递给视图函数。 Each view is responsible for returning an HttpResponse object.每个视图负责返回一个 HttpResponse 对象。

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

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