標籤:serialize session desc api pattern sans model null 添加
一、安裝REST Framework
1、事先部署好django環境,此處不再贅述。
[[email protected] ~]# pip install djangorestframework
[[email protected] ~]# pip install markdown
2、建立一個名為snippets的app
(1)編輯settings.py,註冊snippets的APP和rest_framework
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘snippets‘,
‘rest_framework‘,
]
(2)更改Models.py
[[email protected] ~]# vim snippets/models.py
class Idc(models.Model):
ch_name = models.CharField("機房中文名稱", max_length=32, unique=True, null=True)
en_name = models.CharField("機房英文名稱", max_length=32, unique=True, null=True)
address = models.CharField("機房地址", max_length=100, null=True, blank=True)
ip_range = models.CharField("IP範圍", max_length=64, null=True)
bandwidth = models.CharField("接入頻寬", max_length=32, null=True)
add_person = models.CharField("添加人", max_length=50, null=True)
add_time = models.CharField("添加時間", max_length=50, null=True)
description = models.TextField("備忘", max_length=100, null=True, blank=True)
def __str__(self):
return self.en_name
class Meta:
verbose_name = ‘機房‘
verbose_name_plural = ‘機房‘
(3)在app目錄下建立serializers.py
[[email protected] ~]# vim snippets/serializers.py
from rest_framework import serializers
from models import Idc
class IdcSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Idc
fields = ‘__all__‘
# fields = (‘id‘,‘ch_name‘,‘en_name‘,‘address‘,‘bandwidth‘,‘description‘)
(4)更改views.py
[[email protected] ~]# vim snnippets/views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from models import *
from rest_framework import viewsets
from rest_framework.parsers import JSONParser
from .serializers import IdcSerializer
from django.http import JsonResponse
class IdcViewSet(viewsets.ModelViewSet):
queryset = Idc.objects.all().order_by(‘-add_time‘)
serializer_class = IdcSerializer
#permission_classes = (permissions.IsAuthenticated,)
@csrf_exempt
def idc_list(request):
if request.method == ‘GET‘:
snippets = Idc.objects.all()
serializer = IdcSerializer(snippets,many=True)
return JsonResponse(serializer.data,safe=False)
elif request.method == ‘POST‘:
data = JSONParser().parse(request)
serializer = IdcSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data,status=201)
return JsonResponse(serializer.errors,status=400)
(5)更改urls.py
[[email protected] ~]# vim snnippets/urls.py
from django.conf.urls import url,include
from django.contrib import admin
from rest_framework import routers
from snippets.views import IdcViewSet
from snippets import views
router = routers.DefaultRouter()
router.register(r‘idc‘, IdcViewSet)
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^‘,include(router.urls)),
url(r‘^idc/$‘,views.idc_list),
]
(6)運行而後瀏覽器訪問http://127.0.0.1:8000,接著訪問list的uri
[[email protected] ~]# python manage.py runserver 0:8000
2018-7-11 Django REST API小試牛刀