前后端分离-django主机管理开发二
1、django项目根路由
from django.urls import path, include urlpatterns = [ path('api/', include('apps.api.urls')), ]
2、安装rest_framework、corsheaders这两个包和创建api这个项目并导入
INSTALLED_APPS = [ 'rest_framework', 'apps.api.apps.ApiConfig', 'corsheaders', ]
3、设置api项目下的路由
from django.urls import path from apps.api import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'hosts', views.HostView, basename='host') urlpatterns = router.urls
4、创建serializers文件并从数据库取出数据后序列化
from rest_framework import serializers from apps.api import models class HostSerializer(serializers.ModelSerializer): class Meta: model = models.Host fields = '__all__'
5、创建api项目的数据库
from django.db import models # Create your models here. class Host(models.Model): name = models.CharField(max_length=32) ip = models.GenericIPAddressField() port = models.PositiveIntegerField() c_time = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-c_time'] def __str__(self): return self.name
6、api的视图展示
from django.shortcuts import render from .models import Host from rest_framework.viewsets import ModelViewSet from .serializers import HostSerializer # Create your views here. class HostView(ModelViewSet): queryset = Host.objects.all() serializer_class = HostSerializer