Django - Guardar configuración de DB para cargarla al iniciar

 
Vista:
sin imagen de perfil
Val: 5
Ha disminuido su posición en 2 puestos en Django (en relación al último mes)
Gráfica de Django

Guardar configuración de DB para cargarla al iniciar

Publicado por Antonio (2 intervenciones) el 03/09/2018 16:03:08
El problema que tengo es que trabajo con 2 base de datos una en postgresql y la otra en sql server , desde el visual se guarda la configuracion de la base de datos db_app2 lo que es usuario, contraseña, servidor y el nombre de la base de datos y guardo en un archivo .py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def save_db_settings_to_file(form):
path_to_store_settings = os.path.join(settings.BASE_DIR, 'SystemProyect')
for fname in os.listdir(path_to_store_settings):
    if fname=='conexion.cfg':
        full_path = os.path.join(path_to_store_settings, fname)
        remove(full_path)
 
database_id = 'db_app2'  # just something unique
newDatabase = {}
newDatabase["id"] = database_id
newDatabase['ENGINE'] = 'sql_server.pyodbc'
newDatabase['NAME'] = form.data['database']
newDatabase['USER'] = form.data['usuario_sql']
newDatabase['PASSWORD'] = form.data['password_sql']
newDatabase['HOST'] = form.data['servidor_sql']
newDatabase['PORT'] = ''
settings.DATABASES[database_id] = newDatabase
 
newDbString = """DATABASES={'%(id)s':{
'ENGINE': '%(ENGINE)s', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '%(NAME)s',                      # Or path to database file if using sqlite3.
'USER': '%(USER)s',                      # Not used with sqlite3.
'PASSWORD': '%(PASSWORD)s',                  # Not used with sqlite3.
'HOST': '%(HOST)s',                      # Set to empty string for localhost. Not used with sqlite3.
'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
'OPTIONS':"{'driver': 'SQL Server Native Client 10.0',}"
} }
"""% newDatabase
file_to_store_settings = os.path.join(path_to_store_settings, 'conexion' + ".py")
salvar=open(file_to_store_settings,'w')
salvar.write(newDbString)
salvar.close()

y en un fichero python llamado settings_manager.py tengo este codigo que le hago un import settings_manager en setitings.py

1
2
3
4
5
6
7
8
import os
path_to_store_settings =  os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'SystemProyect')
for fname in os.listdir(path_to_store_settings):
  if fname == 'conexion.py':
      full_path = os.path.join(path_to_store_settings, fname)
      with open(full_path) as fobj:
        archivo_inicio = fobj.read()
    exec(archivo_inicio)

así me guarda el archivo conexion.py

1
2
3
4
5
6
7
8
9
10
11
DATABASES = {
    'db_app2': {
        'ENGINE': 'sql_server.pyodbc',  # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'prueba',  # Or path to database file if using sqlite3.
        'USER': 'tony',  # Not used with sqlite3.
        'PASSWORD': '123456',  # Not used with sqlite3.
        'HOST': '10.16.41.2',  # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',  # Set to empty string for default. Not used with sqlite3.
        'OPTIONS': "{'driver': 'SQL Server Native Client 10.0',}"
    }
}
Pero cuando inicio el servidor no carga los datos para utilizarlo en algunos métodos que hago consultas a la base de datos a partir de los modelos hechos con inspecdb o con conections['db_app2'].cursor() y me devuelve el error que no encuentra la base de datos ´db_app2´, y cuando lo pongo normal en el setings.py me funciona
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder