drf初體驗

快速開始

安裝

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/python

 

 訪問http://127.0.0.1:8000/host/數據庫

 

我的感受drf的應用場景在先後端分離時,經過json格式交互數據,不用涉及模板渲染等

相關文章
相關標籤/搜索