關(guān)于Restful API,可閱讀理解RESTful架構(gòu)和RESTful API 設(shè)計(jì)指南跟伏。
在Django中要實(shí)現(xiàn)Restful API比較簡(jiǎn)單贪绘,有現(xiàn)成的的框架可用绍哎。
- 安裝
pip install djangorestframework
pip install django-filter # Filtering support
- 在setting中加載
# Application definition
INSTALLED_APPS = [
'rest_framework',
]
- 在urls中配置api訪問地址
url(r'^api/devops/', include('devops.urls.api_urls', namespace='api-devops')),
- devops.urls.api_urls的文件中具體配置
# coding:utf-8
from django.conf.urls import url
from .. import api
from rest_framework_bulk.routes import BulkRouter
app_name = 'devops'
router = BulkRouter()
router.register(r'v1/pci', api.PCIViewSet, 'pci')
router.register(r'v1/pci-build', api.PCIBuildViewSet, 'pci-build')
router.register(r'v1/pci-builds', api.PCIBuildsViewSet, 'pci-builds')
router.register(r'v1/pci-release', api.PCIReleaseViewSet, 'pci-release')
router.register(r'v1/online-version', api.OnlineVersionViewSet, 'online-version')
urlpatterns = []
urlpatterns += router.urls
定義models
參考之前文章Django-models創(chuàng)建api.py
from common.mixins import IDInFilterMixin
from rest_framework_bulk import BulkModelViewSet
from . import serializers
from devops.models import PCI,PCI_RELEASE,ONLINE_VERSION,PCI_BUILDS
class PCIViewSet(IDInFilterMixin,BulkModelViewSet):
queryset = PCI.objects.all()
serializer_class = serializers.PCISerializer
class PCIBuildViewSet(IDInFilterMixin,BulkModelViewSet):
queryset = PCI_BUILDS.objects.all()
serializer_class = serializers.PCIBuildSerializer
def get_queryset(self):
queryset = super(PCIBuildViewSet, self).get_queryset()
pci_id = self.request.query_params.get('pci_id', '')
if pci_id:
self.queryset = queryset.filter(pci__id=pci_id)
return self.queryset
- 創(chuàng)建Serializer
# -*- coding: utf-8 -*-
from rest_framework import serializers
from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin
from devops.models import PCI,PCI_RELEASE,ONLINE_VERSION,PCI_BUILDS
from projects.models import Project
class PCISerializer(BulkSerializerMixin, serializers.ModelSerializer):
pro = serializers.SlugRelatedField(slug_field='name',required=False,allow_null=True,queryset=Project.objects.all())
class Meta:
model = PCI
list_serializer_class = BulkListSerializer
fields = ["pro", "job_name", "pro_scm","last_build_number", "last_build_result", "last_build_url", "last_update_time","id"]