接收请求,响应请求。前后端不分离,返回的是页面;前后端分离,返回的是数据。
操作之前,请确保应用已经注册到项目中,可以先看我的博客:
https://blog.csdn.net/weixin_43431593/article/details/106872257
https://blog.csdn.net/weixin_43431593/article/details/106876828
现在操作views,即通过views与数据库、前端打交道。"接收到响应"的中间过程,就是操作数据库的过程,因此,views需要导入模型。
models.py:
class students(models.Model):
loginname = models.CharField(max_length=20)
nickname = models.CharField(max_length=10)
sex = models.BooleanField(default=True)
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import students
# Create your views here.
def studentsDetails(request):
return HttpResponse("欢迎来到django学习基地")
配置主路由(项目文件的urls.py):
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
# path('admin/', admin.site.urls),
path('studyapp/', include('studyapp.urls')),
]
配置子路由(应用程序的urls.py):
from django.urls import path
from studyapp.views import studentsDetails
urlpatterns = [
path('studentsDetails/', studentsDetails),
]
命令行启动服务:
python manage.py runserver
http://127.0.0.1:8000/studyapp/studentsDetails/
即可获得页面响应,我们这里使用了HttpResponse(“欢迎来到django学习基地”)直接响应页面,这种方式,叫前后端不分离。
修改views文件:
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import students
# Create your views here.
# def studentsDetails(request):
# return HttpResponse("欢迎来到django学习基地")
def studentsDetails(request):
return JsonResponse({"info":"欢迎来到django学习基地"}, safe=False, json_dumps_params={'ensure_ascii':False})
刷新页面后,展示如下:
现在我们增加一个接口,获取数据库students表所有数据:
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import json
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from django.views.decorators.http import require_http_methods
# Create your views here.
from .models import students
# def studentsDetails(request):
# return HttpResponse("欢迎来到django学习基地")
def studentsDetails(request):
return JsonResponse({"info":"欢迎来到django学习基地"}, safe=False, json_dumps_params={'ensure_ascii':False})
@require_http_methods(["GET"])
@csrf_exempt
def getstudents(request):
response = {}
try:
studentList = students.objects.filter()
response['list'] = json.loads(serializers.serialize("json", studentList))
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
return JsonResponse(response)
上面我们说到了前后端分离,并且写了一个接口,但不一定很规范,现在我们说django前后端分离的框架rest_framework。
安装配置先看看我的另一篇博客:
https://blog.csdn.net/weixin_43431593/article/details/107134506
应用目录添加serializers.py文件:
from .models import students
from rest_framework import serializers
class studentsSerializer(serializers.Serializer):
msg = serializers.CharField(max_length=20)
更改views:
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import json
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from django.views.decorators.http import require_http_methods
from .serializers import studentsSerializer
# Create your views here.
from .models import students
# def studentsDetails(request):
# return HttpResponse("欢迎来到django学习基地")
def studentsDetails(request):
return JsonResponse({"info":"欢迎来到django学习基地"}, safe=False, json_dumps_params={'ensure_ascii':False})
@require_http_methods(["GET"])
@csrf_exempt
def getstudents(request):
response = {}
try:
studentList = students.objects.filter()
response['list'] = json.loads(serializers.serialize("json", studentList))
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
serializers_obj = studentsSerializer(instance=response)
response = serializers_obj.data
return JsonResponse(response)
如上,首先导入模块“from .serializers import studentsSerializer”,接着引用:
“
serializers_obj = studentsSerializer(instance=response)
response = serializers_obj.data
”
因为有了序列器的作用,可以给前端返回想要的数据,这里只返回了“msg”。