厦门易尔通网站建设好吗,搜狗输入法下载安装,wordpress添加表情,广告营销专业在Django框架中#xff0c;视图类#xff08;Class-based views#xff0c;简称CBVs#xff09;提供了一个面向对象的方式来定义视图。这种方式可以让你通过创建类来组织视图逻辑#xff0c;而不是使用基于函数的视图#xff08;Function-based views#xff0c;简称FBV…在Django框架中视图类Class-based views简称CBVs提供了一个面向对象的方式来定义视图。这种方式可以让你通过创建类来组织视图逻辑而不是使用基于函数的视图Function-based views简称FBVs。CBVs带来了可重用性和模块化等优势尤其是在处理标准的CRUD操作时。 1创建应用 python manage.py startapp app2 2创建模版文件
!DOCTYPE html
html langen
headmeta charsetUTF-8titleTitle/title
/head
bodyform methodPOST
{% csrf_token %}p用户名/pinput typetext nameusernameinput typesubmit value提交
/form/body
/html 3配置模版路径 Test/Test/settings.py
import osTEMPLATES [{BACKEND: django.template.backends.django.DjangoTemplates,DIRS: [os.path.join(BASE_DIR, templates)],APP_DIRS: True,OPTIONS: {context_processors: [django.template.context_processors.debug,django.template.context_processors.request,django.contrib.auth.context_processors.auth,django.contrib.messages.context_processors.messages,],},},
] 4注册应用
Test/Test/settings.py 5添加视图函数
Test/app2/views.py
from django.shortcuts import render# Create your views here.
from django.http import HttpResponse
from django.views import Viewclass MyView(View):def get(self, request):# 处理GET请求的逻辑return HttpResponse(get, Hello, World!)def post(self, request):# 处理POST请求的逻辑print(request.method)print(request.POST.get(username))return HttpResponse(post, Hello, World!) 6添加路由地址
from django.urls import path
from app2.views import MyViewurlpatterns [path(MyView, MyView.as_view(), nameMyView),
] 7测试接口
Test/Test/settings.py
ps这个中间件是为了防止跨站请求伪造的平时用网页表单请求时post提交是没有问题的但是用api调用时就会被禁止为了能使用接口调用post请求需要注释掉。 import requestsres_get requests.get(urlhttp://127.0.0.1:8000/app2/MyView)
print(res_get.text)res_post requests.post(urlhttp://127.0.0.1:8000/app2/MyView , data{username:admin})
print(res_post.text) 分别成功请求getpost接口获取接口请求的admin值