django原生api介面 1.1 創建django項目 django-admin startproject drfdemo1 1.2 創建app django-admin startapp app 1.3 創建數據模型 app/models.py中編寫如下代碼: from django.db im ...
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": "刪除成功"
}
資料庫: