def database(): if dj_database_url.config() == {}: return { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } else: return {'default': dj_database_url.config()}
def test_database_url(self): a = dj_database_url.config() assert not a os.environ['DATABASE_URL'] = 'postgres://*****:*****@ec2-107-21-253-135.compute-1.amazonaws.com:5431/d8r82722r2kuvn' url = dj_database_url.config() assert url['ENGINE'] == 'django.db.backends.postgresql_psycopg2' assert url['NAME'] == 'd8r82722r2kuvn' assert url['HOST'] == 'ec2-107-21-253-135.compute-1.amazonaws.com' assert url['USER'] == 'uf07k1i6d8ia0v' assert url['PASSWORD'] == 'wegauwhgeuioweg' assert url['PORT'] == 5431
def validate_and_heal_db_settings(foreign_globals): def validate_db_settings(): return 'DATABASES' in foreign_globals and 'default' in foreign_globals['DATABASES'] and foreign_globals['DATABASES']['default'] != {} if not validate_db_settings(): import dj_database_url default_db = foreign_globals.get('DATABASE_URL', None) if default_db: foreign_globals['DATABASES'] = {'default': dj_database_url.config(default=default_db)} else: foreign_globals['DATABASES'] = {'default': dj_database_url.config()} if not validate_db_settings(): exit_with_error(error=messages.NO_DB)
def test_database_url(self): del os.environ['DATABASE_URL'] a = dj_database_url.config() assert not a os.environ['DATABASE_URL'] = 'postgres://*****:*****@ec2-107-21-253-135.compute-1.amazonaws.com:5431/d8r82722r2kuvn' url = dj_database_url.config() assert url['ENGINE'] == EXPECTED_POSTGRES_ENGINE assert url['NAME'] == 'd8r82722r2kuvn' assert url['HOST'] == 'ec2-107-21-253-135.compute-1.amazonaws.com' assert url['USER'] == 'uf07k1i6d8ia0v' assert url['PASSWORD'] == 'wegauwhgeuioweg' assert url['PORT'] == 5431
def connect_db(): db = dj_database_url.config() return psycopg2.connect( database=db.get("NAME", "redditsearch2"), user=db.get("USER", "andrew"), password=db.get("PASSWORD", "password"), host=db.get("HOST", "localhost"), )
def get_conn(self, db_name=None, auto_commit=True): if self.db is None: self.auto_commit = auto_commit # 主库 读写 if not self.db_name: dbConf = dj_database_url.config(default = settings.DATABASE_URL) if self.db_name: dbConf = dj_database_url.config(default = getattr(settings, 'DATABASE_URL_%s' % self.db_name)) self.db = pymysql.Connect(host=dbConf['HOST'], user=dbConf['USER'], passwd=dbConf['PASSWORD'], port=int(dbConf['PORT']), db=dbConf['NAME'], charset=self.default_charset, cursorclass=pymysql.cursors.DictCursor) self.db.autocommit(self.auto_commit) self.cur = self.db.cursor() elif auto_commit != self.auto_commit: self.auto_commit = auto_commit self.db.autocommit(auto_commit)
def test_config_engine_setting(self): engine = "django_mysqlpool.backends.mysqlpool" os.environ[ "DATABASE_URL" ] = "mysql://*****:*****@us-cdbr-east.cleardb.com/heroku_97681db3eff7580?reconnect=true" url = dj_database_url.config(engine=engine) assert url["ENGINE"] == engine
def test_database_url(self): del os.environ["DATABASE_URL"] a = dj_database_url.config() assert not a os.environ[ "DATABASE_URL" ] = "postgres://*****:*****@ec2-107-21-253-135.compute-1.amazonaws.com:5431/d8r82722r2kuvn" url = dj_database_url.config() assert url["ENGINE"] == "django.db.backends.postgresql_psycopg2" assert url["NAME"] == "d8r82722r2kuvn" assert url["HOST"] == "ec2-107-21-253-135.compute-1.amazonaws.com" assert url["USER"] == "uf07k1i6d8ia0v" assert url["PASSWORD"] == "wegauwhgeuioweg" assert url["PORT"] == 5431
def populate_db(): ''' Return a dictionary with DATABASE_URL settings ''' if not os.getenv('DATABASE_URL'): return {} db = dj_database_url.config(conn_max_age=60) return db
def __init__(self): config = dj_database_url.config() self.conn = psycopg2.connect( dbname=config["NAME"], user=config["USER"], password=config["PASSWORD"], host=config["HOST"], port=config["PORT"], )
def test_database_url_with_options(self): del os.environ['DATABASE_URL'] a = dj_database_url.config() assert not a os.environ['DATABASE_URL'] = 'postgres://*****:*****@ec2-107-21-253-135.compute-1.amazonaws.com:5431/d8r82722r2kuvn?sslrootcert=rds-combined-ca-bundle.pem&sslmode=verify-full' url = dj_database_url.config() assert url['ENGINE'] == 'django.db.backends.postgresql_psycopg2' assert url['NAME'] == 'd8r82722r2kuvn' assert url['HOST'] == 'ec2-107-21-253-135.compute-1.amazonaws.com' assert url['USER'] == 'uf07k1i6d8ia0v' assert url['PASSWORD'] == 'wegauwhgeuioweg' assert url['PORT'] == 5431 assert url['OPTIONS'] == { 'sslrootcert': 'rds-combined-ca-bundle.pem', 'sslmode': 'verify-full' }
def test_database_url_with_options(self): # Test full options os.environ['DATABASE_URL'] = 'postgres://*****:*****@ec2-107-21-253-135.compute-1.amazonaws.com:5431/d8r82722r2kuvn?sslrootcert=rds-combined-ca-bundle.pem&sslmode=verify-full' url = dj_database_url.config() assert url['ENGINE'] == EXPECTED_POSTGRES_ENGINE assert url['NAME'] == 'd8r82722r2kuvn' assert url['HOST'] == 'ec2-107-21-253-135.compute-1.amazonaws.com' assert url['USER'] == 'uf07k1i6d8ia0v' assert url['PASSWORD'] == 'wegauwhgeuioweg' assert url['PORT'] == 5431 assert url['OPTIONS'] == { 'sslrootcert': 'rds-combined-ca-bundle.pem', 'sslmode': 'verify-full' } # Test empty options os.environ['DATABASE_URL'] = 'postgres://*****:*****@ec2-107-21-253-135.compute-1.amazonaws.com:5431/d8r82722r2kuvn?' url = dj_database_url.config() assert 'OPTIONS' not in url
def connect(url = None): if not os.environ.get('DATABASE_URL'): os.environ['DATABASE_URL'] = 'postgres://*****:*****@localhost:5432/livechat' param = dj_database_url.config() return psycopg2.connect( dbname = param['NAME'], user = param['USER'], password = param['PASSWORD'], host = param['HOST'], port = param['PORT'], )
def apply_settings(settings): s = settings s.DATA_ROOT = os.path.abspath(env("DATA_ROOT", os.path.join(s.PROJECT_ROOT, 'tmp'))) s.MEDIA_ROOT = env("MEDIA_ROOT", os.path.join(s.DATA_ROOT, 'media')) s.STATIC_ROOT = env("STATIC_ROOT", os.path.join(s.DATA_ROOT, 'static_collected')) s.LOG_ROOT = env("LOG_ROOT", os.path.join(s.DATA_ROOT, 'logs')) s.SOCKET_ROOT = env("SOCKET_ROOT", s.DATA_ROOT) s.REDIS_SOCKET = env("REDIS_SOCKET", os.path.join(s.SOCKET_ROOT, 'redis.sock')) s.ALLOWED_HOSTS = env("ALLOWED_HOSTS", ['127.0.0.1', 'localhost',]) import dj_database_url s.DATABASES = {'default': dj_database_url.config(default='sqlite:///%s' % os.path.join(s.DATA_ROOT, 'db.sqlite3'))}
def terminal(): global all_rows #directory = os.path.dirname(__file__) db = dj_database_url.config() conn = psycopg2.connect(db) c = conn.cursor() c.execute('SELECT last_login, email, username, first_name, last_name, school_name, student_id FROM {tn}'.format(tn = 'userauth_student')) all_rows = c.fetchall() #print all_rows conn.commit() conn.close()
def test_mysql_database_url_with_sslca_options(self): os.environ['DATABASE_URL'] = 'mysql://*****:*****@ec2-107-21-253-135.compute-1.amazonaws.com:3306/d8r82722r2kuvn?ssl-ca=rds-combined-ca-bundle.pem' url = dj_database_url.config() assert url['ENGINE'] == 'django.db.backends.mysql' assert url['NAME'] == 'd8r82722r2kuvn' assert url['HOST'] == 'ec2-107-21-253-135.compute-1.amazonaws.com' assert url['USER'] == 'uf07k1i6d8ia0v' assert url['PASSWORD'] == 'wegauwhgeuioweg' assert url['PORT'] == 3306 assert url['OPTIONS'] == { 'ssl': { 'ca': 'rds-combined-ca-bundle.pem' } } # Test empty options os.environ['DATABASE_URL'] = 'mysql://*****:*****@ec2-107-21-253-135.compute-1.amazonaws.com:3306/d8r82722r2kuvn?' url = dj_database_url.config() assert 'OPTIONS' not in url
def factorise(): """ Returns a dict of settings suitable for Django, acquired from the environment in a 12factor-y way - see http://12factor.net/config Caller probably wants to, in `settings.py`: globals().update(factorise()) """ settings = {} settings['LOGGING'] = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'stdout': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'loggers': { 'root': { 'handlers': ['stdout'], 'propagate': True, }, }, } settings['DATABASES'] = { 'default': dj_database_url.config(default='sqlite://:memory:') } settings['DEBUG'] = getenv_bool('DEBUG') if 'TEMPLATE_DEBUG' in os.environ: settings['TEMPLATE_DEBUG'] = getenv_bool('TEMPLATE_DEBUG') else: settings['TEMPLATE_DEBUG'] = settings['DEBUG'] # Slightly opinionated... if 'SECRET_KEY' in os.environ: settings['SECRET_KEY'] = os.environ['SECRET_KEY'] elif not settings['DEBUG']: sys.exit('DEBUG is False but no SECRET_KEY is set in the environment - either it has been hardcoded (bad) or not set at all (bad) - exit()ing for safety reasons') settings['CACHES'] = { 'default': django_cache_url.config(default='locmem://') } settings.update(dj_email_url.config(default='dummy://')) settings['ALLOWED_HOSTS'] = os.getenv('ALLOWED_HOSTS', '').split(',') return settings
def factorise(): """ Returns a dict of settings suitable for Django, acquired from the environment in a 12factor-y way - see http://12factor.net/config Caller probably wants to, in `settings.py`: globals().update(factorise()) """ settings = {} # Slightly opinionated... if 'SECRET_KEY' in os.environ: settings['SECRET_KEY'] = os.environ['SECRET_KEY'] else: logger.warn('No SECRET_KEY provided, using UUID') settings['SECRET_KEY'] = str(uuid.uuid4()) settings['LOGGING'] = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'stdout': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'loggers': { 'root': { 'handlers': ['stdout'], 'propagate': True, }, }, } settings['DATABASES'] = { 'default': dj_database_url.config(default='sqlite://:memory:') # Note this'll currently break due to https://github.com/kennethreitz/dj-database-url/pull/21 } settings['DEBUG'] = getenv_bool('DEBUG') if 'TEMPLATE_DEBUG' in os.environ: settings['TEMPLATE_DEBUG'] = getenv_bool('TEMPLATE_DEBUG') else: settings['TEMPLATE_DEBUG'] = settings['DEBUG'] settings['CACHES'] = { 'default': django_cache_url.config(default='locmem://') } settings.update(dj_email_url.config(default='dummy://')) return settings
def postgresify(): """Return a fully configured Django ``DATABASES`` setting. We do this by analyzing all environment variables on Heroku, scanning for postgres DBs, and then making shit happen, duh. Returns a fully configured databases dict. """ databases = {} # If the special ``DATABASE_URL`` variable is set, use this as the # 'default' database for Django. if environ.get(DEFAULT_URL, ""): databases["default"] = config() # If there is a legacy ``SHARED_DATABASE_URL`` variable set, assign this if environ.get(SHARED_URL, "") and databases.get("default", "") != config(env=SHARED_URL): databases["SHARED_DATABASE"] = config(env=SHARED_URL) # Analyze all environment variables looking for databases: for key in environ.iterkeys(): # If this is a Heroku PostgreSQL database: if ( key.startswith("HEROKU_") and "POSTGRESQL" in key and key.endswith("_URL") and databases.get("default", "") != config(env=key) ): # Generate a human-friendly database name: db_name = key.split("_") db_name.remove("HEROKU") db_name.remove("POSTGRESQL") db_name.remove("URL") db_name = "_".join(db_name) databases[db_name] = config(env=key) return databases
def apply_settings(settings): username = env('USER') # this is the unix username stage = username.split('-')[1] server_cfg = {'username': username, 'site': os.environ.get('DEPLOYMENT_SITE', 'main')} settings.DATA_ROOT = '/home/%(username)s/upload/' % server_cfg settings.MEDIA_ROOT = '/home/%(username)s/upload/media/' % server_cfg settings.STATIC_ROOT = '/home/%(username)s/static/' % server_cfg settings.LOG_ROOT = '/home/%(username)s/log/' % server_cfg settings.SOCKET_ROOT = '/home/%(username)s/tmp/' % server_cfg settings.REDIS_SOCKET = '/home/%(username)s/tmp/%(username)s_%(site)s_redis.sock' % server_cfg settings.ALLOWED_HOSTS = env("ALLOWED_HOSTS", ['%(username)s.divio.ch' % server_cfg]) import dj_database_url settings.DATABASES = {'default': dj_database_url.config(default='postgres://%(username)s@/%(username)s' % server_cfg)}
def database_config(env_varibale_pattern="HEROKU_POSTGRESQL_\S+_URL", default_env_variable="DATABASE_URL"): r = re.compile(env_varibale_pattern) urls = filter(lambda k : r.match(k) is not None, os.environ.keys()) if len(urls) > 1: if not os.environ.has_key(default_env_variable): print "Multiple env variables matching %s detected. Using %s" % (env_varibale_pattern, urls[0]) if len(urls) == 0: if not os.environ.has_key(default_env_variable): raise Exception("No database detected. Make sure you enable database on your heroku instance (e.g. heroku addons:add heroku-postgresql:dev)") return dj_database_url.config(default_env_variable, os.environ[urls[0]] if len(urls) !=0 else None)
def database_config(environment_variable, default_database_url, shard_group=None, is_replica_of=None): """ Wraps dj_database_url to provide additional arguments to specify whether a database is a shard and if it a replica of another database. """ db_config = config(env=environment_variable, default=default_database_url) if not db_config: return db_config db_config["TEST"] = db_config.get("TEST", {}) db_config["SHARD_GROUP"] = shard_group if is_replica_of: db_config["PRIMARY"] = is_replica_of db_config["TEST"]["MIRROR"] = is_replica_of return db_config
def handle(self, parsed_args): """Command entry point.""" dbinfo = None if parsed_args.dburl: dbinfo = dj_database_url.config(default=parsed_args.dburl[0]) if 'sqlite' in dbinfo['ENGINE']: parsed_args.dbtype = 'sqlite' elif 'psycopg2' in dbinfo['ENGINE']: parsed_args.dbtype = 'postgres' else: parsed_args.dbtype = 'mysql' if parsed_args.dbtype == 'sqlite': generator = SQLiteMapFilesGenerator(dbinfo) else: generator = MapFilesGenerator(dbinfo) generator.render(parsed_args)
def handle(self, parsed_args): """Command entry point.""" django.setup() dbinfo = None if parsed_args.dburl: dbinfo = dj_database_url.config(default=parsed_args.dburl[0]) if "sqlite" in dbinfo["ENGINE"]: parsed_args.dbtype = "sqlite" elif "psycopg2" in dbinfo["ENGINE"]: parsed_args.dbtype = "postgres" else: parsed_args.dbtype = "mysql" if parsed_args.dbtype == "sqlite": generator = SQLiteMapFilesGenerator(dbinfo) else: generator = MapFilesGenerator(dbinfo) generator.render(parsed_args)
def load_land_vectors(db_conn=None, url=None): if not url: url = settings.LAND_DATA_URL if db_conn: database = dj_database_url.config(default=db_conn) else: database = settings.DATABASES['feature_data'] logger.info("Downloading land data: {0}".format(url)) download_filename = download_file(url) logger.info("Finished downloading land data: {0}".format(url)) file_dir = None if os.path.splitext(download_filename)[1] == ".zip": extract_zip(download_filename) file_dir = os.path.splitext(download_filename)[0] file_name = get_vector_file(file_dir) else: file_name = download_filename cmd = 'ogr2ogr -s_srs EPSG:3857 -t_srs EPSG:4326 -f "PostgreSQL" ' \ 'PG:"host={host} user={user} password={password} dbname={name} port={port}" ' \ '{file} land_polygons'.format(host=database['HOST'], user=database['USER'], password=database['PASSWORD'].replace('$', '\$'), name=database['NAME'], port=database['PORT'], file=file_name) logger.info("Loading land data...") exit_code = subprocess.call(cmd, shell=True) if exit_code: logger.error("There was an error importing the land data.") if file_dir: shutil.rmtree(file_dir) os.remove(download_filename) try: os.remove(file_name) except OSError: pass finally: logger.info("Finished loading land data.")
def main(): config = dj_database_url.config() conn = psycopg2.connect( database=config['NAME'], user=config['USER'], password=config['PASSWORD'], host=config['HOST'], port=config['PORT'] ) cur = conn.cursor() conn.autocommit = True inp = read_input() cur.execute(inp) # hasattr(cur, 'commit') and cur.commit() cur.close() conn.close()
def databases(): # Database config on Heroku is simple if 'HEROKU' in os.environ and os.environ['HEROKU']: import dj_database_url return { 'default': dj_database_url.config() } try: from ndiaDjango import config except ImportError: config = None # Note whether configuration was provided or not configed = bool(config) or 'DATABASE_URL' in os.environ # Set values with provided configuration or default config = config if config else object() user = getattr(config, 'user', '') password = getattr(config, 'password', '') host = os.environ.get('DATABASE_URL', getattr(config, 'host', '')) port = getattr(config, 'port', '') if configed: engine = 'django.db.backends.postgresql_psycopg2' name_of_database = getattr(config, 'name_of_database', 'ndia') logger.info('Using PostgreSQL Database') else: engine = 'django.db.backends.sqlite3' name_of_database = 'ndia.db' logger.info('Using SQLite Database') return { 'default': { 'ENGINE': engine, 'NAME': name_of_database, 'USER': user, 'PASSWORD': password, 'HOST': host, 'PORT': port, } }
def database_config(environment_variable, default_database_url, database_name=None, shard_group=None, is_replica_of=None): """ Wraps dj_database_url to provide additional arguments to specify whether a database is a shard and if it a replica of another database. If database_name is provided, it will override the database name in the environment_variable URL """ db_config = config(env=environment_variable, default=default_database_url) if not db_config: return db_config db_config['TEST'] = db_config.get('TEST', {}) db_config['SHARD_GROUP'] = shard_group if database_name is not None: db_config['NAME'] = database_name if is_replica_of: db_config['PRIMARY'] = is_replica_of db_config['TEST']['MIRROR'] = is_replica_of return db_config
def heroku_settings(): # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES['default'] = dj_database_url.config() # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] # Static asset configuration import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) return
def get_template_context(self, options): """Build the context used to render templates.""" dburl = options.get("dburl") db_settings = ( dj_database_url.config(default=dburl) if dburl else settings.DATABASES["default"]) if "sqlite" in db_settings["ENGINE"]: dbtype = "sqlite" elif "psycopg2" in db_settings["ENGINE"]: dbtype = "postgres" else: dbtype = "mysql" commandline = "{} {}".format( os.path.basename(sys.argv[0]), " ".join(sys.argv[1:])) context = { "date": timezone.now(), "commandline": commandline, "dbtype": dbtype, "dbuser": db_settings["USER"], "dbpass": db_settings["PASSWORD"], "dbname": db_settings["NAME"], "dbhost": db_settings.get("HOST", "127.0.0.1"), } return context
WSGI_APPLICATION = 'adv_project.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } DATABASES = { } #creating an empty database so python doesnt get mad at next line DATABASES['default'] = dj_database_url.config(conn_max_age=600) # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME':
# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # social authenticaion # http://psa.matiasaguirre.net/docs/index.html AUTHENTICATION_BACKENDS = ( 'social.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_FACEBOOK_KEY = '1005810502839407' SOCIAL_AUTH_FACEBOOK_SECRET = '256beb6f7c0a90738813864b04084383' # Define SOCIAL_AUTH_FACEBOOK_SCOPE to get extra permissions from facebook. # Email is not sent by deafault, to get it, you must request the email permission: SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'publish_actions'] SOCIAL_AUTH_REDIRECT_IS_HTTPS = True # This is because heroku fails to pass the headers required to identify the app. # Only when running in Heroku if "DYNO" in os.environ: STATIC_ROOT = 'staticfiles' import dj_database_url DATABASES['default'] = dj_database_url.config() DEBUG = True # False, once service is succesfully deployed ALLOWED_HOSTS = ['*']
import os PROJECT_DIR = Path(__file__).parent.parent FS_FEE = Decimal('0.03') DEBUG = False FRESPO_PROJECT_ID = -1 # only needed for backwards compatibility with south patch 0008_set_isfeedback_true.py ADMINS = (('Admin', '*****@*****.**'), ) TEMPLATE_DEBUG = DEBUG MANAGERS = ADMINS DATABASES = { 'default': dj_database_url.config(default='sqlite:///' + PROJECT_DIR.child('database.db')) } GITHUB_BOT_USERNAME = '******' GITHUB_BOT_PASSWORD = '******' SITE_PROTOCOL = 'http' SITE_HOST = 'www.freedomsponsors.org' SITE_NAME = 'FreedomSponsors' SITE_HOME = SITE_PROTOCOL + '://' + SITE_HOST PAYPAL_USE_SANDBOX = False PAYPAL_DEBUG = False PAYPAL_IPNNOTIFY_URL_TOKEN = 'megablasteripn' PAYPAL_API_USERNAME = "******" PAYPAL_API_PASSWORD = '******'
}, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } DATABASES['default'].update(dj_database_url.config(conn_max_age=500)) # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME':
) MIDDLEWARE += ['audit_logging.middleware.UserDetailsMiddleware'] AUDIT_MODELS = [ ('eventkit_cloud.tasks.models.ExportRun', 'ExportRun'), ('eventkit_cloud.tasks.models.DataProviderTaskRecord', 'DataProviderTaskRecord'), ('eventkit_cloud.tasks.models.ExportTaskRecord', 'ExportTaskRecord'), ] DATABASES = {} if os.getenv('VCAP_SERVICES'): if os.getenv('DATABASE_URL'): DATABASES = {'default': dj_database_url.config()} if not DATABASES: for service, listings in json.loads( os.getenv('VCAP_SERVICES')).items(): try: if ('pg_95' in service) or ('postgres' in service): DATABASES['default'] = dj_database_url.config( default=listings[0]['credentials']['uri']) DATABASES['default']['CONN_MAX_AGE'] = 180 except (KeyError, TypeError) as e: print( ("Could not configure information for service: {0}".format( service))) print(e) continue if DATABASES:
#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #EMAIL_HOST = 'smtp.gmail.com' #EMAIL_PORT = 587 #EMAIL_HOST_USER = '******' #EMAIL_HOST_PASSWORD = '' #EMAIL_USE_TLS = True DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' import dj_database_url # customize database configuration DATABASES = { 'default': dj_database_url.config( default= 'postgres://*****:*****@localhost:5432/familybridge') } MIDDLEWARE_CLASSES = ( # 'johnny.middleware.LocalStoreClearMiddleware', # 'johnny.middleware.QueryCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
class Common(Configuration): INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third party apps 'rest_framework', # utilities for rest apis 'rest_framework.authtoken', # token authentication 'django_filters', # for filtering rest endpoints # Your apps 'bookshelf.users', 'books', 'rentals', ) # https://docs.djangoproject.com/en/2.0/topics/http/middleware/ MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ALLOWED_HOSTS = ["*"] ROOT_URLCONF = 'bookshelf.urls' SECRET_KEY = os.getenv('DJANGO_SECRET_KEY') WSGI_APPLICATION = 'bookshelf.wsgi.application' # Email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' ADMINS = ( ('Author', '*****@*****.**'), ) # Postgres DATABASES = { 'default': dj_database_url.config( default='postgres://postgres:@postgres:5432/postgres', conn_max_age=int(os.getenv('POSTGRES_CONN_MAX_AGE', 600)) ) } # General APPEND_SLASH = False TIME_ZONE = 'UTC' LANGUAGE_CODE = 'en-us' # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = False USE_L10N = True USE_TZ = True LOGIN_REDIRECT_URL = '/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_ROOT = os.path.normpath(join(os.path.dirname(BASE_DIR), 'static')) STATICFILES_DIRS = [] STATIC_URL = '/static/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # Media files MEDIA_ROOT = join(os.path.dirname(BASE_DIR), 'media') MEDIA_URL = '/media/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': STATICFILES_DIRS, 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Set DEBUG to False as a default for safety # https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = strtobool(os.getenv('DJANGO_DEBUG', 'no')) # Password Validation # https://docs.djangoproject.com/en/2.0/topics/auth/passwords/#module-django.contrib.auth.password_validation AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(server_time)s] %(message)s', }, 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, }, 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, 'django.request': { 'handlers': ['mail_admins', 'console'], 'level': 'ERROR', 'propagate': False, }, 'django.db.backends': { 'handlers': ['console'], 'level': 'INFO' }, } } # Custom user app AUTH_USER_MODEL = 'users.User' # Django Rest Framework REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': int(os.getenv('DJANGO_PAGINATION_LIMIT', 10)), 'DATETIME_FORMAT': '%Y-%m-%dT%H:%M:%S%z', 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ) }
'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'petshelter.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': dj_database_url.config(default=os.environ.get('DATABASE_URL')) } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, {
if config('MODE')=="dev": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':'gallery', 'PASSWORD':'******', 'USER':'******', 'HOST': '127.0.0.1', 'PORT':5432, } } #production else: DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', },
# --------------------------------------------------------------------------- # # Course: PYTHON 230: Internet Programming With Python # Script Title: # Change Log: (Who, When, What) # D. Rodriguez, 2019-08-15, Initial release # --------------------------------------------------------------------------- # import dj_database_url from .settings import * import os DATABASES = { 'default': dj_database_url.config(default='sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')) } DEBUG = False TEMPLATE_DEBUG = False ALLOWED_HOSTS = [os.environ.get('ALLOWED_HOSTS'), 'localhost'] STATIC_ROOT = os.path.join(BASE_DIR, 'static') SECRET_KEY = os.environ.get('SECRET_KEY')
# ('Your Name', '*****@*****.**'), ) MANAGERS = ADMINS INTERNAL_IPS = get_list(os.environ.get('INTERNAL_IPS', '127.0.0.1')) CACHES = {'default': django_cache_url.config()} if os.environ.get('REDIS_URL'): CACHES['default'] = { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': os.environ.get('REDIS_URL')} DATABASES = { 'default': dj_database_url.config( default='postgres://*****:*****@localhost:5432/saleor', conn_max_age=600)} TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us' LOCALE_PATHS = [os.path.join(PROJECT_ROOT, 'locale')] USE_I18N = True USE_L10N = True USE_TZ = True FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' EMAIL_URL = os.environ.get('EMAIL_URL') SENDGRID_USERNAME = os.environ.get('SENDGRID_USERNAME') SENDGRID_PASSWORD = os.environ.get('SENDGRID_PASSWORD')
'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'todolist.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = {'default': dj_database_url.config()} # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME':
# Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } DATABASE_URL = os.getenv('DATABASE_URL', False) if DATABASE_URL is not False: DATABASES['default'].update(dj_database_url.config()) # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ # { # 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', # }, # { # 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', # }, # { # 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', # },
# STATICFILES_DIRS = ( # os.path.join(BASE_DIR, '../foodtaskerapp/static'), # ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') LOGIN_REDIRECT_URL = '/' # AUTH_USER_MODEL = 'LocalUser' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) # Facebook configuration SOCIAL_AUTH_FACEBOOK_KEY = '598963994090483' SOCIAL_AUTH_FACEBOOK_SECRET = '4eca1790f6830d63531051df15fdb089' # Google configuration SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '296361253961-2071gn8pk4lp74rag297q5fqtkvo9bjo.apps.googleusercontent.com' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'CLMPCKBjtM8L88ALQa-2XirC' # Github configuration SOCIAL_AUTH_GITHUB_KEY = '4aa1d9e6957d711e4be8' SOCIAL_AUTH_GITHUB_SECRET = '5e1c58151b6984143e6d0db2a026fd7b3dbe3c4a'
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ CAS_SERVER_URL = 'https://fed.princeton.edu/cas/' LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/New_York' USE_I18N = True USE_L10N = True USE_TZ = True # Change 'default' database configuration with $DATABASE_URL. DATABASES['default'].update(dj_database_url.config(conn_max_age=500, ssl_require=True)) # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static_root') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [
}, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', } } DATABASES['default'] = dj_database_url.config( default= 'postgres://*****:*****@ec2-54-158-122-162.compute-1.amazonaws.com:5432/d9jlnu99al0ihh' ) db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
"django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "garnett.context_processors.languages", ], }, }, ] # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { "default": dj_database_url.config(default="sqlite:///" + str(BASE_DIR / "db.sqlite3")) } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, {
# social media "social_django.context_processors.backends", # <-- "social_django.context_processors.login_redirect", # <-- ], }, }, ] WSGI_APPLICATION = "teambyc.wsgi.application" # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases if config("PROD", cast=bool, default=False) == True: ALLOWED_HOSTS = ["*"] DATABASES = {} DATABASES["default"] = dj_database_url.config( default=config("DATABASE_URL")) # SECURE_SSL_REDIRECT = True else: ALLOWED_HOSTS = config("DOMAINS").split(',') DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {
import os ROOT = os.path.dirname(__file__) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '*****@*****.**'), ) MANAGERS = ADMINS import dj_database_url DATABASES = {'default': dj_database_url.config(default='sqlite:///db.sqlite')} # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True
import dj_database_url DATABASES = {'default': dj_database_url.config(default='postgres://localhost')} DEBUG = False
"django.contrib.auth.context_processors.auth", "strut.context_processors.preact", ], "builtins": [ "django.contrib.staticfiles.templatetags.staticfiles", "strut.templatetags.core", ], }, }] WSGI_APPLICATION = "strut.wsgi.application" SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") DATABASES = { "default": dj_database_url.config("STRUT_DATABASE_URL", default="postgres://[email protected]:5432/strut") } AUTH_USER_MODEL = "strut.User" AUTHENTICATION_BACKENDS = [ "social_core.backends.google.GoogleOAuth2", # 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = env("GOOGLE_OAUTH2_CLIENT_ID") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = env("GOOGLE_OAUTH2_CLIENT_SECRET") SOCIAL_AUTH_GOOGLE_OAUTH2_USER_FIELDS = ["email"] SOCIAL_AUTH_PIPELINE = ( "social_core.pipeline.social_auth.social_details", "social_core.pipeline.social_auth.social_uid",
{ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' # settings.py # Heroku: Update database configuration from $DATABASE_URL. import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env)
USE_I18N = True USE_L10N = True USE_TZ = False CAS_SERVER_URL = "https://login.iiit.ac.in/cas/" CAS_LOGOUT_COMPLETELY = True CAS_PROVIDE_URL_TO_LOGOUT = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'action/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' import dj_database_url prod_db = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(prod_db) ALLOWED_HOSTS = [ 'heckermen-plus-one.herokuapp.com' ]
import os import sys # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Include BOOTSTRAP3_FOLDER in path BOOTSTRAP3_FOLDER = os.path.abspath(os.path.join(BASE_DIR, '..', 'bootstrap3')) if BOOTSTRAP3_FOLDER not in sys.path: sys.path.insert(0, BOOTSTRAP3_FOLDER) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ SECRET_KEY = SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&022shmi1jcgihb*' DEBUG = True DATABASES = {'default': dj_database_url.config(default='postgres://*****:*****@localhost/postgresql-shallow-44207')} ALLOWED_HOSTS = ['*'] # cache settings CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } }
WSGI_APPLICATION = 'djorg.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } # DATABASES['default'] = dj_database_url.config(default='postgres://...') DATABASES = {'default': dj_database_url.config(default=config('DATABASE_URL'))} # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME':
APPEND_SLASH = True MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') if "RENDER" in os.environ: DEBUG = False RENDER_EXTERNAL_HOSTNAME = os.environ.get('RENDER_EXTERNAL_HOSTNAME') if RENDER_EXTERNAL_HOSTNAME: ALLOWED_HOSTS.append(RENDER_EXTERNAL_HOSTNAME) DATABASES = {'default': dj_database_url.config(conn_max_age=600)} AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'metalink' AWS_S3_REGION_NAME = 'nyc3' AWS_S3_ENDPOINT_URL = f'https://metalink.{AWS_S3_REGION_NAME}.digitaloceanspaces.com/' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'theme/static'), ]
'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'example_project.wsgi.application' DATABASES = { # Configure by setting the DATABASE_URL environment variable. # The default settings may work well for local development. 'default': dj_database_url.config() or { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'hordak', 'HOST': '127.0.0.1', 'PORT': '5432', 'USER': getpass.getuser(), 'PASSWORD': '', } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME':
"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'mysite.log', 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'propagate': True, 'level': 'DEBUG', }, 'MYAPP': { 'handlers': ['file'], 'level': 'DEBUG', }, } } DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)
USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' # static 파일들이 현재 어디에 있는지를 쓰는 곳 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'blog', 'static') ] # static 파일들이 어디로 모일 것인지를 쓰는 곳 STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Heroku: Update database configuration from $DATABASE_URL. import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env)
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] #whitenoseが必要 STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' #Herokuでのデプロイに必要なため追加。 STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CRISPY_TEMPLATE_PACK = 'bootstrap3' import dj_database_url db_from_env = dj_database_url.config() DATABASES = {'default': dj_database_url.config()} try: from .local_settings import * except ImportError: pass #本番環境において、以下が適応される。AWSの設定もここに追加しよう。 if not DEBUG: SECRET_KEY = os.environ['SECRET_KEY'] AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']