django-admin startproject drfdemo1
django-admin startapp app
app/models.py中编写如下代码:
创新互联是一家集网站建设,海州企业网站建设,海州品牌网站建设,网站定制,海州网站建设报价,网络营销,网络优化,海州网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
from django.db import models
class studentsInfo(models.Model):
name = models.CharField(max_length=12, verbose_name='姓名')
sex = models.CharField(max_length=1, verbose_name='性别')
age = models.IntegerField(verbose_name='年龄')
classroom = models.CharField(max_length=10, verbose_name='教室')
info = models.CharField(max_length=100, verbose_name='个人简介')
drfdemo1/settings.py:
# 后端只提供接口,不使用后台等其他功能,所以将无用功能注释掉可以减轻压力,提高性能
INSTALLED_APPS = [
# 'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
'app',
]
# 由于我们在使用post请求提交数据到后台的时候,django会有一个csrftoken验证,这样使用postman工具提交表单数据时就会失败,所以注释掉csrf中间件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# 由于是测试,所以不再使用mysql,使用sqlite3比较方便
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 设置为中文
LANGUAGE_CODE = 'zh-hans'
python manage.py makemigration
python manage.py migrate
app/views.py:
import json
from .models import *
from django.views import View
from django.http import JsonResponse
"""
post /students/ 添加一个学生
GET /students/ 获取所有学生信息
GET /students//获取一个学生信息
PUT /students// 更新一个学生信息
DELETE /students// 删除一个学生信息
一个路由对应一个视图类,把5个api接口分为两个视图类来写
"""
# 原生接口
class studentView(View):
def post(self, request):
# 1.接受客户端提交的数据
name = request.POST.get("name")
sex = request.POST.get("sex")
age = request.POST.get("age")
classroom = request.POST.get("classroom")
info = request.POST.get("info")
# 2.操作数据库,保存数据
instance = studentsInfo.objects.create(
name=name,
sex=sex,
age=age,
classroom=classroom,
info=info
)
# 3.返回结果
return JsonResponse({
"id": instance.id,
"name": instance.name,
"sex": instance.sex,
"age": instance.age,
"classroom": instance.classroom,
"info": instance.info
}, status=201, json_dumps_params={"ensure_ascii": False})
def get(self, request):
"""
获取多个学生信息
"""
students_list = studentsInfo.objects.values()
return JsonResponse(data=list(students_list), status=200, safe=False, json_dumps_params={"ensure_ascii": False})
class studentInfoView(View):
def get(self, request, pk):
"""
获取一条数据
"""
try:
instance = studentsInfo.objects.get(id=pk)
except studentsInfo.DoesNotExist:
return JsonResponse(data={"message": "学生不存在"}, status=404)
else:
return JsonResponse({
"id": instance.id,
"name": instance.name,
"sex": instance.sex,
"age": instance.age,
"classroom": instance.classroom,
"info": instance.info
}, status=201, json_dumps_params={"ensure_ascii": False})
def put(self, request, pk):
# 1.接受客户端提交的数据
data = json.loads(request.body)
name = data.get("name")
sex = data.get("sex")
age = data.get("age")
classroom = data.get("classroom")
info = data.get("info")
# 2.操作数据库,修改并保存数据
try:
instance = studentsInfo.objects.get(id=pk)
except studentsInfo.DoesNotExist:
return JsonResponse(data={"message": "学生不存在"}, status=404)
else:
instance.name = name
instance.sex = sex
instance.age = age
instance.classroom = classroom
instance.info = info
instance.save()
# 3.返回结果
return JsonResponse({
"id": instance.id,
"name": instance.name,
"sex": instance.sex,
"age": instance.age,
"classroom": instance.classroom,
"info": instance.info
}, status=201, json_dumps_params={"ensure_ascii": False})
def delete(self, request, pk):
try:
studentsInfo.objects.get(id=pk).delete()
except studentsInfo.DoesNotExist:
return JsonResponse(data={"message": "您要删除的数据不存在"}, status=404)
else:
return JsonResponse(data={"message": "删除成功"})
drfdemo1/urls.py:
from django.urls import path, include
urlpatterns = [
# path('admin/', admin.site.urls),
path('api/',include('app.urls')),
]
app/urls.py:
from django.urls import path,re_path
from .views import *
urlpatterns = [
path('students/', studentView.as_view()),
re_path(r'^students/(?P\d+)/$', studentInfoView.as_view())
]
python manage.py runserver 8000
返回数据:
{
"id": 13,
"name": "胡歌",
"sex": "男",
"age": "36",
"classroom": "888",
"info": "这个人很懒,什么都没有留下"
}
数据库:
返回数据
[
{
"id": 1,
"name": "小明",
"sex": "男",
"age": 22,
"classroom": "301",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 2,
"name": "小红",
"sex": "女",
"age": 18,
"classroom": "301",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 3,
"name": "张三",
"sex": "男",
"age": 25,
"classroom": "307",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 4,
"name": "李四",
"sex": "男",
"age": 24,
"classroom": "308",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 5,
"name": "闵麒良",
"sex": "男",
"age": 23,
"classroom": "310",
"info": "河工胡歌"
},
{
"id": 12,
"name": "孙明辉",
"sex": "男",
"age": 23,
"classroom": "333",
"info": "这个人很懒,什么都没有留下"
},
{
"id": 13,
"name": "胡歌",
"sex": "男",
"age": 36,
"classroom": "888",
"info": "这个人很懒,什么都没有留下"
}
]
返回数据
{
"id": 13,
"name": "胡歌",
"sex": "男",
"age": 36,
"classroom": "888",
"info": "这个人很懒,什么都没有留下"
}
返回数据
{
"id": 13,
"name": "胡歌",
"sex": "男",
"age": 18,
"classroom": 666,
"info": ""
}
数据库:
返回数据:
{
"message": "删除成功"
}
数据库: