Numerous Django Databases - Not Always Available

I am developing a Django application that will use multiple database backends. I would like to host the sqlite database on the machine running the django application and synchronize with the remote mysql database. The hard part is that the machine on which the application is running will not always have an Internet connection, so the mysql database is not always available. There will be several computers running the application, each of which has its own local sqlite database, but all use the same remote mysql database.

I haven't written the code yet, but here is what I mean. Each time I run an insert or update, I would like to write it to both databases if the remote database is not available, in which case I will save the sql statement in a table in the local database to run when the remote database is available.

Can this be done using database routers, or do I need to manually implement this with each db instruction?

Note on PC: It is not directly related, but it will certainly be offered. A primary key will be generated locally on each machine. In mysql DB there will be a field for this key and a field with a unique identifier for each application instance, which together will provide a unique key.

+4
source share
2 answers

Suppose you have a model called "Bag", then you can use the following to save it locally and remotely (provided that you have configured access to the remote db).

blog = Blog('test') blog.save() #Assuming that sqlite is the default db try: blog.save(using='mysql') except NoInternetConnection: pass 

Make sure you define and configure "mysql" in settings.py and you handle cases where there is no internet connection.

Side note: I'm not quite sure why you really want to do this. If this is for backup purposes, I would use standard backup procedures. For more information on using multiple databases, see http://docs.djangoproject.com/en/dev/topics/db/multi-db/#using-raw-cursors-with-multiple-databases

+3
source

I took the DrDee code and bound it to the post_save signal (+1 for reference).

 @receiver(models.signals.post_save) #new signal decorator in Django 1.3 def save_to_remote(sender,instance,using,**kwargs): if using == 'default' and instance.__module__ == 'mymodel.myapp.models': try: instance.save(using='remote') except: pending_instance=Pending_Remote( pk_default=instance.pk, model_default=instance.__class__.__name__ ) pending_instance.save() 

It also retains a record of what was not stored in the remote database. Note that the Pending_Remote model should not be in 'myapp'.

+2
source

Source: https://habr.com/ru/post/1339025/


All Articles