1

day103 跨域请求 与频率访问限制.

目录

一、跨域请求

二、频率访问限制 

 

 

一 、同一个域下的ajax请求访问 

url文件

 

 

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

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

 

  

 

views

 

from django.shortcuts import render,HttpResponse

# Create your views here.
def  index(request):
    return render(request,"index.html")

def books(request):

    import json
    book_list =["西游记","水浒传","金瓶"]

    return HttpResponse(json.dumps(book_list,ensure_ascii=False))

 

 html index文件

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>

</head>
<body>

<button class="btn">click</button>

<p>书籍列表:</p>

<p class="book_list"></p>
<script>
    $(".btn").click(function () {
        $.ajax({
            url:"/books/",
            success:function (data) {
                $(".book_list").append(data)
            }


        })
        
    })

</script>

</body>
</html>

 

 

 

 结果为 

 

 

 

第二个域的views文件为:

# Create your views here.
def books(request):
    import json
    book_list =["西游记","水浒传","金瓶"]

    HttpResponse(json.dumps(book_list,ensure_ascii=False))
 

 

 

 

 二、跨域访问

 

将 ajax的访问路径做更改

 

 输出结果为:

 

 

 

 解决办法 在第二个项目的view文件里做如下更改

 

# Create your views here.
def books(request):
    import json
    book_list =["西游记","水浒传","金瓶"]

    # return HttpResponse(json.dumps(book_list,ensure_ascii=False))
    obj =HttpResponse(json.dumps(book_list,ensure_ascii=False))
    obj["Access-Control-Allow-Origin"] ="http://127.0.0.1:8000"
    return obj

 

 

 

 打印结果:

 

 

 

 预检

 

 

 

 

 

 

 

 

 

ajax请求代码

 

 

 

 

 

 

二、频率访问限制

 viewS文件 

 

from django.shortcuts import render,HttpResponse

# Create your views here.
from app01 import models
from rest_framework.views import APIView
from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet
from django.views import  View


# 序列化组件
class BookModelSerializers(ModelSerializer):
    class Meta:
        model =models.Book
        fields ="__all__"

class PublishModelSeralizers(ModelSerializer):
    class Meta:
        models=models.Publish
        fields ="__all__"

class AuthorModelSeralizers(ModelSerializer):
    class Meta:
        models =models.Author
        fields ="__all__"


# 频率访问组件
from rest_framework.throttling import BaseThrottle
class VisitThrottle(BaseThrottle):
    def allow_request(self,request,view):
        return  False


class BooksModeView(ModelViewSet):

    throttle_classes = [VisitThrottle]
    queryset = models.Book.objects.all()
    serializer_class = BookModelSerializers

  

 

 

 

 

案例 每隔10秒最多访问3次 

from django.shortcuts import render,HttpResponse

# Create your views here.
from app01 import models
from rest_framework.views import APIView
from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet


# 序列化组件
class BookModelSerializers(ModelSerializer):
    class Meta:
        model =models.Book
        fields ="__all__"

class PublishModelSeralizers(ModelSerializer):
    class Meta:
        models=models.Publish
        fields ="__all__"

class AuthorModelSeralizers(ModelSerializer):
    class Meta:
        models =models.Author
        fields ="__all__"


# 频率访问组件
from rest_framework.throttling import BaseThrottle

VISIT_RECORD={}
class VisitThrottle(BaseThrottle):

    def __init__(self):
        self.history =[]

    def allow_request(self,request,view):
        remote_addr =request.META.get("REMOTE_ADDR")
        print(remote_addr)
        print(self.get_ident(request))

        import time
        ctime =time.time()
        #IP 第一次访问
        if remote_addr not in VISIT_RECORD:
            VISIT_RECORD[remote_addr] = [ctime,]
            return True

        #查去当前访问IP的访问历史记录
        history =VISIT_RECORD.get(remote_addr)
        self.history =history
        print(self.history)

        if history and ctime - history[-1] > 10:
            history.pop()

        if len(history)<3:
            history.insert(0,ctime)  #索引第一位开始插入
            return True
        else:
            return  False

#显示剩余多少时间可以继续访问
    def wait(self):
        import time
        ctime = time.time()
        return 10 - (ctime - self.history[-1])


class BooksModeView(ModelViewSet):

    throttle_classes = [VisitThrottle,]
    queryset = models.Book.objects.all()
    serializer_class = BookModelSerializers

  

 

posted @ 2018-07-03 16:43  萌哥-爱学习  阅读(156)  评论(0编辑  收藏  举报