對於先後端分離你們可能在網上能夠找到不少的文章。可是,咱們今天分享的文章的英文咱們的老師對於先後端的分離問題的多年工做經驗的總結。今天,咱們把這些經驗總結知識點分享給你們,但願能夠幫助到你們。django
路由格式:json
/ API / <模塊> /後端
示例:api
/ API /資產/跨域
/ API / DNS /app
/ API /監視器/cors
返回格式:框架
0表示請求成功,非0表示請求異常前後端分離
{u'message': u'ERROR_PROXY_AUTH_FAILED', u'code': -97} {u'message': u'SUCCESS', u'code': 0}
增,刪,改,查及分頁post
採用django-rest-framework框架提供後端接口服務;
示例:
# -*- coding: UTF-8 -*- class StandardResultsSetPagination(pagination.PageNumberPagination): # 覆蓋 settings 中的默認分頁 page_size = 10 # page_size_query_param = 'page' # 限制最大分頁大小 max_page_size = 10
class BaseManageView(generics.ListAPIView): serializer_class = TbRecordsSerializer model = TbRecords queryset = TbRecords.objects.all() pagination_class = StandardResultsSetPagination parser_classes = (JSONParser,) def get_object(self, pk): try: return TbRecords.objects.get(pk=pk) except TbRecords.DoesNotExist: raise Http404 def get(self, request, *args, **kwargs): # 分頁 return super(DnsManageView, self).get(request, *args, **kwargs) def get_queryset(self): # 條件搜索 queryset = super(DnsManageView, self).get_queryset() queryset = self.get_queryset_search(queryset) return queryset def get_queryset_search(self, queryset): queryset = queryset.objects.filter(update_time=F('update_time') + 8) return queryset def post(self, request): # 添加 data = self._parseRequest(request.body) pass return apiSucess("SUCCESS", 200) def put(self, request): # 修改 data = self._parseRequest(request.body) pass return apiSucess("SUCCESS", 200) def delete(self, request, pk): # 刪除 obj = self.get_object(pk) obj.delete() return apiSucess("SUCCESS", 204) def options(self, request): # 非分頁 data = TbRecords.objects.values() return apiSucess(data, 200) def _parseRequest(self, querydict_obj): # 解析已提交的數據 params = QueryDict(querydict_obj).dict() if isinstance(params, dict): if len(params) == 1: data = json.loads(params.keys()[0]) else: data = params elif isinstance(params, list): pass else: pass return data
1,經過NGINX的方式
經過在NGINX代理添加標題的方式
server { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Headers X-Requested-With; add_header Access-Control-Allow-Methods GET,POST,OPTIONS; }
2,經過後端服務方式
修改project_name / settings.py文件。
(1)添加。
INSTALLED_APPS添加corsheaders
(2)開啓黑白名單,任選其一。
CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( '*', 'localhost:8000', '127.0.0.1:9000', )
針對主機的權限控制
示例:
# -*- coding: UTF-8 -*- import functools from rest_framework import status from rest_framework.response import Response # 容許的白名單IP地址 ALLECT_ADDR_POOL = ( '127.0.0.1', ) def AclHost(func): def wrapper(request, *args, **kwargs): username = request.request.user method = request.request.method if request.request.META.has_key('HTTP_X_FORWARDED_FOR'): remote_addr = request.request.META['HTTP_X_FORWARDED_FOR'] else: remote_addr = request.request.META['REMOTE_ADDR'] # 有多層代理 if remote_addr.count(',') >=1: remote_addr = remote_addr.split(',')[-1].strip() if remote_addr not in ALLECT_ADDR_POOL: data = {'result' : {'username' : username, 'method' : method, 'remote_addr' : remote_addr}, "errmsg" : 'FORBIDDEN'} return Response(data, status=status.HTTP_403_FORBIDDEN) return func(request, *args, **kwargs) return functools.wraps(func)(wrapper)
針對Token的權限控制
建立用戶自動生成Token,基於Token的路由的訪問。
示例:
(1)djuser / models.py
# -*- coding: UTF-8 -*- from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.contrib.auth.models import User # 針對新建立的用戶生成token @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance)
(2)djuser / views.py
from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class UserManager(APIView): # Token驗證 authentication_classes = (SessionAuthentication, TokenAuthentication) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content)