【问题标题】:Python Rate Limit class based view Flask基于 Python 速率限制类的视图 Flask
【发布时间】:2016-04-26 08:41:10
【问题描述】:

我正在关注这个例子:

http://flask-limiter.readthedocs.org/en/stable/#ratelimit-string

app = Flask(__name__)
limiter = Limiter(app, key_func=get_remote_address)

class MyView(flask.views.MethodView):
    decorators = [limiter.limit("10/second")]
    def get(self):
        return "get"

    def put(self):
        return "put"

我的问题是,例如,应用程序、限制器和类在同一个文件中定义,在我的情况下,应用程序和限制器定义在同一个文件中,但我的类位于单独的文件中。

如果我导入限制器或应用程序,我的 Flask 应用程序不会启动,因为循环 dependencies。如何解决这个问题,推荐的方法是什么?我想将限制器应用于特定端点。 我尝试from flask import current_app以初始化限制器,但此函数没有将其作为有效参数。有什么建议吗?

文件信息:

  • app.py
  • api_main.py

在 app.py 下我定义了我的资源:

api_app = Flask(__name__)  # Flask Application
api_app.config.from_pyfile("../../../conf/settings.py")  # Flask configuration

imbue_api = restful.Api(api_app)  # Define API
limiter = Limiter(api_app, key_func=get_remote_address, global_limits=["10 per second"])

imbue_api.add_resource(ApiBase, settings.BASE_API_URL)

在 api_main.py 我已经定义了我所有的类:

class ApiBase(Resource):
    @authenticator.requires_auth
    def get(self):
        """

        :return:
        """
        try:
            # =========================================================
            # GET API
            # =========================================================
            log.info(request.remote_addr + ' ' + request.__repr__())
            if request.headers['Content-Type'] == 'application/json':
                # =========================================================
                # Send API version information
                # =========================================================
                log.info('api() | GET | Version' + settings.api_version)
                response = json.dumps('version: ' + settings.api_version)
                resp = Response(response, status=200, mimetype='application/json')
                return resp

        except KeyError:
            response = json.dumps('Invalid type headers. Use application/json')
            resp = Response(response, status=415, mimetype='application/json')
            return resp

        except Exception, exception:
            log.exception(exception.__repr__())
            response = json.dumps('Internal Server Error')
            resp = Response(response, status=500, mimetype='application/json')
            return resp

【问题讨论】:

    标签: python python-2.7 flask flask-restful


    【解决方案1】:

    使用Resource.method_decorators

    https://github.com/flask-restful/flask-restful/blob/master/flask_restful/init.py#L574

    它适用于每个请求。您可以在视图类中覆盖它:

    @property
    def method_decorators(self):
        # get some limiter bound to the `g` context
        # maybe you prefer to get it from `current_app`
        return g.limiter
    

    如果您愿意,可以将限制器附加到现有的 method_decorators,然后再将资源添加到您的 RESTful API。

    ApiBase.method_decorators.append(limiter)
    imbue_api.add_resource(ApiBase, settings.BASE_API_URL)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多