📜  Django视图

📅  最后修改于: 2020-12-31 00:35:26             🧑  作者: Mango

Django视图

视图是放置我们的应用程序业务逻辑的地方。该视图是一个Python函数,用于执行一些业务逻辑并将响应返回给用户。此响应可以是网页的HTML内容,重定向或404错误。

所有视图函数都是在Django应用的views.py文件中创建的。

Django查看简单示例

//views.py

import datetime
# Create your views here.
from django.http import HttpResponse
def index(request):
    now = datetime.datetime.now()
    html = "

Now time is %s.

" % 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 It is used to designate that a page hasn’t been modified since the user’s last request (status code 304).
class HttpResponseBadRequest It acts just like HttpResponse but uses a 400 status code.
class HttpResponseNotFound It acts just like HttpResponse but uses a 404 status code.
class HttpResponseNotAllowed It acts just like HttpResponse but uses a 410 status code.
HttpResponseServerError It acts just like HttpResponse but uses a 500 status code.

Django查看范例

// views.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('

Page not found

') else: return HttpResponse('

Page was found

') # rendering the template in HttpResponse

输出:

Django View HTTP装饰器

HTTP装饰器用于根据请求方法限制对视图的访问。

这些装饰器在django.views.decorators.http中列出,如果不满足条件,则返回django.http.HttpResponseNotAllowed。

句法

require_http_methods(request_method_list)

Django Http装饰器示例

//views.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('

This is Http GET request.

')

仅当请求是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),
]

输出: