2018-7-11 Django REST API小试牛刀

2021-03-29 17:25

阅读:773

标签:serialize   session   desc   api   pattern   sans   model   null   添加   

 

 

一、安装REST Framework

1、事先部署好django环境,此处不再赘述。

[root@k8s-minion ~]# pip install djangorestframework
[root@k8s-minion ~]# 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

[root@k8s-minion ~]# 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
[root@k8s-minion ~]# 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

[root@k8s-minion ~]# 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

[root@k8s-minion ~]# 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
[root@k8s-minion ~]# python manage.py runserver 0:8000

 技术分享图片

 

技术分享图片

 


2018-7-11 Django REST API小试牛刀

标签:serialize   session   desc   api   pattern   sans   model   null   添加   

原文地址:https://www.cnblogs.com/yue-hong/p/9295810.html


评论


亲,登录后才可以留言!