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.

  • 相关阅读:
    Recommended Books for Algo Trading in 2020
    Market Making is simpler than you think!
    Top Crypto Market Makers of 2020
    Top Crypto Market Makers, Rated and Reviewed
    爬取伯乐在线文章(五)itemloader
    爬取伯乐在线文章(四)将爬取结果保存到MySQL
    爬取伯乐在线文章(三)爬取所有页面的文章
    爬取伯乐在线文章(二)通过xpath提取源文件中需要的内容
    爬取伯乐在线文章(一)
    爬虫去重策略
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6517642.html
Copyright © 2011-2022 走看看