THE QUESTION
All of my app's routes are defined via flask-restful Resources. How can I find the resource object/class that is processing current request?
WHY I WANT THIS
I wanted to log all exceptions raised while processing requests. I connect to flask.got_request_exception
, as described in http://flask.pocoo.org/docs/1.0/api/#signals and something like this works well:
from flask import got_request_exception, request
def log_exception(sender, exception, **extra):
logger.info("URL: {}, Exception: {}".format(request.url, type(exception).__name__))
got_request_exception.connect(log_exception, app)
The only problem is that I want to log some of the request data, but not all the data - e.g. I'd like to hide passwords. I think it would be a good idea to have logging-data-logic together with request processing logic, like this:
from flask import request
import flask_restful
class SomeResource(flask_restful.Resource):
def get(self):
# ... GET processing
def log_data(self):
# log all body params
return request.get_json()
class Login(flask_restful.Resource):
def post(self):
# ... authentication
def log_data(self):
# log selected body params
return {'login': request.get_json()['login'], 'password': 'HIDDEN!'}
and than use it in my log_exception
:
from flask import got_request_exception, request
def log_exception(sender, exception, **extra):
resource_class = # THIS IS THE THING I'M MISSING
logger.info("URL: {}, Exception: {}, Data: {}".format(request.url, type(exception).__name__),
resource_class.log_data())
got_request_exception.connect(log_exception, app)
But maybe this should be done other way?