程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django REST Framework quickly builds RestFulAPI

編輯:Python

一、安裝django和djangorestframework

General will need package and writing text version of the batch installation,Convenient environment migration
eg:

django==1.11.15
djangorestframework==3.5.4

命令

pip install -r requirement.txt

二、創建項目

1. 創建項目fault
django-admin startproject fault
2. 創建子應用core
python manage.py startapp core
3. settingsRegistration applications and configurationrest_framework
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
'rest_framework'
]
REST_FRAMEWORK = {
# Abnormal request processing
'EXCEPTION_HANDLER': 'backend.core.apis.views.custom_exception_handler',
# 分頁格式
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
# 分頁大小
'PAGE_SIZE': 15,
# Interface default permissions
'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
'rest_framework.permissions.IsAuthenticated',
],
# 用戶驗證
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'backend.performance.apis.permissions.CsrfExemptSessionAuthentication',
),
# 默認渲染
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
}
4. For the first time synchronization database
python manage.py migrate
5. 創建一個管理員
python manage.py createsuperuser

三、直接用Django自帶的User,Group模塊

1. Serializers(fault/core/serializers.py下)

Define some serializedUser,Group數據表Serializers

from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'email')
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('id', 'name')
2. Views(fault/core/views.py下)

Can write the view code

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from core.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
允許用戶查看或編輯的API路徑.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
允許組查看或編輯的API路徑.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
from rest_framework.views import exception_handler
from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework import status
def custom_exception_handler(exc, context):
"""
自定義的異常處理
:param exc: The abnormal information of this request
:param context: 本次請求發送異常的執行上下文【本次請求的request對象,異常發送的時間,行號等....】
:return:
"""
response = exception_handler(exc, context)
# 在此處補充自定義的異常處理
if response is not None:
response.data['status_code'] = response.status_code
return response
if response is None:
"""Come to this is2中情況,Either program haven't made a mistake,Or make a mistake andDjango或者restframework不識別"""
view = context['view']
if isinstance(exc, DatabaseError):
# 數據庫異常
"""有5A way to senddebug info error critical warning"""
logger.error('[%s] %s' % (view, exc))
response = Response({'message': '服務器內部錯誤,請聯系客服工作人員!'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
return response
3. urls
from django.contrib import admin
from django.conf.urls import include, url
from rest_framework import routers
from core import views
router = routers.DefaultRouter()
router.register(r'users',views.UserViewSet)
router.register(r'groups',views.GroupViewSet)
# 使用自動URLRouting link ourAPI
# Support to surfAPI
urlpatterns = [
url('admin/', admin.site.urls),
url('^api/',include(router.urls)),
url(r'^api/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
4. 啟動服務器
python3 manage.py runserver 0.0.0.0:8080
5. 請求接口測試

http://127.0.0.1:8080/api/users/


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved