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
django-admin startproject fault
python manage.py startapp core
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',
)
}
python manage.py migrate
python manage.py createsuperuser
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')
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
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')),
]
python3 manage.py runserver 0.0.0.0:8080
http://127.0.0.1:8080/api/users/