Busata
Busata

Reputation: 1118

Flask: Preferred way to manipulate view arguments?

I'm creating REST API with Flask & have a question related to manipulating the arguments of the view questions. I have currently two resources, "Survey" and "SurveyStep", accessible through:

/surveys
/survey/*survey-id*/steps/*step-id*

Since I'll be using the Survey resource for each request, I want it to be fetched automatically (SQLAlchemy) before each request.

Currently I found 3 ways to do this:

1) Write a URL converter, as described in (http://corbinsimpson.com/entries/be-prepared.html)

2) Use @....before_request, adding things to the request.view_args manually

3) Use @....before_request, adding it to the flask.g object

I first tried 1), which has the issue that the alchemy objects do not belong to the session, and in case of lazy relationships they need to be added first.

2) seems "dirty", as your functions get arguments that aren't really visibly declared

3) is what I'm using now, it makes the view arguments not needed in the functions itself, but it solves the session issue & it's a bit more visible than 2.

Any thoughts, caveats, improvements?

Thanks!

Upvotes: 2

Views: 141

Answers (1)

Paolo Casciello
Paolo Casciello

Reputation: 8202

Using g is a good solution for a system which always needs the Survey object.

For a mixed context I would do a simple decorator loading the appropriate Survey object and passing it to the decorated function (updating kwargs for example) or something like that. Even putting the object in g, but only for that function.

Like:

@app.route(...)
@load_survey
def do_something(....):
  ...

Upvotes: 1

Related Questions