我下面這個例子:速率限制類視圖瓶
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