zoukankan      html  css  js  c++  java
  • [Django] Building the rest API

    Install the rest api framework:

    pip install djangorestfamework

    In settings.py:

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
        'scrurumboard',
    ]

    Create serializers to transform python to JSON:

    ## scrumboard/serializers.py
    
    from rest_framework import serializers
    
    from .models import List, Card
    
    ## Translate python to JSON
    class ListSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = List
            fields = '__all__'
    
    
    class CardSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Card
            fields = '__all__'

    It will according to 'Card' and 'List' Models to generate JSON.

    REST API Views:
    We also needs to use Views (controllers) to get data from database thought Model and transform to JSON and return to the client.

    ## scrumboard/api.py
    
    from rest_framework.generics import ListAPIView
    
    from .serializers import ListSerializer, CardSerializer
    from .models import List, Card
    
    class ListApi(ListAPIView):
        queryset = List.objects.all() ## get all the List data from databse
        serializer_class = ListSerializer ## conver to JSON
    
    
    class CardApi(ListAPIView):
        queryset = Card.objects.all()
        serializer_class = CardSerializer

    CONFIG URLS:

    ## scrumboard/urls.py
    
    from django.conf.urls import url
    
    from .api import ListApi, CardApi
    
    urlpatterns = [
        url(r'^lists$', ListApi.as_view()),
        url(r'^cards$', CardApi.as_view())
    ]

    This tells that anthing match sub-url like 'lists' or 'cards', we serve those request with ListApi view or CardApi view.

    Then in the default urls.py, we need to set up this app entry url:

    from django.conf.urls import url, include
    from django.contrib import admin
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^scrumboard/', include('scrumboard.urls')) ## match the urls.py file in scrumboard folder
    ]

    Because we added 'rest_framework' into INSTALLED_APPS array, we can visit: http://localhost:8000/scrumboard/cards

    TO see the REST API interface.

  • 相关阅读:
    [JSOI2004]平衡点
    [HNOI2009]梦幻布丁
    蒜头君救人
    蒜头君的排序
    蒜头君的坐骑
    [ZJOI2006]超级麻将
    环状最大两段子段和
    洛谷P2480 [SDOI2010]古代猪文(卢卡斯定理+中国剩余定理)
    线性基学习笔记
    洛谷P2473 [SCOI2008]奖励关(期望+状压)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6517642.html
Copyright © 2011-2022 走看看