Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to merge two Django projects' user tables?

Tags:

I've got two Django projects on the same server. The first launched several months ago, and has since collected hundreds of user accounts. The second project is launching in a few days, and we'd like the second project to allow users of the first app to authenticate using the same credentials.

At first, I was going to simply dump the user table from the first project into the second project, but this would not allow for a synchronous solution (user creates account on project B, does not then have access to project A).

Does Django have some way of natively switching database names (since they're on the same server) for user authentication, and then back to the original database when finished with authentication?

If not, what do you think would be the best solution for my problem? Also - we're using MySQL.

like image 206
Nick Sergeant Avatar asked Dec 04 '08 20:12

Nick Sergeant


2 Answers

If you wait awhile, eventually Django will get multiple database support.

But as of right now, I think the best solution to your problem would be to synchronize the two database's user tables after changes to either are made. You can use the signals support to handle this:

from django.db import models

def user_post_save(sender, instance, **kwargs):
    ... run script to synchronize tables ...
models.signals.post_save.connect(user_post_save, sender=User)

You won't be able to use the ORM... but dumping the source table, then dropping the destination and importing into it would be relatively painless. This could definitely cause timing problems, but transactions would mostly solve that. If the two sites stepping on each other is a concern, I might look into setting up a write lock on the User table during the update, and set up some kind of a spin-wait cycle on the User model's save() method (or the pre_save signal) to check for a lock before completing the save. This would guarantee that the post_save signal won't get sent during a synchronization.

like image 162
Daniel Naab Avatar answered Sep 23 '22 04:09

Daniel Naab


This will probably get me shot; but you could create the user table of the new project simply as a view of the first project:

DROP TABLE proj2.users;
CREATE VIEW proj2.users AS SELECT * FROM proj1.users;
like image 42
eliego Avatar answered Sep 22 '22 04:09

eliego