曾幾什麼時候,Ajax已經統治了Web開發中的客戶端,而REST成爲web世界中最流行的架構風格(architecture style)。因此咱們的選擇變得很簡單:前端ajax訪問後端的RESTful API對資源進行操做
Django中有一些可選的REST framework,好比django-piston,django-tasypie。 可是我和google(呵呵,很差意思)推薦這個:Django REST framework前端
django-framework就是定義一個url,能夠利用這個url去數據庫中讀數據,或者寫數據web
安裝django-frameworkajax
pip install djangorestframework
pip install markdown
pip install django-filter
在Project中配置django-framework數據庫
打開project的settings.pydjango
INSTALLED_APPS = ( ... 'rest_framework', ) REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' #全部人都能訪問API,有讀寫權限 ] }
在Madking的url.py裏配置api的url後端
from assets import rest_urls as asset_urls urlpatterns = [ url(r'^api/', include(asset_urls)), #api的入口url ]
在asset的rest_urls.py裏註冊並關聯視圖api
from django.conf.urls import url, include from rest_framework import routers #導入rest_viewset,取個別名views from assets import rest_viewset as views #這個是rest_framework封裝django 的routers router = routers.DefaultRouter() #將views裏的UserViewSet和AssetViewSet註冊進來 #用戶請求http://127.0.0.1:8000/api/users/和http://127.0.0.1:8000/api/asset/就能獲取到數據 router.register(r'users', views.UserViewSet) router.register(r'asset', views.AssetViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), #這個是API的認證,必須得登陸才能請求API ]
在asset的rest_viewset.py裏定義去數據庫裏查詢數據markdown
from rest_framework import viewsets from assets import models from assets import rest_serializers class UserViewSet(viewsets.ModelViewSet): queryset = models.UserProfile.objects.all() #去查詢全部的數據 serializer_class = rest_serializers.UserSerializers #序列化(表現層,將數據按照必定格式返回給用戶) class AssetViewSet(viewsets.ModelViewSet): queryset = models.Asset.objects.all() serializer_class = rest_serializers.AssetSerializer
在asset裏的rest_serializers.py裏定義架構
#導入表結構 from assets import models #導入serializer方法 from rest_framework import serializers #獲取UserProfile表裏的信息 class UserSerializers(serializers.ModelSerializer): class Meta: #指定數據庫, model = models.UserProfile #指定返回給用戶的具體表中的哪些字段 fields = ('username','name') #獲取Asset表裏的信息 class AssetSerializer(serializers.ModelSerializer): class Meta: model = models.Asset depth=2 fields = ('name', 'sn','server','networkdevice')
測試測試
訪問http://127.0.0.1:8000/api/能看到API
訪問獲取用戶信息的API:http://127.0.0.1:8000/api/users/