乐趣区

关于django:使用-Django-搭建后台-API-服务一

开发环境

IDE:Pycharm 2021.1.1
零碎:macOS Mojave 10.14.6
Python 3.9.2

环境筹备

装置 Python

装置 Django

pip3 install Django
pip3 install djangorestframework

创立我的项目

django-admin startproject api

创立利用

python3 manage.py startapp pms

编辑 api/settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
    'pms.apps.PmsConfig'
]

应用 MySQL 数据库

装置 MySQL 驱动

pip3 install mysqlclient

批改配置

编辑文件 api/settings.py

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'pms',
        'HOST': 'localhost',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': '123'
    }
}

批改时区

编辑文件 api/settings.py

TIME_ZONE = 'Asia/Shanghai'

执行数据库迁徙

# 迁徙数据库
python3 manage.py migrate

# 创立超级管理员
python3 manage.py createsuperuser

创立模型

编辑 pms/models.py

from django.db import models


class Project(models.Model):
    name = models.CharField(max_length=100)
    start_date = models.DateField
    end_date = models.DateField
# 生成迁徙文件
python3 manage.py makemigrations pms

# 查看对应的迁徙 SQL
python3 manage.py sqlmigrate pms 0001

# 执行迁徙(模型同步到数据库)python3 manage.py migrate

创立序列化

新建 pms/serializers.py,编辑:

from rest_framework import serializers
from pms.models import Project


class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ['id', 'name', 'start_date', 'end_date']

编辑视图

编辑 pms/views.py

from rest_framework import viewsets
from pms.models import Project
from pms.serializers import ProjectSerializer


class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer

编辑路由

编辑 pms/url.py

from django.urls import include
from rest_framework.routers import DefaultRouter
from pms import views


router = DefaultRouter()
router.register(r'projects', views.ProjectViewSet)

urlpatterns = [path('', include(router.urls)),
]

运行服务

python3 manage.py runserver

测试

# 创立我的项目
POST http://127.0.0.1:8000/projects/
申请:{
    "name": "移居火星我的项目",
    "start_date": "2021-01-01",
    "end_date": "2021-01-31"
}
# 获取我的项目列表
GET http://127.0.0.1:8000/projects/
后果:[
    {
        "id": 1,
        "name": "移居火星我的项目",
        "start_date": "2022-01-01",
        "end_date": "2072-12-30"
    }
]
# 获取我的项目详情
GET http://127.0.0.1:8000/projects/1/
后果:{
    "id": 1,
    "name": "移居火星我的项目",
    "start_date": "2022-01-01",
    "end_date": "2072-12-30"
}
# 更新我的项目
PUT http://127.0.0.1:8000/projects/1/
申请:{
    "name": "移居火星我的项目 2",
    "start_date": "2022-01-01",
    "end_date": "2072-12-30"
}
# 删除我的项目
DELETE http://127.0.0.1:8000/projects/1/
退出移动版