Diango教程-Django 视图

视图是我们放置应用程序业务逻辑的地方。视图是一个Python函数,用于执行一些业务逻辑并向用户返回响应。该响应可以是网页的 HTML 内容、重定向或 404 错误。
所有视图函数都是在Django 应用程序的views.py文件中创建的。
Django 查看简单示例
//视图.py
import datetime
# Create your views here.
from django.http import HttpResponse
def index(request):
now = datetime.datetime.now()
html = "<html><body><h3>Now time is %s.</h3></body></html>" % now
return HttpResponse(html) # rendering the template in HttpResponse
让我们逐步浏览一下代码。
首先,我们将导入 DateTime 库,该库提供了获取当前日期和时间的方法以及 HttpResponse 类。
接下来,我们定义一个视图函数索引,用于接收 HTTP 请求并返回响应。
当与urls.py中的 URL 映射时查看调用。例如
path('index/', views.index),
输出:
返回错误
Django 提供了各种内置错误类,它们是HttpResponse的子类,用于将错误消息显示为 HTTP 响应。下面列出了一些课程。
Class | Description |
---|---|
class HttpResponseNotModified | 它用于指示自用户上次请求(状态代码 304)以来页面尚未被修改。 |
class HttpResponseBadRequest | 它的行为与 HttpResponse 类似,但使用 400 状态代码。 |
class HttpResponseNotFound | 它的行为与 HttpResponse 类似,但使用 404 状态代码。 |
class HttpResponseNotAllowed | 它的行为与 HttpResponse 类似,但使用 410 状态代码。 |
HttpResponseServerError | 它的行为与 HttpResponse 类似,但使用 500 状态代码。 |
Django 视图示例
// 视图.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse, HttpResponseNotFound
def index(request):
a = 1
if a:
return HttpResponseNotFound('<h1>Page not found</h1>')
else:
return HttpResponse('<h1>Page was found</h1>') # rendering the template in HttpResponse
输出:
Django 视图 HTTP 装饰器
HTTP装饰器用于根据请求方法限制对视图的访问。
这些装饰器列在 django.views.decorators.http 中,如果不满足条件,则返回 django.http.HttpResponseNotAllowed 。
句法
require_http_methods(request_method_list)
Django Http 装饰器示例
//视图.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse, HttpResponseNotFound
from django.views.decorators.http import require_http_methods
@require_http_methods(["GET"])
def show(request):
return HttpResponse('<h1>This is Http GET request.</h1>')
仅当请求是 HTTP GET 请求时才会执行此方法。
//urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('show/', views.show),
]
输出: