Django REST framework 简易开发接口示例

1.安装django-rest-framework

pip install django-rest-framework
pip install django-cors-headers

2.创建项目app super_cmdb_api

python manage.py startapp super_cmdb_api

3.注册app:vim setting.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'databases_models',
    'super_cmdb',
    'rest_framework',
    'super_cmdb_api',
]

4.对整个项目的路由进行配置,让访问super_cmdb_api/ 路径时候转到super_cmdb_api应用中的urls.py文件配置进行处理:vim boampV2/urls.py

from django.contrib import admin
from django.urls import path
from django.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('super_cmdb/',include('super_cmdb.urls')),
    path('super_cmdb_api/',include('super_cmdb_api.urls')),
]

5.在super_cmdb_api文件夹中创建serializer.py文件,并写对应序列化器

from rest_framework import serializers

from databases_models.models import GameServerVersion
from databases_models.models import GameServer

class GameServerVersionSerializer(serializers.ModelSerializer):
    class Meta:
        model = GameServerVersion
        fields = '__all__'

class GameServerSerializer(serializers.ModelSerializer):
    class Meta:
        model = GameServer
        fields = '__all__'

6.在super_cmdb_api/views.py文件中写对应的视图集ViewSet来处理请求

from rest_framework import viewsets
from databases_models import models
from super_cmdb_api import serializer

class GameServerVersionViewSet(viewsets.ModelViewSet):
    queryset = models.GameServerVersion.objects.all()
    serializer_class = serializer.GameServerVersionSerializer

class GameServerViewSet(viewsets.ModelViewSet):
    queryset = models.GameServer.objects.all()
    serializer_class = serializer.GameServerSerializer

7.在super_cmdb_api/urls.py文件中写对应的路由映射

from django.urls import path,include
from rest_framework.routers import DefaultRouter
from super_cmdb_api import views

router = DefaultRouter()
router.register('version_list',views.GameServerVersionViewSet)
router.register('gameserver_list',views.GameServerViewSet)

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

8.生成数据结构和运行项目

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

9.页面测试,至此,已完成2个接口:

http://127.0.0.1:8001/super_cmdb_api/api/

 

 

 10.访问具体接口,页面可支持

GET /super_cmdb_api/api/version_list/
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

 

 

Allow: GET, POST, HEAD, OPTIONS
posted @ 2021-03-18 16:02  chenjianwen  阅读(52)  评论(0编辑  收藏  举报