pip install djangorestframework
django-admin startproject mydrf
cd mydrf python3 manage.py startapp app01
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' ] }
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)
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')
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
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')) ]
訪問http://127.0.0.1:8000/idc/python
訪問http://127.0.0.1:8000/host/數據庫