开发环境
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/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。