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

Posted yue-hong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2018-7-11 Django REST API小试牛刀相关的知识,希望对你有一定的参考价值。

 

 

一、安装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小试牛刀的主要内容,如果未能解决你的问题,请参考以下文章

如何在 django-rest-framework 中为 API 使用 TokenAuthentication

Python / Django 中的 REST API

django-rest-swagger对API接口注释

DJANGO REST API--找不到模块错误

在 HTML 页面或模板中使用 Django-REST-Framework 从在 Django 中创建的 API 获取/显示 API 数据

django-rest-framework 和 swagger api 文档