django原生api接口
1.1 创建django项目
|
django-admin startproject drfdemo1 |
1.2 创建app
|
django-admin startapp app |
1.3 创建数据模型
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='个人简介') |
|
1.4 配置环境
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' |
1.5 数据迁移
|
python manage.py makemigration |
|
python manage.py migrate |
1.6 编写视图代码
app/views.py:
|
import json |
|
from .models import * |
|
from django.views import View |
|
from django.http import JsonResponse |
|
|
|
""" |
|
post /students/ 添加一个学生 |
|
GET /students/ 获取所有学生信息 |
|
|
|
GET /students/<pk>/获取一个学生信息 |
|
PUT /students/<pk>/ 更新一个学生信息 |
|
DELETE /students/<pk>/ 删除一个学生信息 |
|
|
|
一个路由对应一个视图类,把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": "删除成功"}) |
1.7 配置路由
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<pk>\d+)/$', studentInfoView.as_view()) |
|
] |
1.8 启动项目
|
python manage.py runserver 8000 |
1.9 测试api接口
1.9.1 添加一个学生
返回数据:
|
{ |
|
"id": 13, |
|
"name": "胡歌", |
|
"sex": "男", |
|
"age": "36", |
|
"classroom": "888", |
|
"info": "这个人很懒,什么都没有留下" |
|
} |
数据库:
1.9.2 获取所有学生信息
返回数据
|
[ |
|
{ |
|
"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": "这个人很懒,什么都没有留下" |
|
} |
|
] |
1.9.3 获取一条数据
返回数据
|
{ |
|
"id": 13, |
|
"name": "胡歌", |
|
"sex": "男", |
|
"age": 36, |
|
"classroom": "888", |
|
"info": "这个人很懒,什么都没有留下" |
|
} |
1.9.4 更新一条数据
返回数据
|
{ |
|
"id": 13, |
|
"name": "胡歌", |
|
"sex": "男", |
|
"age": 18, |
|
"classroom": 666, |
|
"info": "6666666666666666" |
|
} |
数据库:
1.9.5 删除一条数据
返回数据:
|
{ |
|
"message": "删除成功" |
|
} |
数据库: