Last active
May 27, 2017 19:49
-
-
Save VanDavv/f2f92305df23694bc9ff6511e9a3f1eb to your computer and use it in GitHub Desktop.
[Django] Script which initializes Your db with data You provided in Your settings.py (For PostgreSQL databases)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import psycopg2 | |
from emily_backend import settings # pass Your settings here | |
db_config = settings.DATABASES.get('default') | |
logger = logging.getLogger(__name__) | |
try: | |
conn = psycopg2.connect(f"" | |
f"dbname='postgres' " | |
f"user='postgres' " | |
f"port='{db_config.get('PORT')}' " | |
f"host='{db_config.get('HOST') }' " | |
f"password='postgres'" | |
) | |
conn.set_isolation_level(0) | |
cursor = conn.cursor() | |
cursor.execute(f"CREATE DATABASE {db_config.get('NAME')}") | |
cursor.execute(f"CREATE ROLE {db_config.get('USER')} WITH PASSWORD \'{db_config.get('PASSWORD')}\'") | |
cursor.execute(f"ALTER ROLE {db_config.get('USER')} WITH LOGIN") | |
cursor.execute(f"ALTER ROLE {db_config.get('USER')} CREATEDB") | |
cursor.execute(f"GRANT ALL PRIVILEGES ON DATABASE {db_config.get('NAME')} TO {db_config.get('USER')}") | |
except: | |
logger.warning("Initialization failed, skipping") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment