jobou
jobou

Reputation: 1863

How to use correctly importlib in a flask controller?

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 :

./run.py :

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 Handler class :

./handlers/simple.py :

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 ?

Upvotes: 2

Views: 764

Answers (1)

jobou
jobou

Reputation: 1863

Question moved to codereview. Thanks all for your help : https://codereview.stackexchange.com/questions/96533/extension-pattern-in-a-flask-controller-using-importlib

I am closing this thread.

Upvotes: 1

Related Questions