快速开始
安装
pip install djangorestframework
创建django项目
django-admin startproject mydrf
创建APP
cd mydrf python3 manage.py startapp app01
配置文件修改(settings.py)
INSTALLED_APPS = [ ... 'rest_framework', 'app01', ] #对于匿名只读 REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] }
创建数据库表(app01下的models.py)
class IDC(models.Model): '''机房''' name = models.CharField(max_length=64, unique=True) def __str__(self): return self.name class Host(models.Model): hostname = models.CharField(max_length=64,unique=True) ip_addr = models.GenericIPAddressField() port = models.SmallIntegerField(default=22) idc = models.ForeignKey('IDC',blank=True,null=True) system_type_choices = ((0,'Linux'),(1,'Windows')) system_type = models.SmallIntegerField(choices=system_type_choices,default=0) memo = models.CharField(max_length=128,blank=True,null=True) enabled = models.BooleanField(default=1,verbose_name="启用本机") class Meta: unique_together = ('ip_addr','port') verbose_name = "主机表" def __str__(self): return "%s(%s)"%( self.hostname,self.ip_addr)
serialize配置(序列化,返回json格式,在app01下新建rest_serialize.py)
from app01 import models from rest_framework import serializers class IDCSerializer(serializers.ModelSerializer): class Meta: model = models.IDC fields = ('name',) #需要返回的字段 class HostSerializer(serializers.ModelSerializer): class Meta: model = models.Host fields = ('id','hostname','ip_addr','port','idc','system_type','memo','enabled')
视图配置(app01下新建rest_view.py)
from rest_framework import viewsets from app01 import models from app01 import rest_serializer class IDCViewSet(viewsets.ModelViewSet): queryset = models.IDC.objects.all() serializer_class = rest_serializer.IDCSerializer class HostViewSet(viewsets.ModelViewSet): queryset = models.Host.objects.all() serializer_class = rest_serializer.HostSerializer
url配置
from rest_framework import routers from app01 import rest_viewset from django.conf.urls import url,include router = routers.DefaultRouter() router.register(r'idc',rest_viewset.IDCViewSet) router.register(r'host',rest_viewset.HostViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
数据库里随便加点数据,启动django测试
访问http://127.0.0.1:8000/idc/
访问http://127.0.0.1:8000/host/