I am trying to load a module according to some settings. I have found a working solution but I need a confirmation from an advanced python developer that this solution is the best performance wise as the API endpoint which will use it will be under heavy load.
The idea is to change the working of an endpoint based on parameters from the user and other systems configuration. I am loading the correct handler class based on these settings. The goal is to be able to easily create new handlers without having to modify the code calling the handlers.
This is a working example:
from flask import Flask, abort import importlib import handlers app = Flask(__name__) @app.route('/') def api_endpoint(): try: endpoint = "simple" # Custom logic to choose the right handler handlerClass = getattr(importlib.import_module('.'+str(endpoint), 'handlers'), 'Handler') handler = handlerClass() except Exception as e: print(e) abort(404) print(handlerClass, handler, handler.value, handler.name()) # Handler processing. Not yet implemented return "Hello World" if __name__ == "__main__": app.run(host='0.0.0.0', port=8080, debug=True)
One "simple" handler example. A handler is a module which needs to define an
import os class Handler: def __init__(self): self.value = os.urandom(5) def name(self): return "simple"
If I understand correctly, the import is done on each query to the endpoint. It means IO in the filesystem with lookup for the modules, ...
Is it the correct/"pythonic" way to implement this strategy?
The answer so far from the previous Stack Overflow exchange:
I would whitelist if possible.
I already whitelist when I fill in the endpoint variable with my custom logic.
It does not seem to be a very clean solution. Each handler needs to define an
Handler class (same name for different class). I am searching for a cleanest "extension mecanism". How would you clean it up?
Based on @netme answer, this is the 2.0 version