class Local(ProjectDefault): """The local settings.""" # Application definition INSTALLED_APPS = ProjectDefault.INSTALLED_APPS.copy() MIDDLEWARE = ProjectDefault.MIDDLEWARE.copy() # Debug # https://docs.djangoproject.com/en/{{docs_version}}/ref/settings/#debug DEBUG = True # Email URL # https://django-configurations.readthedocs.io/en/stable/values/ EMAIL = values.EmailURLValue("console://") # Django Debug Toolbar # https://django-debug-toolbar.readthedocs.io/en/stable/configuration.html try: import debug_toolbar # noqa except ModuleNotFoundError: # pragma: no cover pass else: # pragma: no cover INTERNAL_IPS = values.ListValue([], environ_name="ALLOWED_HOSTS") INSTALLED_APPS.append("debug_toolbar") MIDDLEWARE.append("debug_toolbar.middleware.DebugToolbarMiddleware")
class Qa(Common): """ The qa settings and the default configuration. """ DEBUG = False THUMBNAIL_DEBUG = False EMAIL = values.EmailURLValue('smtp://localhost:25')
class Prod(Common): """ The in-production settings. """ DEBUG = False THUMBNAIL_DEBUG = False EMAIL = values.EmailURLValue('smtp://localhost:25')
class Beta(ProjectDefault): """The beta settings.""" # Debug # https://docs.djangoproject.com/en/{{docs_version}}/ref/settings/#debug DEBUG = False # Email URL # https://django-configurations.readthedocs.io/en/stable/values/ EMAIL = values.EmailURLValue("console://")
class Testing(ProjectDefault): """The testing settings.""" # Debug # https://docs.djangoproject.com/en/stable/ref/settings/#debug DEBUG = False # Email URL # https://django-configurations.readthedocs.io/en/stable/values/ EMAIL = values.EmailURLValue("dummy://", environ=False)
class Prod(Common): """ The in-production settings """ DEBUG = False SECRET_KEY = values.SecretValue() ADMINS = values.SingleNestedTupleValue() ALLOWED_HOSTS = values.ListValue() DATABASES = values.DatabaseURLValue() EMAIL = values.EmailURLValue() REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ), } STATIC_ROOT = values.PathValue() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'pilotwire_handler': { 'level': 'INFO', 'class': 'heating.log.PilotwireHandler', 'logLength': 500, }, }, 'loggers': { 'heating.pilotwire': { 'handlers': ['pilotwire_handler'], 'level': 'INFO', }, }, } # Authentication AUTHENTICATION_BACKENDS = [ 'core.auth.backends.SettingsBackend', ] + Common.AUTHENTICATION_BACKENDS # pylint: disable=no-member ADMIN_LOGIN = values.Value() ADMIN_PASSWORD = values.SecretValue()
def before_binding(configuration: Type[ComposedConfiguration]) -> None: email = cast( Dict[str, str], values.EmailURLValue( environ_name='EMAIL_URL', environ_prefix='DJANGO', environ_required=True, # Disable late_binding, to make this return a usable value (which is a simple dict) # immediately late_binding=False, ), ) for email_setting, email_setting_value in email.items(): setattr(configuration, email_setting, email_setting_value)
class Production(Remote): """The production settings.""" # Debug # https://docs.djangoproject.com/en/stable/ref/settings/#debug DEBUG = False # Email URL # https://django-configurations.readthedocs.io/en/stable/values/ EMAIL = values.EmailURLValue() # Security # https://docs.djangoproject.com/en/stable/topics/security/ SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True
class Production(ProjectDefault): """The production settings.""" # Debug # https://docs.djangoproject.com/en/{{docs_version}}/ref/settings/#debug DEBUG = False # Email URL # https://django-configurations.readthedocs.io/en/stable/values/ EMAIL = values.EmailURLValue() # Deployment # https://docs.djangoproject.com/en/{{docs_version}}/howto/deployment/checklist/ SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True X_FRAME_OPTIONS = "DENY" # Default: 'SAMEORIGIN'
class Prod(Base): u"""Configuração para Produção.""" DEBUG = False EMAIL = values.EmailURLValue( 'smtp://[email protected]:[email protected]:465/?ssl=True') ALLOWED_HOSTS = ['.gestaolivre.org'] @classmethod def pre_setup(cls): u"""Executado antes da Configuração.""" super(Base, cls).pre_setup() @classmethod def setup(cls): u"""Executado depois da Configuração.""" super(Base, cls).setup() logging.info('Configurações de produção carregadas: %s', cls) @classmethod def post_setup(cls): u"""Executado depois da Configuração.""" super(Base, cls).post_setup()
class Base(Configuration): LANGUAGE_CODE = '{{cookiecutter.django_language_code}}' TIME_ZONE = '{{cookiecutter.time_zone}}' ADMINS = ( ('{{cookiecutter.author_name}}', '{{cookiecutter.email}}'), ) MANAGERS = ADMINS USE_I18N = True USE_L10N = True USE_TZ = True ALLOWED_HOSTS = [ os.environ['DJANGO_ALLOWED_HOSTS'], ] PROJECT_DIR = Path(__file__).ancestor(2) STATIC_ROOT = PROJECT_DIR.child('static') STATIC_URL = '/static/' MEDIA_ROOT = PROJECT_DIR.child('media') MEDIA_URL = '/media/' DATABASES = values.DatabaseURLValue() EMAIL = values.EmailURLValue() SECRET_KEY = values.Value() SITE_ID = 1 ROOT_URLCONF = '{{cookiecutter.repo_name}}.urls' WSGI_APPLICATION = '{{cookiecutter.repo_name}}.wsgi.application' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.admindocs', '{{cookiecutter.repo_name}}', ] MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.admindocs.middleware.XViewMiddleware', ] CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': os.environ['DJANGO_HIREDIS_CACHE_LOCATION'], 'OPTIONS': { 'DB': 1, 'PARSER_CLASS': 'redis.connection.HiredisParser', } }, } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [PROJECT_DIR.child('templates')], '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', 'django.template.context_processors.csrf', '{{cookiecutter.repo_name}}.context_processors.debug', ], }, }, ]
class ProjectDefault(Configuration): """ The default settings from the Django project template. Django Configurations https://django-configurations.readthedocs.io """ # Build paths inside the project like this: BASE_DIR / "subdir". BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/stable/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = values.SecretValue() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = values.BooleanValue(True) ALLOWED_HOSTS = values.ListValue([]) # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] 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", ] ROOT_URLCONF = "{{cookiecutter.project_slug}}.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "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", ] }, } ] WSGI_APPLICATION = "{{cookiecutter.project_slug}}.wsgi.application" # Database # https://docs.djangoproject.com/en/stable/ref/settings/#databases DATABASES = values.DatabaseURLValue() # Password validation # https://docs.djangoproject.com/en/stable/ref/settings/#auth-password-validators # fmt: off AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", # noqa }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # fmt: on # Internationalization # https://docs.djangoproject.com/en/stable/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/stable/howto/static-files/ STATIC_URL = "/static/" STATIC_ROOT = BASE_DIR / "static" STATICFILES_STORAGE = ( "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ) # Stored files # https://docs.djangoproject.com/en/stable/topics/files/{% if cookiecutter.use_media_volume == "Yes" %} # noqa MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media" # noqa{% else %} # MEDIA_URL = "/media/" # MEDIA_ROOT = BASE_DIR / "media"{% endif %} # Email Settings # https://docs.djangoproject.com/en/stable/topics/email/ ADMINS = values.SingleNestedTupleValue( (("admin", "errors@{{cookiecutter.domain_url}}"),) ) DEFAULT_FROM_EMAIL = values.EmailValue("info@{{cookiecutter.domain_url}}") EMAIL_SUBJECT_PREFIX = "[{{cookiecutter.project_name}}] " EMAIL_USE_LOCALTIME = True SERVER_EMAIL = values.EmailValue("server@{{cookiecutter.domain_url}}") # Email URL # https://django-configurations.readthedocs.io/en/stable/values/ EMAIL = values.EmailURLValue("console://") # Translation # https://docs.djangoproject.com/en/stable/topics/i18n/translation/ # LANGUAGES = (("en", "English"), ("it", "Italiano")) # Clickjacking Protection # https://docs.djangoproject.com/en/stable/ref/clickjacking/ X_FRAME_OPTIONS = "SAMEORIGIN" # Default: 'SAMEORIGIN'
class Base(Settings): # Django settings for localshop project. PROJECT_ROOT = os.path.dirname(__file__) BASE_DIR = os.path.dirname(os.path.abspath(os.path.join(__file__, '..'))) CACHES = values.CacheURLValue('dummy://') django_debug = os.environ.get('DJANGO_DEBUG', 'False').upper() == 'TRUE' DEBUG = django_debug TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '*****@*****.**'), ) MANAGERS = ADMINS DATABASES = values.DatabaseURLValue( 'sqlite:///' + os.path.join(DEFAULT_PATH, 'localshop.db')) # 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. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = values.Value('UTC') # 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 # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" # MEDIA_ROOT = 'files' MEDIA_ROOT = '/media' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" # STATIC_ROOT = 'assets' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/assets/' STATIC_ROOT = values.Value( default=os.path.join(BASE_DIR, 'public', 'static')) # Additional locations of static files STATICFILES_DIRS = [os.path.join(PROJECT_ROOT, 'static')] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = values.SecretValue() SESSION_COOKIE_AGE = 28 * 24 * 60 * 60 # 4 weeks # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', #'django.template.loaders.eggs.Loader', ) TEMPLATE_CONTEXT_PROCESSORS = [ 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.contrib.messages.context_processors.messages', ] MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.http.ConditionalGetMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'localshop.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'localshop.wsgi.application' TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, 'templates'), ) MESSAGE_TAGS = {messages.ERROR: 'danger'} BROKER_URL = "django://" CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERYD_FORCE_EXECV = False CELERYBEAT_SCHEDULE = { # Executes every day at 1:00 AM 'every-day-1am': { 'task': 'localshop.apps.packages.tasks.update_packages', 'schedule': crontab(hour=1, minute=0), }, } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.humanize', 'kombu.transport.django', 'djcelery', 'gunicorn', 'widget_tweaks', 'localshop', 'localshop.apps.accounts', 'localshop.apps.dashboard', 'localshop.apps.packages', 'localshop.apps.permissions', 'raven.contrib.django.raven_compat', ] # Auth settings AUTHENTICATION_BACKENDS = ( 'localshop.apps.accounts.backend.AccessKeyBackend', 'localshop.apps.accounts.backend.LDAPBackend', 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = '/accounts/login' LOGIN_REDIRECT_URL = '/dashboard/' LOGOUT_URL = '/accounts/logout' AUTH_USER_MODEL = 'accounts.User' # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'handlers': ['console'], 'propagate': True, 'level': 'DEBUG', }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler' }, }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, }, } EMAIL = values.EmailURLValue('smtp://localhost:25/') ALLOWED_HOSTS = ['*'] LOCALSHOP_DELETE_FILES = False DEFAULT_FILE_STORAGE = values.Value( 'storages.backends.overwrite.OverwriteStorage') LOCALSHOP_HTTP_PROXY = None LOCALSHOP_ISOLATED = False LOCALSHOP_RELEASE_OVERWRITE = True # Use X-Forwarded-For header as the source for the client's IP. # Use where you have Nginx/Apache/etc as a reverse proxy infront of Localshop/Gunicorn. LOCALSHOP_USE_PROXIED_IP = False LOCALSHOP_VERSIONING_TYPE = None # AWS S3 Settings AWS_ACCESS_KEY_ID = values.Value() AWS_SECRET_ACCESS_KEY = values.Value() AWS_STORAGE_BUCKET_NAME = values.Value() # LDAP Authentication AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_X_TLS_REQUIRE_CERT: ldap.OPT_X_TLS_NEVER, } AUTH_LDAP_START_TLS = True AUTH_LDAP_SERVER_URI = os.environ.get('AUTH_LDAP_SERVER_URI', 'ldap://ldapsample.com') AUTH_LDAP_BIND_DN = os.environ.get('AUTH_LDAP_BIND_DN', 'cn=username,dc=ldapsample,dc=com') AUTH_LDAP_BIND_PASSWORD = os.environ.get('AUTH_LDAP_BIND_PASSWORD', 'sompass') #AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=ldapsample,dc=com" if 'AUTH_LDAP_USER_DN_TEMPLATE' in os.environ: AUTH_LDAP_USER_DN_TEMPLATE = os.environ['AUTH_LDAP_USER_DN_TEMPLATE'] AUTH_LDAP_USER_SEARCH_BASE = os.environ.get( 'AUTH_LDAP_USER_SEARCH_BASE', 'ou=users,dc=ldapsample,dc=com') AUTH_LDAP_USER_SEARCH_QUERY = os.environ.get('AUTH_LDAP_USER_SEARCH_QUERY', '(uid=%(user)s)') AUTH_LDAP_USER_SEARCH = LDAPSearch(AUTH_LDAP_USER_SEARCH_BASE, ldap.SCOPE_SUBTREE, AUTH_LDAP_USER_SEARCH_QUERY)
class Base(Configuration): LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/New_York' LOGIN_URL = reverse_lazy('auth_login') LOGIN_REDIRECT_URL = reverse_lazy('api-root') LOGOUT_REDIRECT_URL = reverse_lazy('auth_login') ADMINS = () MANAGERS = ADMINS USE_I18N = True USE_L10N = True USE_TZ = True USE_X_FORWARDED_HOST = True ALLOWED_HOSTS = ['*'] PROJECT_DIR = Path(__file__).ancestor(2) LOCALE_PATH = PROJECT_DIR.child('locale') STATIC_ROOT = PROJECT_DIR.child('static-compiled') STATIC_URL = '/static/' STATICFILES_DIRS = [PROJECT_DIR.child('static')] MEDIA_ROOT = PROJECT_DIR.child('media') MEDIA_URL = '/media/' DATABASES = values.DatabaseURLValue().value SLAVE_DATABASES = ['default'] if os.environ.get('READ_REPLICA_DATABASE_URL'): DATABASES.update( values.DatabaseURLValue( # pragma: no cover alias='read-replica', environ_name='READ_REPLICA_DATABASE_URL').value) SLAVE_DATABASES = ['read-replica'] # pragma: no cover DATABASE_ROUTERS = ('multidb.MasterSlaveRouter', ) # pragma: no cover EMAIL = values.EmailURLValue() SECRET_KEY = values.Value() SITE_ID = 1 ROOT_URLCONF = 'impact.urls' WSGI_APPLICATION = 'impact.wsgi.application' INSTALLED_APPS = [ 'paypal.standard', 'paypal.pro', 'paypal.standard.pdt', 'accelerator.apps.AcceleratorConfig', 'simpleuser.apps.SimpleuserConfig', 'corsheaders', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'sorl.thumbnail', 'embed_video', 'oauth2_provider', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_swagger', 'fluent_pages', 'impact', ] ACCELERATOR_MODELS_ARE_MANAGED = True AUTH_USER_MODEL = 'simpleuser.User' MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.admindocs.middleware.XViewMiddleware', 'django.middleware.locale.LocaleMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'impact.middleware.MethodOverrideMiddleware', ] CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': os.environ['DJANGO_HIREDIS_CACHE_LOCATION'], 'OPTIONS': { 'DB': 1, 'PARSER_CLASS': 'redis.connection.HiredisParser', } }, } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [PROJECT_DIR.child('templates')], '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', 'django.template.context_processors.csrf' ], }, }, ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'localhost:1234', 'localhost:8000', ) CORS_ORIGIN_REGEX_WHITELIST = ( r'^(https?://)?(\w+\.)?masschallenge\.org$', ) ALGOLIA_INDEX_PREFIX = os.environ.get('ALGOLIA_INDEX_PREFIX', 'dev') ALGOLIA_INDEXES = [ '{algolia_prefix}_mentor'.format(algolia_prefix=ALGOLIA_INDEX_PREFIX) ] NEW_RELIC_CONFIG_FILE = os.path.join(PROJECT_DIR, 'newrelic.ini') NEW_RELIC_ENVIRONMENT = os.environ.get('NEW_RELIC_ENVIRONMENT', 'development') ALGOLIA_APPLICATION_ID = os.environ.get('ALGOLIA_APPLICATION_ID', '') ALGOLIA_API_KEY = os.environ.get('ALGOLIA_API_KEY', '') ALGOLIA_STAFF_SEARCH_ONLY_API_KEY = os.environ.get( 'ALGOLIA_STAFF_SEARCH_ONLY_API_KEY', '') ALGOLIA_SEARCH_ONLY_API_KEY = os.environ.get('ALGOLIA_SEARCH_ONLY_API_KEY', '') V0_SECURITY_KEY = bytes( os.environ.get('IMPACT_API_V0_SECURITY_KEY', 'XXX'), 'utf-8') V0_IMAGE_PASSWORD = bytes( os.environ.get('IMPACT_API_V0_IMAGE_PASSWORD', 'XXX'), 'utf-8') V0_SITE_NAME = bytes( os.environ.get('IMPACT_API_V0_SITE_NAME', 'masschallenge.org'), 'utf-8') V0_API_GROUP = bytes( os.environ.get('IMPACT_API_V0_API_GROUP', 'v0_clients'), 'utf-8') # This and the above should get generalized. See AC-4574. V1_API_GROUP = bytes( os.environ.get('IMPACT_API_V1_API_GROUP', 'v1_clients'), 'utf-8') V1_CONFIDENTIAL_API_GROUP = bytes('v1_confidential', 'utf-8') OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': { 'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups' } } # settings.py REST_PROXY = { 'HOST': os.environ.get('ACCELERATE_SITE_URL', 'https://accelerate.masschallenge.org'), 'AUTH': { 'user': None, 'password': None, # Or alternatively: 'token': None, }, 'VERIFY_SSL': False, } REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': ('rest_framework.pagination.LimitOffsetPagination'), 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } AUTHENTICATION_BACKENDS = ( 'oauth2_provider.backends.OAuth2Backend', 'simpleuser.email_model_backend.EmailModelBackend', 'django.contrib.auth.backends.ModelBackend', ) SESSION_COOKIE_AGE = 3600 * 24 * 7 * 2 # default JWT_AUTH = { 'JWT_ALLOW_REFRESH': False, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=(SESSION_COOKIE_AGE * 2)), # after timedelta has passed, token is no longer valid, and cannot # be refreshed any longer 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(seconds=(SESSION_COOKIE_AGE * 2)), # after timedelta has passed since first obtaining the token, # it is no longer possible to refresh the token, even if the token # did not expire 'JWT_AUTH_COOKIE': os.environ.get('JWT_AUTH_COOKIE', ''), 'JWT_SECRET_KEY': os.environ.get('JWT_SECRET_KEY', ''), } PAYPAL_WPP_USER = '' PAYPAL_WPP_PASSWORD = '' PAYPAL_WPP_SIGNATURE = '' PAYPAL_RECEIVER_EMAIL = '' PAYPAL_IDENTITY_TOKEN = '' MPTT_SWAPPABLE_INDUSTRY_MODEL = "accelerator.Industry" MPTT_SWAPPABLE_INDUSTRY_MODEL_ADDITIONAL = "accelerator.Industry" MPTT_SWAPPABLE_INDUSTRY_DB_TABLE_NAME = ( "accelerator_startup_related_industry") MPTT_SWAPPABLE_FUNCTIONALEXPERTISE_MODEL = ( "accelerator.FunctionalExpertise") CMS_FILE_ROOT = '/var/www/cms-files'
class Base(Configuration): # Django settings for test_project project. DEBUG = values.BooleanValue(True, environ=True) TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '*****@*****.**'), ) EMAIL_URL = values.EmailURLValue('console://', environ=True) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # 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 # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '-9i$j8kcp48(y-v0hiwgycp5jb*_)sy4(swd@#m(j1m*4vfn4w' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'test_project.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'test_project.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'configurations', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
class Base(Configuration): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) SECRET_KEY = values.SecretValue() DEBUG = values.BooleanValue(False) ALLOWED_HOSTS = values.ListValue(['*']) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third apps 'rest_framework', 'drf_yasg', # Local apps 'library.apps.authors.apps.AuthorsConfig', 'library.apps.base.apps.BaseConfig', 'library.apps.books.apps.BooksConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'library.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(PROJECT_DIR, 'templates')], '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', ], }, }, ] WSGI_APPLICATION = 'library.wsgi.application' DATABASES = values.DatabaseURLValue('sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3')) 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', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' EMAIL = values.EmailURLValue('console://') REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer', ), 'PAGE_SIZE': 10, } SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'Basic': { 'type': 'basic' }, 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header' } }, 'USE_SESSION_AUTH': False }
class Base(Configuration): # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = values.Value() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = values.BooleanValue(False) ALLOWED_HOSTS = values.ListValue([]) # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # App locals "src.apps.core.apps.CoreConfig", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "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", ] ROOT_URLCONF = "src.urls" TEMPLATES = [{ "BACKEND": "django.template.backends.django.DjangoTemplates", "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", ] }, }] WSGI_APPLICATION = "src.wsgi.application" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = values.DatabaseURLValue("sqlite:///" + os.path.join(BASE_DIR, "db.sqlite3")) # Password validation # https://docs.djangoproject.com/en/3.2/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" }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator" }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = values.Value("en-us") TIME_ZONE = values.Value("UTC") USE_I18N = values.BooleanValue(True) USE_L10N = values.BooleanValue(True) USE_TZ = values.BooleanValue(True) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" # See https://docs.djangoproject.com/en/2.2/topics/email/#console-backend EMAIL = values.EmailURLValue("console://") # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
class Base(Configuration): u"""Configuração comum para todos os ambientes.""" DEBUG = values.BooleanValue(False) ADMINS = values.SingleNestedTupleValue( (('Sergio Garcia', '*****@*****.**'), )) MANAGERS = values.SingleNestedTupleValue( (('Sergio Garcia', '*****@*****.**'), )) DATABASES = values.DatabaseURLValue( 'postgres://postgres@localhost/postgres') CACHES = values.CacheURLValue('locmem://') EMAIL = values.EmailURLValue('console://') EMAIL_SUBJECT_PREFIX = values.Value('[%s] ' % SITE_NAME) TIME_ZONE = values.Value('America/Sao_Paulo') LANGUAGE_CODE = values.Value('pt-br') USE_I18N = values.BooleanValue(True) USE_L10N = values.BooleanValue(True) USE_TZ = values.BooleanValue(True) MEDIA_ROOT = normpath(join(SITE_ROOT, 'media')) MEDIA_URL = values.Value('/media/') STATIC_ROOT = values.PathValue(normpath(join(SITE_ROOT, 'static'))) STATIC_URL = values.Value('/static/') STATICFILES_DIRS = (normpath(join(SITE_ROOT, 'bower_components')), ) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] SECRET_KEY = values.SecretValue() ALLOWED_HOSTS = [] FIXTURE_DIRS = (normpath(join(SITE_ROOT, 'fixtures')), ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [normpath(join(SITE_ROOT, 'templates'))], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.request', ], 'debug': DEBUG }, }, ] MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'gestaolivre.apps.utils.middleware.GlobalRequestMiddleware', ] ROOT_URLCONF = '%s.urls' % SITE_NAME DJANGO_APPS = ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'django.contrib.humanize', 'django.contrib.admin', 'mptt', 'django_mptt_admin', 'widget_tweaks', 'brazil_fields') LOCAL_APPS = ( 'gestaolivre.apps.cadastro', 'gestaolivre.apps.utils', ) INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS LOGIN_REDIRECT_URL = '/' 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', }, ] WSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME TEST_RUNNER = 'django.test.runner.DiscoverRunner' MIGRATION_MODULES = {} INSTALLED_APPS += ( 'rest_framework', 'rest_framework_jwt', 'corsheaders', ) REST_FRAMEWORK = values.DictValue({ 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.SessionAuthentication', # 'rest_framework.authentication.BasicAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), }) CORS_ORIGIN_ALLOW_ALL = values.Value(True) CORS_ALLOW_CREDENTIALS = values.Value(True) INSTALLED_APPS += ('compressor', ) STATICFILES_FINDERS += ('compressor.finders.CompressorFinder', ) COMPRESS_PRECOMPILERS = ( ('text/coffeescript', 'coffee --compile --stdio'), ('text/less', 'lessc --source-map-map-inline {infile} {outfile}'), ('text/x-sass', 'sass {infile} {outfile}'), ('text/x-scss', 'sass --scss {infile} {outfile}'), ) JWT_AUTH = values.DictValue({ 'JWT_EXPIRATION_DELTA': datetime.timedelta(minutes=5), 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_ALLOW_REFRESH': True, 'JWT_AUTH_HEADER_PREFIX': 'Bearer', 'JWT_RESPONSE_PAYLOAD_HANDLER': jwt_response_payload_handler }) @classmethod def pre_setup(cls): u"""Executado antes da Configuração.""" super(Base, cls).pre_setup() @classmethod def setup(cls): u"""Executado depois da Configuração.""" super(Base, cls).setup() logging.info('Configurações comuns carregadas: %s', cls) @classmethod def post_setup(cls): u"""Executado depois da Configuração.""" super(Base, cls).post_setup() logging.debug("done setting up! \o/")
class Common(Configuration): # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = values.SecretValue() DEBUG = True THUMBNAIL_DEBUG = DEBUG ALLOWED_HOSTS = values.ListValue([''], separator=';') ADMINS = (('Philip Kalinsky', '*****@*****.**'), ) DATE_FORMAT = '%m/%d/%Y' EMAIL = values.EmailURLValue('console://') DEFAULT_FROM_EMAIL = '*****@*****.**' NOREPLY_EMAIL = '*****@*****.**' INTERNAL_IPS = ('127.0.0.1', ) MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' SESSION_STORAGE = 'django.contrib.sessions.backends.cache' #SESSION_ENGINE = 'redis_sessions.session' # Application definition INSTALLED_APPS = ( 'charityadmin.apps.longerusername', 'django.contrib.contenttypes', 'grappelli.dashboard', 'grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'charityadmin.apps.paws', 'charityadmin.apps.timeslots', 'django_extensions', ) MIDDLEWARE_CLASSES = ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) ROOT_URLCONF = 'charityadmin.apps.paws.urls' WSGI_APPLICATION = 'charityadmin.wsgi.application' # Database # https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#databases # http://django-configurations.readthedocs.org/en/latest/values/#configurations.values.DatabaseURLValue DATABASES = values.DatabaseURLValue() EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' SITE_ID = 1 # Localization LANGUAGE_CODE = 'en' LOCALE_PATHS = (os.path.join(BASE_DIR, 'charityadmin', 'locale'), ) ugettext = lambda s: s LANGUAGES = (('en', ugettext('English')), ) USE_I18N = True USE_L10N = True TIME_ZONE = 'America/New_York' USE_TZ = True #RAVEN_CONFIG = {'dsn': os.environ.get('SENTRY_RAVEN_DSN', ''),} DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'charityadmin', 'static') STATIC_URL = '/static/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'charityadmin', 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.messages.context_processors.messages', 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.request', ], #'loaders': [ # 'django.template.loaders.cached.Loader', ( # 'django.template.loaders.filesystem.Loader', # 'django.template.loaders.app_directories.Loader', # ), #], }, }, ] CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } #django-grappelli GRAPPELLI_INDEX_DASHBOARD = 'charityadmin.dashboard.CustomIndexDashboard' GRAPPELLI_ADMIN_TITLE = "PAWS NYC CMS" LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' }, }, 'handlers': { 'syslog': { 'class': 'logging.handlers.SysLogHandler', 'facility': SysLogHandler.LOG_LOCAL7, 'address': '/dev/log', 'formatter': 'standard', }, 'stderr': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'standard', }, #'mail_admins': { # 'level': 'ERROR', # 'class': 'django.utils.log.AdminEmailHandler', # 'include_html': False, #}, 'request_handler': { 'class': 'logging.NullHandler', }, }, 'loggers': { '': { 'handlers': ['syslog', 'stderr'], 'level': 'DEBUG', 'propagate': True }, 'django.request': { 'handlers': ['stderr'], 'level': 'ERROR', 'propagate': True, }, 'django.db.backends': { # Stop SQL debug from logging to main logger 'handlers': ['request_handler'], 'level': 'DEBUG', 'propagate': False }, } }
class Common(Configuration): VERSION = values.Value('0.0.0-x', environ_prefix='ID') SITE_NAME = values.Value('Investigative Dashboard', environ_prefix='ID') INSTALLED_APPS = ( 'django.contrib.contenttypes', 'django.contrib.auth', # Third party apps 'rest_framework', 'corsheaders', 'django_filters', 'social_django', 'activity', # Your apps 'api_v3', ) MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ) ALLOWED_HOSTS = ["*"] ROOT_URLCONF = 'api_v3.urls' SECRET_KEY = values.SecretValue() WSGI_APPLICATION = 'api_v3.wsgi.application' USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ROUTER_CLASS = 'rest_framework.routers.DefaultRouter' # Email EMAIL = values.EmailURLValue('console://') DEFAULT_FROM_EMAIL = values.EmailValue('', environ_prefix='ID', environ_required=True) DEFAULT_FROM = '{} <{}>'.format(SITE_NAME, DEFAULT_FROM_EMAIL) ADMINS = [] # Postgres DATABASES = values.DatabaseURLValue( 'postgres://postgres:@postgres:5432/postgres') # CORS CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = values.ListValue(['localhost:8000']) CORS_ORIGIN_ALLOW_ALL = values.BooleanValue(False) # Sentry RAVEN_CONFIG = { 'dsn': values.Value('', environ_name='SENTRY_DSN', environ_prefix=''), 'release': VERSION, } # 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 = False USE_TZ = False # Media files: max. size of 500MB MEDIA_ROOT = values.Value(environ_name='MEDIA_ROOT', environ_prefix='', environ_required=True) MAX_UPLOAD_SIZE = 1024 * 1024 * 500 STATIC_URL = '/api/static/' DEBUG = values.BooleanValue(False) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ os.path.abspath( os.path.join(os.path.dirname(__file__), '..', 'templates')), ], }, ] # Logging LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, } } # Custom user app AUTH_USER_MODEL = 'api_v3.Profile' # Authentication AUTHENTICATION_BACKENDS = values.ListValue([ 'api_v3.misc.oauth2.KeycloakOAuth2', ]) SOCIAL_AUTH_KEYCLOAK_BASE = values.Value('', environ_prefix='') SOCIAL_AUTH_KEYCLOAK_KEY = values.Value('', environ_prefix='') SOCIAL_AUTH_KEYCLOAK_SECRET = values.Value('', environ_prefix='') SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = values.Value('', environ_prefix='') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = values.Value('', environ_prefix='') # Username is not used. SOCIAL_AUTH_USER_FIELDS = ['email'] # See: http://python-social-auth.readthedocs.io/en/latest/pipeline.html SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.user.user_details', 'api_v3.misc.oauth2.activate_user', 'api_v3.misc.oauth2.map_email_to_subscriber', ) # Django Rest Framework REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.SessionAuthentication', ) } # JSON API DRF JSON_API_FORMAT_KEYS = 'dasherize' JSON_API_FORMAT_TYPES = 'dasherize' JSON_API_PLURALIZE_TYPES = True
class Remote(ProjectDefault): """The remote settings.""" # Debug # https://docs.djangoproject.com/en/stable/ref/settings/#debug DEBUG = False MIDDLEWARE = ProjectDefault.MIDDLEWARE.copy() # Email URL # https://django-configurations.readthedocs.io/en/stable/values/ EMAIL = values.EmailURLValue() # Security # https://docs.djangoproject.com/en/stable/topics/security/ CSRF_COOKIE_SECURE = True SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_SSL_REDIRECT = False SECURE_HSTS_PRELOAD = True X_FRAME_OPTIONS = "DENY" # Persistent connections # https://docs.djangoproject.com/en/stable/ref/databases/#general-notes CONN_MAX_AGE = None # Session auth # https://docs.djangoproject.com/en/stable/ref/settings/#sessions SESSION_COOKIE_SECURE = True # WhiteNoise # http://whitenoise.evans.io/en/stable/django.html try: import whitenoise # noqa except ModuleNotFoundError: # pragma: no cover pass else: # pragma: no cover MIDDLEWARE.insert(1, "whitenoise.middleware.WhiteNoiseMiddleware") STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" # Sentry # https://sentry.io/for/django/ try: import sentry_sdk # noqa except ModuleNotFoundError: # pragma: no cover pass else: # pragma: no cover from sentry_sdk.integrations.django import DjangoIntegration # noqa sentry_sdk.init(integrations=[DjangoIntegration()], send_default_pii=True) # Django Storages # https://django-storages.readthedocs.io/en/stable/{% if cookiecutter.use_media == "Yes" %} # noqa try: import storages # noqa except ModuleNotFoundError: # pragma: no cover pass else: # pragma: no cover AWS_ACCESS_KEY_ID = values.Value() AWS_DEFAULT_ACL = values.Value("public-read") AWS_LOCATION = values.Value("") AWS_QUERYSTRING_AUTH = False AWS_S3_ENDPOINT_URL = values.Value() AWS_S3_FILE_OVERWRITE = values.BooleanValue(False) AWS_SECRET_ACCESS_KEY = values.Value() AWS_STORAGE_BUCKET_NAME = values.Value() @property def DEFAULT_FILE_STORAGE(self): """Return the Django file storage backend.""" if all( ( self.AWS_ACCESS_KEY_ID, self.AWS_S3_ENDPOINT_URL, self.AWS_SECRET_ACCESS_KEY, self.AWS_STORAGE_BUCKET_NAME, ) ): return "storages.backends.s3boto3.S3Boto3Storage" # pragma: no cover return "django.core.files.storage.FileSystemStorage" # noqa {% endif %}