2

I'd like to switch databases upon user login. I've created this login signal.. but it doesn't work

from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in
from django.db import connections

@receiver(user_logged_in)
def db_switch(sender, **kwargs):
    user_db = 'userdb_%s' % kwargs['user'].username
    cursor = connections[user_db].cursor()

The databases are defined in settings.py. Do I have to make this cursor global? Or is this all the way wrong way of doing it?

Thanks!

Mission
  • 1,287
  • 3
  • 16
  • 31
  • 1
    hmm, sounds like really badddd practice! Why should every user have their own database? – Willian Mar 28 '12 at 13:44
  • It's an SaaS learning project... separate databases are a good practice for SaaS... I've found examples with subdomains and db switching based on that... but I don't need that I'd like to switch db's based on users... – Mission Mar 28 '12 at 14:48
  • Hmmm... posted my answer before I saw your new comment. Subdomains is the *only* way to do it, because you need to modify the databases at the beginning of the request, not in the middle. Everything I've seen suggests that attempting to change global settings mid-request is a **bad thing**. – Jordan Reiter Mar 28 '12 at 14:57
  • Thanks Jordan, damn I really wanted to do this without subdomains... I need this for 5 users tops... – Mission Mar 28 '12 at 15:05
  • I don't know of any SaaS that uses separate databases for each user but all on the same domain... – Jordan Reiter Mar 28 '12 at 21:18

1 Answers1

2

It's the wrong way of doing it.

Honestly I don't think there is a straightforward, stable way of doing this in Django. It's just not designed for it.

Instead, I'd set up a settings_username.py file for each user, which specifies a secondary database called personal or something. Then, after logging, have them redirect to a new domain, like username.example.com, which uses a unique .wsgi file that pulls in the settingsusername.py file.

Now, as far as the system is concerned, each website is totally separate and unique to that user. Just make sure to set the session cookie to example.com so that they're still logged in when they go to their user website.

Jordan Reiter
  • 20,467
  • 11
  • 95
  • 161
  • Hi, I don't want domains because I don't need them... that's why I've been looking around for a way without subdomains... the other options I've thought about is example.com/user but I think that's just bad... – Mission Mar 28 '12 at 15:03
  • Sounds like maybe a framework other than Django would be better suited, then. – Jordan Reiter Mar 28 '12 at 21:17