pythonflask

Python Flask Blueprint with classes


I am looking at moving to blueprints in Flask, but the current implementation passes the flask app instance into a class as part of the init(), how do I do this with blueprints please?

def __init__(self, flask_instance, logger, event_manager):
    self._logger = logger
    self._flask = flask_instance
    self._event_manager = event_manager

    # Add route : /management/add
    self._quart.add_url_rule('/job/new_job',
        methods = ['POST'], view_func = self._new_job)

Solution

  • You put the blueprint into the class construction

    class Test(object):
        blueprint = Blueprint("Test", __name__)
        def __init__(self, db_host, db_port):
            self.db_host = db_host
            self.db_port = db_port
        def loadDb(self):
            return Connection(self.db_host, self.db_port)
        @blueprint.route("/<var>")
        def testView(var): # adding self here gives me an error
            return render_template("base.html", myvar=self.loadDb().find({"id": var})
    

    Reference: How to pass class's self through a flask.Blueprint.route decorator?