# -*- coding: utf-8 -*-
"""
Sample settings:
DATABASE_ENGINE = 'postgresql_psycopg2'
DATABASE_NAME = 'default_db_name'
DATABASE_USER = 'user'
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
# Any omitted property will inherit the default value from settings
DATABASES = {
'default': {},
'alternative': {
'DATABASE_NAME': 'alternative_db_name',
},
}
"""
from django.conf import settings
from django.db import models, backend
# Default connection
db_settings = {
'DATABASE_HOST': settings.DATABASE_HOST,
'DATABASE_NAME': settings.DATABASE_NAME,
'DATABASE_OPTIONS': settings.DATABASE_OPTIONS,
'DATABASE_PASSWORD': settings.DATABASE_PASSWORD,
'DATABASE_PORT': settings.DATABASE_PORT,
'DATABASE_USER': settings.DATABASE_USER,
'TIME_ZONE': settings.TIME_ZONE,
}
def prepare_db_settings(db_profile_name):
"""
Takes custom database settings, replaces missing values with the
defaults from settings and returns a new connection dict.
"""
return dict(db_settings, **settings.DATABASES[db_profile_name])
class MultiDBManager(models.Manager):
"""
A manager that can connect to different databases.
"""
def use(self, db_profile_name):
"""
Return a queryset connected to a custom database.
"""
# Get customized database settings to use in a new connection wrapper
db_settings = prepare_db_settings(db_profile_name)
# Get the queryset and replace its connection
qs = self.get_query_set()
qs.query.connection = backend.DatabaseWrapper(db_settings)
return qs
#List Example
pals = list()
pals.append( "chris" )
pals.append( "sandy" )
pals.append( "josie" )
print "Items in List => " + str(pals), "List Length => " + str(len(pals))
print "\n"
#Dictionary Example: Great for placing key value pairs without knowing in advance what we will be putting in the dictionary
pal = dict()
pal['first'] = 'Chris'
pal['last'] = 'Aiv'
pal['email'] = 'chrisaiv@gmail.com'
pal['phone'] = '555-555-5555'
print pal
print "\n"
#Forgiving way to find an item within a dictionary
print pal.get("age", "Age not available")
print pal.get("phone", "Phone not available")
print "\n"
#Looping through a Dictionary
print "~~KEY : Value~~"
for key in pal:
print key, ":", pal[key]
print "\n"
#Find out what capabilities are available in a particular Data Object
print dir(pals)