Reputation: 7276
I have built flask apis in the past, but I've never had the luxury of being on a project where I was allowed to do test driven development while working on one. Now I am.
Every how-to I've ever read shows flask-apis being defined in a decidedly non-object-oriented style. This makes writing unit tests very difficult because one cannot pass optional or test-specific parameters into the instantiated api.
For example, this blog explains one method for creating unit tests for a flask-api: http://mkelsey.com/2013/05/15/test-driven-development-of-a-flask-api/
The blog sets an environment variable when in test mode and the script watches for that variable, altering its behavior when it is found. This seems very inadvisable to me. There are a long list of reasons why letting your source code bleed into your OS environment is a Bad Idea. I'm a big believer in encapsulating functionality in order to maximize portability and to draw clear distinctions between where modules begin and end.
In order to satisfy my coding philosophy someone might suggest I just wrap the flask API up in a class. However, it isn't clear to me how one would do such a thing. For example, Flask uses decorators in order to define a route:
@app.route()
How could this be fit into a class?
I would greatly appreciate the guidance of anyone who has developed a flask api in an object oriented manner.
Upvotes: 2
Views: 3676
Reputation: 311
You can replace the use of @app.route
with add_url_rule
.
To put it in an example:
from flask import Flask
class MyFlaskApp:
def __init__(self):
self.app = Flask(__name__)
self.app.add_url_rule('/', 'index', self.index)
def index(self):
pass
Which is similar to:
from flask import Flask
app = Flask(__name__)
@app.route('/index')
def index():
pass
Upvotes: 11