django restframework 快速入門

django restframework 快速入門python

基本流程

  1. 創建 Models
  2. 依靠 Serialiers 將數據庫取出的數據 Parse 爲 API 的數據(可用於返回給客戶端,也可用於瀏覽器顯示)
  3. ViewSet 是一個 views 的集合,根據客戶端的請求(GET、POST等),返回 Serialiers 處理的數據 權限 Premissions 也在這一步作處理
  4. ViewSet 可在 Routers 進行註冊,註冊後會顯示在 Api Root 頁上
    在 urls 裏註冊 ViewSet 生成的 view,指定監聽的 url

1 安裝

pip install django
pip install djangorestframework

2 建立項目和啓動APP

django-admin.py startproject tutorial .  # Note the trailing '.' character
cd tutorial
django-admin.py startapp quickstart

使用pycharm的話這些命令都是不用手動去敲的,可是你要會這些知識數據庫

3 同步數據庫和建立django admin用戶

python manage.py migrate
python manage.py createsuperuser --email admin@example.com --username admin

4 序列器

from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

顯示超鏈接,繼承serializers.HyperlinkedModelSerializer,model那個表,fields是要序列那些字段django

5 views視圖

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

6 路由 urls

from django.conf.urls import url, include
from rest_framework import routers
from tutorial.quickstart import views

# 下面是自動配置urls
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))

]api

7 settings

INSTALLED_APPS = (
    ...
    'rest_framework',
)

啓動一下server吧

python manage.py runserver

結果

瀏覽器訪問 http://127.0.0.1:8000/users/瀏覽器

相關文章
相關標籤/搜索