2

I have a django applicaiton with multiple databases. The default database is on the local machine. There is also a remote mysql database which is used for some write operations, but it is not always up. When the server is down, mysqldb raises an OperationalError.

I would like have a local sqlite database called 'fallback' which would accept the data if the mysql server is down. I realize that this involves at try/except clause in django.db.mysql.base, but I am not quite sure where to go from there. Has anyone tried something similar? Do you have suggestions on a better way to handle this?

1 Answer 1

1

You could probably use Database Routers in combination with a custom base Model class that overrides the save method. Wrap it in a try..catch, and if the OperationalError occurs, provide some hints so your database router can determine if the fallback needs to be used.

I think this will be the cleanest way, rather than modifying the django code itself.

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

3 Comments

+1 for convincing me not to modify django code. I didn't use routers due to the specific nature of the writes to the remote DB. See my solution at stackoverflow.com/questions/4945295/…. It hadn't been working, due a related error in a connection_created signal handler.
Routers does not deal with database connections and cursors (which are responsible of OperationalError).They just select a database alias, that's to say the key in your settings.DATABASES dictionary. Did you find an alternative way to test a database connection and select another one as fallback?
You're right @Marco. I'd, now, recommend doing a try: .using['primary'] except: .using['backup'] in the save method.

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.