Django drf:手撸自定义跨域

项目需求:

  1.用域名8000向8001发送请求,用django框架解决跨域问题

  2.用上自定义中间件配置,支持get、post、put、detele和非简单请求

  3.支持版本控制

  4.在setting中配置白名单列表,在表中域名可以访问,否则返回错误信息

 

# 首先8000端口url层设置路由

from django.conf.urls import url
from django.contrib import admin
from app import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.test),
]

#写test视图函数

from django.views.decorators.cache import cache_page
import time
from rest_framework.response import Response
# 单页面缓存10秒
# @cache_page(10)
def test(request):
    print('三儿来了!')
    ctime = time.time()

    return render(request,'index.html',locals())

# 模板层写index模板(这里用到ajax向后台提交数据,需要引入bootstop且在setting中配置)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="/static/jquery-3.3.1.js"></script>
    <title>Title</title>
</head>
<body>
不缓存
{{ ctime }}
<br>
存在的缓存
{#{% load cache %}#}
{#第一个是超时时间,缓存时间。第二个参数是Key值,别名。#}
{#{% cache 10 'test' %}#}
{#    {{ ctime }}#}
{#{% endcache %}#}
<button id="btn">点我发请求</button>

</body>
<script>
    $("#btn").click(function () {
        $.ajax({
            url: 'http://127.0.0.1:8001/v1/publishs/',
            {#type: 'get',#}
            type:'post',
            {#type:'put',#}
            contentType:'application/json',
            {#data:JSON.stringify({'name':'egon'}),#}
            success: function (data) {
                console.log(data)
            }
        })
    })

</script>
</html>

# ajax提交的路由请求http://127.0.0.1:8001/v1/publishs/

# 由于请求的是V1版本,我们在端口8001路由层中设置版本路由

 

from django.conf.urls import url
from django.contrib import admin
from app import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^(?P<version>[v1|v2]+)/publishs/', views.PublishView.as_view()),
   
]

# 写对应的的函数视图

from rest_framework.views import APIView
from rest_framework.versioning import URLPathVersioning
from rest_framework.response import Response

# 版本控制的局部使用
class PublishView(APIView):
    # versioning_class = QueryParameterVersioning # 基于url的get传参方法
    versioning_class = URLPathVersioning # 基于url的正则方式

    def get(self,request,*args,**kwargs):
        print(request.version)
        return Response({'status':100})

    def post(self,request,*args,**kwargs):
        print(request.method)
        return Response({'status': 100, 'msg': 'post'})

    def delete(self,request,*args,**kwargs):
        print(request.method)
        return Response({'status':100,'msg':'delete'})

    def put(self,request,*args,**kwargs):
        print(request.method)
        return Response({'status':100,'msg':'put'})

#这个时候写定义中间件

from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from rest_framework.response import Response
from django.http import JsonResponse

class CORSMiddle(MiddlewareMixin):
    def process_response(self,request,response):
        #
        # print(request.META['HTTP_ORIGIN'])
        host_list = settings.OPEN_HOST
        host = request.META['HTTP_ORIGIN']

        response['Access-Control-Allow-Origin'] = host
        if request.method == 'OPTIONS':
            response['Access-Control-Allow-Methods'] = 'PUT,DELETE,POST,GET'
            response['Access-Control-Allow-Headers'] = 'Content-Type'


        print(host,host_list)
        if host not in host_list:
            # rep = JsonResponse({'msg':'error  非法访问!'})
            rep = Response({'msg':'error  非法访问!'})
            rep['Access-Control-Allow-Origin'] = host
            return rep
        return response

# 自定义中间需要到setting中做配置,且把csrf注销

MIDDLEWARE = [
    'django.middleware.security.SecurityMid'
    ''
    'dleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'app.center.CORSMiddle',# 此为自定义中间件
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# 后面需要在setting中自定义白名单

OPEN_HOST = ['http://127.0.0.1:8002','http://127.0.0.1:8003']

 

转载于:https://www.cnblogs.com/wuzhengzheng/p/10458687.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值