zoukankan      html  css  js  c++  java
  • flask-limiter限制单个IP访问的频率和次数

      Flask-Limiter provides rate limiting features to flask routes. It has support for a configurable backend for storage with current implementations for in-memory, redis and memcache. Flask-Limiter对flask的路由功能提供访问速率限制的功能。访问的信息可以存储到应用本身的内存里,或者存储到redis、memcache里

      

    举例demo:

    from flask import Flask
    from flask_limiter import Limiter
    from flask_limiter.util import get_remote_address
    
    app = Flask(__name__)
    limiter = Limiter(
        app,
        key_func=get_remote_address,   //根据访问者的IP记录访问次数
        default_limits=["200 per day", "50 per hour"]  //默认限制,一天最多访问200次,一小时最多访问50次
    )
    @app.route("/slow")
    @limiter.limit("1 per day")  //自定义访问速率
    def slow():
        return "24"
    
    @app.route("/fast")        //默认访问速率
    def fast():
        return "42"
    
    @app.route("/ping")
    @limiter.exempt      //无访问速率限制
    def ping():
        return "PONG"

    效果:

    $ curl localhost:5000/fast
    42
    $ curl localhost:5000/fast
    42
    $ curl localhost:5000/fast
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <title>429 Too Many Requests</title>
    <h1>Too Many Requests</h1>
    <p>2 per 1 minute</p>
    $ curl localhost:5000/slow
    24
    $ curl localhost:5000/slow
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
    <title>429 Too Many Requests</title>
    <h1>Too Many Requests</h1>
    <p>1 per 1 day</p>
    $ curl localhost:5000/ping
    PONG
    $ curl localhost:5000/ping
    PONG
    $ curl localhost:5000/ping
    PONG
    $ curl localhost:5000/ping
    PONG

    注释:

    The built in flask static files routes are also exempt from rate limits.

    即静态文件的访问无速率限制

    文档说明:http://flask-limiter.readthedocs.io/en/stable/

    github地址:https://github.com/alisaifee/flask-limiter

    参考:

    1、https://www.helplib.com/GitHub/article_107460

    2、https://www.jianshu.com/p/dd29529b06d9

    3、

    4、

  • 相关阅读:
    Java知识体系之基础知识
    002-JavaNIO
    001-四种常见的IO模型
    c/c++面试题(6)运算符重载详解
    c/c++面试题(5)(c++重要的概念详解)
    c/c++面试题(4)字符串翻转/打印任意进制格式/类型转换
    c/c++面试题(3)strcat/strcmp/strlen/strcpy的实现
    c/c++面试题(2)
    c/c++面试题(1)
    cocos2dx 3.0 之 lua 创建类 (二)
  • 原文地址:https://www.cnblogs.com/shengulong/p/9019336.html
Copyright © 2011-2022 走看看