librelist archives

« back to archive

lazy loading of sessions

lazy loading of sessions

From:
Bastian Hoyer
Date:
2011-12-27 @ 16:09
Hi,

I was playing with the new flask session interface today and while I
was debugging I noticed that the session is loaded on every request,
even on static files.

I wonder if it would make sense to delay the open_session call until
the first access to the session object, so the session would only get
loaded when it's necessary.

Bastian

Re: [flask] lazy loading of sessions

From:
Simon Sapin
Date:
2011-12-28 @ 07:29
Le 27/12/2011 17:09, Bastian Hoyer a écrit :
> Hi,
>
> I was playing with the new flask session interface today and while I
> was debugging I noticed that the session is loaded on every request,
> even on static files.
>
> I wonder if it would make sense to delay the open_session call until
> the first access to the session object, so the session would only get
> loaded when it's necessary.
>
> Bastian

Hi,

First, if you worry about performance you should serve static files with 
a front-end web server, not with Flask.

Once you’ve done that, can you measure (use profiling tools) that 
session loading takes a significant time on requests that do not use the 
session in your app? No need to make faster what is already fast, and 
you need to measure that, not guess.

If you still want to do this, open_session() is called in 
flask.ctx.RequestContext.push:

https://github.com/mitsuhiko/flask/blob/master/flask/ctx.py#L135

I guess you could have it called later (not sure how) or have it return 
a lazy proxy object instead. I would go for the later, and do it in 
flask.app.Flask.open_session, so that open_session need not be changed 
for each session backend.

Oh, and once you have something working, profile again and compare with 
before.

Regards,
-- 
Simon Sapin