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!

5
  • 1
    hmm, sounds like really badddd practice! Why should every user have their own database? Commented Mar 28, 2012 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... Commented Mar 28, 2012 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. Commented Mar 28, 2012 at 14:57
  • Thanks Jordan, damn I really wanted to do this without subdomains... I need this for 5 users tops... Commented Mar 28, 2012 at 15:05
  • I don't know of any SaaS that uses separate databases for each user but all on the same domain... Commented Mar 28, 2012 at 21:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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...
Sounds like maybe a framework other than Django would be better suited, then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.