Reputation: 2737
I have a Django app with two databases. One holds the critical information, and the other has some nice-to-have miscellaneous data.
The second database is not owned by me, is unreliable and I can't be sure it's always responding or that its schema always matches my Django model.
My problem is that when the Django server can't find the second database, it fails to start. What I want to do is write a Django view so that when the second database is good it shows its data, but while it's down or not adhering to the model, doesn't insist.
Would surrounding the model and router with try-catch do the trick? Anyone have any another suggestions?
Upvotes: 0
Views: 290
Reputation: 3386
If you connect to databases inside a view, you lose on the ORM provided by django. You will have to look after the security, connections and other issues all by yourself. However, if you are so adamant on doing it, you can use mysql-connector. Try this link.
Also, you need to remove the database settings for this DB from your settings file. Only keep the primary DB connection settings.
Controlling DB connections from settings(Beware this is a hack):
In your settings.py
file, make the following changes.
import mysql.connector
try:
cnx = mysql.connector.connect(user='user', password='password',
host='your_settings',
database='your_db_name')
cnx.close()
DATABASES['custom_db'] = {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'your_db_name',
'USER': 'user',
'PASSWORD': 'password',
'HOST': 'ip_where_hosted',
'PORT': '',
}
except:
pass
Upvotes: 1