基于Python速率限制类的视图Flas

2024-05-15 23:49:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我以这个例子为例:

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"

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

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

文件信息:

  • 在应用程序副本在
  • 美国石油学会_主.py在

低于应用程序副本我已经定义了我的资源:

^{pr2}$

在api中_主.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

Tags: 文件apijson应用程序flaskgetreturn定义
1条回答
网友
1楼 · 发布于 2024-05-15 23:49:07

使用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

如果愿意,可以在将资源添加到restfulapi之前,将限制器附加到现有的method_decorators。在

^{pr2}$

相关问题 更多 >