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

來源:互聯網
上載者:User

標籤: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小試牛刀

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.