On May 14, 11:43 am, Antonimus <antoni...@gmail.com> wrote:
> Hi, I'm new to django and web framework. What I'm trying to do is to
> select what database to connect from html template select. In the
> login form, besides user and password, it's a select field with
> database alias to connect:
>      <select name="db_id">
>       {% for db in db %}
>              <option value "{{ db.DbCode }}">{{ db.DbCode }} |
> {{ db.DbName }}</option>
>       {% endfor %}
>    </select>
> where DbCode is db_alias from settings.py.
> How to pass DbCode value to routers.py?
> Thanks

you will need a middleware and use threading.local.

The idea is that the login form will set the used db alias into the
user's session. The middleware will then set a threading.local value
somewhere based on the session db value. Finally the router will read
the threading.local value and do routing based on that value.

However, I do not recommend the above. Instead, I would either try to
pass the DB to use explicitly (by the "using" queryset parameter), or
create a special database alias ("session_db" perhaps) which always
points to the user's selected DB. This alias does not need to exist in
the settings.py file. Again, a middleware is needed. Set the
connections['session_db'] to point to the right database
(connections['session_db'] = connections[session.login_db]) NOTE!
works only in 1.4+! Now, again use the "using" queryset argument, but
you can always set this to "session_db" for the queries which should
go to the session db. It is now explicit which queries go to the
session's database, which not.

To do any of the above you will need some knowledge of Python and/or
Django's database routing/connections implementation. For the latter
look into django.db.util, django.db.__init__ and django.db.backends.

Be careful, you are dealing with potential concurrency issues. Getting
things wrong will likely lead to confusing data corruption issues. Be
extra-careful with transaction handling. The default transaction
handling only works for the default database alias - so you will want
to make sure the user's database alias is also under transaction
control.

I hope the above helps more than confuses... :)

 - 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+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to