Is it somehow possible to access the request object inside settings.py? Maybe by creating a temporary settings object, modifying it and then telling the rest of the "chain" to use that instead of the normal settings.py?
I need it to decide which DB-connection to use.
As an extra question. If I were to have something like 5000 database connections, would settings.py be just as efficient as storing them in a sqlite db on the 开发者_运维技巧web-frontend? And would it be just as painless to update the connections? Or does the server have to be reloaded to catch the changes in settings.py?
Edit: To clarify why I might be needing that many connections. I am building a webapp. It's SaaS and like many others the accounts will each have a subdomain that they can create users on and will have no need to interact with any other subdomain/account. It would then be nice to confine each account to a DB all of its own. This grants some extra security and simplifies the app. There are many more advantages to it, but this should illustrate it just fine. This is why I might end up with that many different databases (but not that many different physical servers if that makes any difference).
If i understand this right, you could use django's new db-routing system and select database on-the-fly based on model instance (e.g. your user) without the need of using()
call.
Just adding this for anyone else looking for the same. It is not currently possible. I have created a feature request on the Django bug-tracker (#13056 i think) and submitted a prototype for a fix, but I don't think it will be included anytime soon and it probably has a lot of bugs in it.
I have moved the project to Flask as it has the g
object that is perfectly suited for this.
Django's ORM is not designed to switch database credentials mid-stride. Perhaps you would be happier with something a bit more DIY, such as SQLAlchemy.
I've addressed this problem on a site I've been using recently, and decided to let Apache/mod_wsgi do the work. This solution adds a bit of memory and CPU overhead, but for my app it was the best way to keep everything flexible.
Apache .conf:
SetEnv DJANGO_TEMPLATE_DIR '/usr/local/www/apache22/data/django/templates/'
<VirtualHost *:80>
ServerName encendio.whatever.com
ServerAdmin your_admin@whatever.com
DocumentRoot "/usr/local/www/apache22/data"
SetEnv DJANGO_DATABASE_NAME monkeys
SetEnv DJANGO_DATABASE_USER root
SetEnv DJANGO_DATABASE_PASSWORD secretPass
SetEnv DJANGO_DATABASE_PORT ''
SetEnv DJANGO_DATABASE_HOST ''
WSGIScriptAlias / /usr/local/www/apache22/data/django/wsgi_handler.py
</VirtualHost>
settings.py:
DATABASE_NAME = os.environ.get('DJANGO_DATABASE_NAME', '')
DATABASE_USER = os.environ.get('DJANGO_DATABASE_USER', '')
DATABASE_PASSWORD = os.environ.get('DJANGO_DATABASE_PASSWORD', '')
DATABASE_HOST = os.environ.get('DJANGO_DATABASE_HOST', '')
This allows you to set up each site as a VirtualHost in the httpd.conf
.
精彩评论