librelist archives

« back to archive

where to put caching code in flask?

where to put caching code in flask?

From:
Oby Sumampouw
Date:
2014-04-28 @ 04:00
Hi,

I'm new to flask and was wondering if someone can tell me the best
practices for coding in flask.
I have a question about the caching pattern in flask. I'm using sqlalchemy
and dogpile cache.
My question is about the location on where to put the caching code.

For example let's say we have a model Person with fields id and name. If we
imagine this as MVC pattern, the model is Person, the controller happens in
the url route methods and the view is in the html layer.

So let's assume that we have the url-routing
@app.route("/person")
def foo():
if it's a GET method
returns the person

if it's a PUT method
it will update the person in the database.

Normally with caching, I would just put the logic in method foo() like the
following:
if person in cache, then returns that person.
else query database using the Person model and refresh the cache.

My only concern with this pattern is if there are other controller classes
that wants to use the Person object in the future then these controllers
must also use this if-then cache check.

Ideally I would put the "check cache" mechanism in the Person model itself.

So what is the best practice about this? Should we create a method in
Person model
to access/update/create the entity and force controller to always use this
method when operating on the database?

Or is there other better alternative? How to prevent someone just calling
Person.query (skipping caching altogether)?

Thanks
-Oby