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.

  • 相关阅读:
    RTImageAssets 自动生成 AppIcon 和 @2x @1x 比例图片
    Git 执行 「fork 出来的仓库」和「最新版本的原仓库」内容同步更新
    自定义支持多种格式可控范围的时间选择器控件
    UIWebView 操作
    iOS 模拟器键盘弹出以及中文输入
    验证 Xcode 是否来自正规渠道
    使用 AFNetworking 进行 XML 和 JSON 数据请求
    Reveal UI 分析工具分析手机 App
    多种方式实现文件下载功能
    网站HTTP升级HTTPS完全配置手册
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6517642.html
Copyright © 2011-2022 走看看