Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Django-Restful框架

Django-Restful框架

編輯:關於Android編程

1.准備工作

安裝django框架 安裝django-rsetful 框架
pip install djangorestframework

2.一個小demo

2.1創建django工程


    django admin startproject restful
    django admin startapp demo

2.2配置restful環境


    修改restful/settings.py
    在INSTALLED_APPS 添加 'rest_framework'

2.3編寫model層 /demo/model.py


    from django.db import models

    # Create your models here.
    class User(models.Model):
        username = models.CharField(max_length=20,blank=True)
        password = models.CharField(max_length=20,blank=True)
        def __str__(self):
            return self.username

2.4配置數據庫


    python manage.py makemigratons
    python manage.py migrate
    python manage.py createsuperuser

2.5配置後台管理 /demo/admin.py


    from django.contrib import admin
    # Register your models here.
    from demo.models import User

    admin.site.register(User)

此時登陸後台添加一些數據
\
(圖片不清楚可按住Ctrl+鼠標滾輪放大)

2.6編寫序列化模塊 /demo/serializer.py


    # author: HuYong
    # coding=utf-8
    from rest_framework import serializers

    from demo.models import User


    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ("id","username","password")

序列化聯通json與模型層

2.7編寫url

2.7.1根url restful/url.py


    from django.conf.urls import include, url
    from django.contrib import admin

    urlpatterns = [
        url(r'^admin/', include(admin.site.urls)),
        url(r'^api/demo/',include('demo.urls')),
    ]

2.7.2APP URL demo/urls.py


    # author: HuYong
    # coding=utf-8
    from django.conf.urls import url

    from demo import views

    urlpatterns = [
        url(r'^user/$',views.User_list),
        url(r'^user/(?P[0-9]+)/$',views.User_detial),
    ]

2.8編寫views層 demo/views.py


    import json

    from django.shortcuts import render

    # Create your views here.
    from rest_framework import status
    from rest_framework.decorators import api_view
    from rest_framework.response import Response

    from demo.models import User
    from demo.serializer import UserSerializer


    @api_view(['GET','POST'])
    def User_list(request):

        if request.method=="GET":
            users = User.objects.all()
            serializer = UserSerializer(users,many=True)
            return Response(serializer.data)

        elif request.method == 'POST':
            print request.body
            serializer = UserSerializer(data=json.loads(request.body))
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


    @api_view(['GET', 'PUT', 'DELETE']) #
    def User_detial(request,pk):
        try:
            user = User.objects.get(pk=pk)
        except User.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        if request.method == "GET":
            serializer = UserSerializer(user)
            return Response(serializer.data)

        elif request.method == "PUT":
            serializer = UserSerializer(user,data=json.loads(request.body))
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            else:
                return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

        elif request.method == "DELETE":
            user.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)

2.9測試

2.9.1獲取用戶列表

浏覽器訪問http://127.0.0.1:8000/api/demo/user/
\
這個浏覽器訪問的界面 通過postman來測試,返回的是json數據
\

2.9.2新增數據

通過postman來測試 簡單設置
\
\ 返回的數據:
\ 此時獲取用戶列表欄
\

2.9.3對單個用戶的操作

URL http://127.0.0.1:8000/api/demo/user/4 (id為4的用戶) 獲取用戶信息(GET)
\ 修改用戶信息(PUT)
\
\ 刪除用戶信息(DELETE)
\
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved