再谈《Django 限制访问频率》

之前提到使用ratelimit来限制访问频率,我的目的是根据用户来限制访问频率,但是实际上通过下面的代码并没有达到效果,如果用多个浏览器进行同时刷新,会存在跳过限制的情况

@ratelimit(key='user', rate='1/8s', block=True, method=('POST'))

本来是不想重复造轮子的,但是由于这个轮子不大好用,于是只好重新造一个,基于redis可以使用下面的代码来实现(ttl为限制时长):

def set_method_limit(method_name, player_id, ttl):
    cash_name = 'RATELIMIT::METHOD=' + method_name + 'PLAYERID=' + str(player_id)
    cache.set(cash_name, method_name, ttl)
def check_is_limit(method_name, player_id):
    cash_name = 'RATELIMIT::METHOD=' + method_name + 'PLAYERID=' + str(player_id)
    if cash_name in cache:
        return True
    return False
def redis_ratelimit(method='ALL', block=False, ttl=5):
    def decorator(fn):
        @wraps(fn)
        def _wrapped(*args, **kw):
            # Work as a CBV method decorator.
            request = args[0]
            auth = request.META.get('HTTP_AUTHORIZATION', 'UNKNOWN')
            # 获取用户id 如果失败则用token
            try:
                auth = request.user.id
                print('PID= ' + str(auth))
            except:
                pass
            token = str(auth).split(' ')[-1]
            if check_is_limit(method, token) and block:
                content = {
                    'status': 403,
                    'message': '大侠喝口茶,小女子给你讲个故事如何?\r\n 从前有座山,山上有座庙……',
                }
                return JsonResponse(content)
                # raise Redis_Rate_Limit()
            set_method_limit(method, token, ttl)
            return fn(*args, **kw)

        return _wrapped

    return decorator

使用方法和retalimit一致:

@api_view(['POST', 'GET'])
@redis_ratelimit(method='api_test', block=True, ttl=10)
@csrf_exempt
def api_test(request):
    """
    测试接口
    http://192.168.1.195:8006/rest-api/battle/api-test/


    :return: 普通数据测试
    """
    return json_response_message(status=API_SUCCESS, message=timezone.now().date())

redis 安装:

pip3 install django-redis
Continue Reading

ubuntu 18.04 pip3 install mysqlclient

不知道是阿里云的问题还是ubuntu本身的问题,今天安装mysqlclient提示:

/usr/bin/ld: cannot find -lssl
/usr/bin/ld: cannot find -lcrypto
collect2: error: ld returned 1 exit status
error: command ‘x86_64-linux-gnu-gcc’ failed with exit status 1

网上搜了一下没有发现类似的错误信息,于是转换思路直接搜索: /usr/bin/ld: cannot find -lssl 在这篇文章看到了解决方案:

https://blog.51cto.com/eminzhang/1285705

Continue Reading

Picasa3 DB Path Changer

用了多年不用的Delphi 写了个路径修改工具:

下载链接: 链接:https://pan.baidu.com/s/1Gztriz7sfpFSDghTyrX-Hw
提取码:hwvg

原理说明:https://image.h4ck.org.cn/2019/12/配置修改picasa3本地数据库路径/

Google 的免费图片管理工具Picasa,数秒钟内就可找到并欣赏计算机上的图片。 Picasa 原为独立收费的图像管理、处理软件,其界面美观华丽, 功能实用丰富。后来被 Google 收购并改为免费软件, 成为了 Google 的一部分,它最突出的优点是搜索硬盘中的相片图片的速度很快,当你输入一个字后,准备输入第二个字时,它已经即时显示出搜索出的图片。不管照片有多少,空间有多大,几秒内就可以查找到所需要的图片。
Picasa 是一款可帮助您在计算机上立即找到、修改和共享所有图片的软件。每次打开 Picasa 时,它都会自动查找所有图片(甚至是那些您已经遗忘的图片),并将它们按日期顺序放在可见的相册中,同时以您易于识别的名称命名文件夹。您可以通过拖放操作来排列相册,还可以添加标签来创建新组。Picasa 保证您的图片从始至终都井井有条。
Continue Reading

韩国美女模特爬虫

对于美女的热爱无法自拔 😆 ,经常会去搜索一些美女图片,下载下来,然后找时间慢慢欣赏。主要用途是用作电脑桌面手机桌面,通常会百度或者bing去搜索下找到图片下载。相对来说能够直接用作桌面的图片并不多,多数是尺寸问题,并不是十分合适。但是即使不能直接用,可以用ps修改下图片尺寸,或者欣赏也是好的啊。 🙂 

以前曾经从一个网站mzitu.com 爬了一些图片,但是最近访问的时候却发现网站挂了~~

Continue Reading

Django 限制访问频率

最近做了一个系统由于部分接口需要进行耗时操作,因而不希望用户进行频繁访问,需要进行访问频率限制。如果要自己实现一个访问限制功能相对来说也不会太复杂,并且网上有各种代码可以参考。如果自己不想实现这个代码可以使用 Django Ratelimit

Django Ratelimit is a ratelimiting decorator for Django views.

https://travis-ci.org/jsocol/django-ratelimit.png?branch=master
Code: https://github.com/jsocol/django-ratelimit
License: Apache Software License
Issues: https://github.com/jsocol/django-ratelimit/issues
Documentation: http://django-ratelimit.readthedocs.org/

使用方法也相对来说比较简单:

@ratelimit(key='ip', rate='5/m')
def myview(request):
    # Will be true if the same IP makes more than 5 POST
    # requests/minute.
    was_limited = getattr(request, 'limited', False)
    return HttpResponse()

@ratelimit(key='ip', rate='5/m', block=True)
def myview(request):
    # If the same IP makes >5 reqs/min, will raise Ratelimited
    return HttpResponse()

@ratelimit(key='post:username', rate='5/m', method=['GET', 'POST'])
def login(request):
    # If the same username is used >5 times/min, this will be True.
    # The `username` value will come from GET or POST, determined by the
    # request method.
    was_limited = getattr(request, 'limited', False)
    return HttpResponse()

@ratelimit(key='post:username', rate='5/m')
@ratelimit(key='post:tenant', rate='5/m')
def login(request):
    # Use multiple keys by stacking decorators.
    return HttpResponse()

@ratelimit(key='get:q', rate='5/m')
@ratelimit(key='post:q', rate='5/m')
def search(request):
    # These two decorators combine to form one rate limit: the same search
    # query can only be tried 5 times a minute, regardless of the request
    # method (GET or POST)
    return HttpResponse()

Continue Reading