前后端分离-django主机管理开发二

1、django项目根路由

from django.urls import path, include


urlpatterns = [
path('api/', include('apps.api.urls')),
]
django-devops.urls

2、安装rest_framework、corsheaders这两个包和创建api这个项目并导入

INSTALLED_APPS = [
    'rest_framework',
    'apps.api.apps.ApiConfig',
    'corsheaders',
]
django-settings.py

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
django-api.urls

4、创建serializers文件并从数据库取出数据后序列化

from rest_framework import serializers
from apps.api import models


class HostSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Host
        fields = '__all__'
django-api.serializers.py

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
django-api.models.py

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
django-api.view.py

 

posted @ 2020-06-21 10:06  python坚持者  阅读(252)  评论(0编辑  收藏  举报