RESTful 的 Django

最近爲了升級曾經用Django做的網站,決定升級修改下架構,而且在當今Rest風格API的架構正在一步步的***到各個公司的API設計中,那Django這個框架呢?當然也會例外。

現在現在以相對比較好用的rest framework做個demo:

環境:ubuntu, mysql, python, django, django-rest-framework


在開始創建項目之前,我們用virtualenv先搭建一個新的虛擬環境,這樣會確保我們的包配置很好的從正在工作的其他項目中隔離,在這裏裏面你可以做任何你想做的,而且可以共享系統中已安裝的組件,只需要安裝本項目特有的組件,是一個很好用的"沙盒":

virtualenv env
source env/bin/activate #激活當前虛擬環境

在任何時候想要退出虛擬環境,只需要輸入:

deactivate


安裝django 

(env)bing@ubuntu:/usr/local$pip install django
Downloading/unpackingdjango
  Downloading Django-1.9.8-py2.py3-none-any.whl(6.6MB): 6.6MB downloaded
Installing collectedpackages: django
Successfullyinstalled django
Cleaning up...

安裝djangorestframework

(env)bing@ubuntu:/usr/local$pip install djangorestframework
Downloading/unpackingdjangorestframework
 
 Downloadingdjangorestframework-3.4.1-py2.py3-none-any.whl (705kB):   
0% 4.1k  Downloading 
djangorestframework-3.4.1-py2.py3-none-any.whl(705kB):   1%  
8.2k Downloading djangorestframework-3.4.1-py2.py3-none-any.whl 
(705kB):   1% 12kB
………..
loaded
Installing collectedpackages: djangorestframework
Successfullyinstalled djangorestframework
Cleaning up...
(env)bing@ubuntu:/usr/local$

安裝markdown - 讓API可瀏覽

(env)bing@ubuntu:/usr/local$pip install django

安裝django-filter - 過濾器

(env)bing@ubuntu:/usr/local$pip install django-filter


安裝MySqL:

(env)bing@ubuntu:/usr/local$sudo apt-get install mysql-server
Reading packagelists... Done
Building dependencytree      
Reading stateinformation... Done
The following extrapackages will be installed:
  libdbd-mysql-perl libdbi-perllibhtml-template-perl libmysqlclient18
  libterm-readkey-perl mysql-client-5.5mysql-client-core-5.5 mysql-common
  mysql-server-5.5 mysql-server-core-5.5
Suggested packages:
  libmldbm-perl libnet-daemon-perllibplrpc-perl libsql-statement-perl
  libipc-sharedcache-perl tinyca mailx
The following NEWpackages will be installed:
  libdbd-mysql-perl libdbi-perllibhtml-template-perl libmysqlclient18
  libterm-readkey-perl mysql-client-5.5mysql-client-core-5.5 mysql-common
  mysql-server mysql-server-5.5mysql-server-core-5.5
0 upgraded, 11 newlyinstalled, 0 to remove and 24 not upgraded.
Need to get 99.3kB/9,594 kB of archives.
After thisoperation, 97.1 MB of additional disk space will be used.

安裝成功後驗證

(env)bing@ubuntu:/usr/local$mysql -uroot -p
Enter password:
Welcome to the MySQLmonitor.  Commands end with ; or \g.
Your MySQLconnection id is 44
Server version:5.5.50-0ubuntu0.14.04.1 (Ubuntu)
 
Copyright (c) 2000,2016, Oracle and/or its affiliates. All rights reserved.
 
Oracle is aregistered trademark of Oracle Corporation and/or its
affiliates. Othernames may be trademarks of their respective
owners.
 
Type 'help;' or '\h'for help. Type '\c' to clear the current input statement.
 
mysql>


現在開始創建項目

django-admin.py startproject resttest

創建Web API.

cd resttest
python manage.py startapp testapi
cd ..

第一次同步數據庫

(env)bing@ubuntu:/usr/local/resttest$python manage.py migrate
Operations toperform:
  Apply all migrations: admin, contenttypes,auth, sessions
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applyingadmin.0002_logentry_remove_auto_add... OK
  Applyingcontenttypes.0002_remove_content_type_name... OK
  Applyingauth.0002_alter_permission_name_max_length... OK
  Applyingauth.0003_alter_user_email_max_length... OK
  Applyingauth.0004_alter_user_username_opts... OK
  Applyingauth.0005_alter_user_last_login_null... OK
  Applyingauth.0006_require_contenttypes_0002... OK
  Applyingauth.0007_alter_validators_add_error_messages... OK
  Applying sessions.0001_initial... OK
(env)bing@ubuntu:/usr/local/resttest$

爲我們的項目初始化一個管理員:

(env)bing@ubuntu:/usr/local/resttest$python manage.py createsuperuser
Username (leaveblank to use 'lybing'): 
Email address:[email protected]
Password:
Password (again):
Superuser createdsuccessfully.
(env)bing@ubuntu:/usr/local/resttest$


Serializers - 數據的展示模塊: resttest/testapi/serializers.py

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')

備註:這裏我們使用hyperlinked關聯,同樣你可以用主鍵或其他各種其他關係,但是hyperlinking是一個很好的RESTful設計


Views : resttest/testapi/views.py

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

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer

class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

與其寫多個view倒不如將一些有相同行爲的view分組叫ViewSets,如果有需有需要,我們可以很容易的拆成單獨的view,但是使用viewsets保持view邏輯便於組織也非常簡明.


配置API Url:resttest/urls.py

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

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# 用自動url路由來連接我們的API
# 另外,包含我們登錄用的可瀏覽的API的url
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]


設置:resttest/settings.py

INSTALLED_APPS = (
    ...
    'rest_framework',
)
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions.IsAdminUser',),
    'PAGE_SIZE': 10
}


啓動服務端測試

python manage.py runserver


未登錄的頁面

wKioL1eckD_jiG1ZAABwczW8mHQ004.png

點擊右上角的Log in登錄,用戶名和密碼在是上面初始化的管理員

wKiom1eckLfDEfSoAACde_R0n-Q980.png

如要添加新的用戶則可以在下面輸入數據,直接點擊Post即可


wKiom1eckO3zGtM9AABfcDE4bj0265.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章