I\'m using Flask to expose some data-crunching code as a web service. I\'d like to have some class variables that my Flask functions can access.
Let me walk you through
The least-coupled solution is to apply the routes at runtime (instead of at load time):
def init_app(flask_app, database_interface, filesystem_interface):
server = MyServer(database_interface, filesystem_interface)
flask_app.route('get_data', methods=['GET'])(server.get_data)
This is very testable--just invoke init_app()
in your test code with the mocked/faked dependencies (database_interface
and filesystem_interface
) and a flask app that has been configured for testing (app.config["TESTING"]=True
or something like that) and you're all-set to write tests that cover your entire application (including the flask routing).
The only downside is this isn't very "Flasky" (or so I've been told); the Flask idiom is to use @app.route()
, which is applied at load time and is necessarily tightly coupled because dependencies are hard-coded into the implementation instead of injected into some constructor or factory method (and thus complicated to test).