关于Restful API,可阅读理解RESTful架构和RESTful API 设计指南。
在Django中要实现Restful API比较简单,有现成的的框架可用。
- 安装
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创建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
- 创建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"]