Thursday, February 2, 2012

Re: Routing to database based on user

On Feb 3, 1:30 am, Tom Eastman <t...@catalyst.net.nz> wrote:
> Here is my solution, I wonder if you could just tell me if you think
> there's a major problem with it.
>
> In simplistic terms, the goal is "whenever a model from wxdatabase is
> accessed, route the query to the database specified in the user's
> organization's field".
>
> It consists of a piece of django middleware and a db_router.

I must warn you that I don't know too much about db routers.

> I guess my main question is: am I using threading.local() correctly?

To me it seems correct.

> class WXDatabaseMiddleware(object):
>     def process_request(self, request):
>         _local.wx_database_label = None
>
>         try:
>             profile = request.user.get_profile()
>             _local.wx_database_label = profile.organization.database.label
>         except:
>             ## This exception needs to be logged!
>             pass

I think here you should make sure you always also clear the
wx_database_label variable, so that it won't be left pointing to a
user's DB in any case. That is, you would need a finally block, and a
process_response method.

Also, I think you are going to generate some more queries than needed
by the user.profile.organization.database.label. If I guess correctly,
that is going to be 5 DB calls for each request. .select_related()
could be handy here...

>
> class WxRouter(object):
>     def _get_database_label(self):
>         return _local.wx_database_label
>
>     def read_and_write(self, model, **hints):
>         if model._meta.app_label == "wxdatabase":
>             return self._get_database_label()
>         else:
>             return None
>
>     db_for_read  = read_and_write
>     db_for_write = read_and_write

Can't comment about this.

- Anssi

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment