Python django.conf.settings() Examples
The following are 30
code examples of django.conf.settings().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.conf
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: utils.py From django-oauth-toolkit-jwt with MIT License | 7 votes |
def encode_jwt(payload, headers=None): """ :type payload: dict :type headers: dict, None :rtype: str """ # RS256 in default, because hardcoded legacy algorithm = getattr(settings, 'JWT_ENC_ALGORITHM', 'RS256') private_key_name = 'JWT_PRIVATE_KEY_{}'.format(payload['iss'].upper()) private_key = getattr(settings, private_key_name, None) if not private_key: raise ImproperlyConfigured('Missing setting {}'.format( private_key_name)) encoded = jwt.encode(payload, private_key, algorithm=algorithm, headers=headers) return encoded.decode("utf-8")
Example #2
Source File: test_digest.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def test_email_weekly_command_digest_day(self): """Test that admin can send digest on the weekly digest day.""" setattr(settings, 'DIGEST_WEEKLY_DAY', 0) previous = timezone.now() static = previous # find the next scheduled digest day while static.weekday() != 0: static += timezone.timedelta(days=1) with patch('openach.management.commands.senddigest.timezone.now') as timezone_mock: timezone_mock.return_value = static logger.debug('Shifted timezone.now() from weekday %s to %s', previous.weekday(), static.weekday()) create_board(board_title='New Board', days=-1) call_command('senddigest', 'weekly') self.assertEqual(len(mail.outbox), 1, 'No weekly digest email sent')
Example #3
Source File: profiles.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def private_profile(request): """Return a view of the private profile associated with the authenticated user and handle settings.""" user = request.user if request.method == 'POST': form = SettingsForm(request.POST, instance=user.settings) if form.is_valid(): form.save() messages.success(request, _('Updated account settings.')) else: form = SettingsForm(instance=user.settings) context = { 'user': user, 'boards_created': user_boards_created(user, viewing_user=user)[:5], 'boards_contributed': user_boards_contributed(user, viewing_user=user), 'board_voted': user_boards_evaluated(user, viewing_user=user), 'meta_description': _('Account profile for user {name}').format(name=user), 'notifications': request.user.notifications.unread(), 'settings_form': form, } return render(request, 'boards/profile.html', context)
Example #4
Source File: 0036_defaultpermissions.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def forwards_func(apps, schema_editor): """Create default permissions for each board, if they don't already have permissions.""" BoardPermissions = apps.get_model("openach", "BoardPermissions") Board = apps.get_model("openach", "Board") db_alias = schema_editor.connection.alias default_read = ( AuthLevels.registered.key if getattr(settings, 'ACCOUNT_REQUIRED', True) else AuthLevels.anyone.key ) for board in Board.objects.using(db_alias).all(): if not BoardPermissions.objects.filter(board=board).exists(): BoardPermissions.objects.create( board=board, read_board=default_read, read_comments=default_read, add_comments=AuthLevels.collaborators.key, add_elements=AuthLevels.collaborators.key, edit_elements=AuthLevels.collaborators.key )
Example #5
Source File: checker.py From django-healthchecks with MIT License | 6 votes |
def _filter_checks_on_permission(request, checks): permissions = getattr(settings, 'HEALTH_CHECKS_BASIC_AUTH', {}) if not permissions: return checks allowed = {} for name in checks.keys(): required_credentials = permissions.get(name, permissions.get('*')) if required_credentials: credentials = _get_basic_auth(request) if not credentials or credentials not in required_credentials: continue allowed[name] = checks[name] return allowed
Example #6
Source File: test_speedrun.py From donation-tracker with Apache License 2.0 | 6 votes |
def setUp(self): self.factory = RequestFactory() self.sessions = SessionMiddleware() self.messages = MessageMiddleware() self.event1 = models.Event.objects.create( datetime=today_noon, targetamount=5, timezone=pytz.timezone(getattr(settings, 'TIME_ZONE', 'America/Denver')), ) self.run1 = models.SpeedRun.objects.create( name='Test Run 1', run_time='0:45:00', setup_time='0:05:00', order=1 ) self.run2 = models.SpeedRun.objects.create( name='Test Run 2', run_time='0:15:00', setup_time='0:05:00', order=2 ) if not User.objects.filter(username='admin').exists(): User.objects.create_superuser('admin', 'nobody@example.com', 'password')
Example #7
Source File: forms.py From ideascube with GNU Affero General Public License v3.0 | 6 votes |
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name, field in self.fields.items(): if isinstance(field, forms.DateField): # Force date format on load, so date picker doesn't mess it up # because of i10n. field.widget = forms.DateInput(format='%Y-%m-%d') if name == 'extra': field.label = getattr( settings, 'USER_EXTRA_FIELD_LABEL', _('Additional data'))
Example #8
Source File: test_digest.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def test_email_weekly_command_other_day(self): """Test that admin cannot digest email not on weekly digest day unless forced.""" setattr(settings, 'DIGEST_WEEKLY_DAY', 0) previous = timezone.now() static = previous # make sure we're not on a scheduled digest day while static.weekday() == 0: static += timezone.timedelta(days=1) with patch('openach.management.commands.senddigest.timezone.now') as timezone_mock: timezone_mock.return_value = static logger.debug('Shifted timezone.now() from weekday %s to %s', previous.weekday(), static.weekday()) create_board(board_title='New Board', days=-1) call_command('senddigest', 'weekly') self.assertEqual(len(mail.outbox), 0, 'Weekly digest email sent on wrong day') call_command('senddigest', 'weekly', '--force') self.assertEqual(len(mail.outbox), 1, 'Weekly digest email not sent when forced')
Example #9
Source File: api.py From freezer-web-ui with Apache License 2.0 | 6 votes |
def client(request): """Return a freezer client object""" api_url = _get_service_url(request) # get keystone version to connect to credentials = { 'token': request.user.token.id, 'auth_url': getattr(settings, 'OPENSTACK_KEYSTONE_URL'), 'endpoint': api_url, 'project_id': request.user.project_id, } credentials['project_domain_name'] = \ request.user.domain_name or 'Default' return freezer_client.Client(**credentials)
Example #10
Source File: api.py From freezer-web-ui with Apache License 2.0 | 6 votes |
def _get_service_url(request): """Get freezer api url""" hardcoded_url = getattr(settings, 'FREEZER_API_URL', None) if hardcoded_url is not None: LOG.warning('Using hardcoded FREEZER_API_URL:{0}' .format(hardcoded_url)) return hardcoded_url e_type = getattr(settings, 'OPENSTACK_ENDPOINT_TYPE', '') endpoint_type_priority = [e_type, ['internal', 'internalURL'], ['public', 'publicURL']] try: catalog = (getattr(request.user, "service_catalog", [])) for c in catalog: if c['name'] == 'freezer': for endpoint_type in endpoint_type_priority: for e in c['endpoints']: if e['interface'] in endpoint_type: return e['url'] raise ValueError('Could no get FREEZER_API_URL from config' ' or Keystone') except Exception: LOG.warning('Could no get FREEZER_API_URL from config or Keystone') raise
Example #11
Source File: celery.py From resolwe with Apache License 2.0 | 6 votes |
def submit(self, data, runtime_dir, argv): """Run process. For details, see :meth:`~resolwe.flow.managers.workload_connectors.base.BaseConnector.submit`. """ queue = "ordinary" if data.process.scheduling_class == Process.SCHEDULING_CLASS_INTERACTIVE: queue = "hipri" logger.debug( __( "Connector '{}' running for Data with id {} ({}) in celery queue {}, EAGER is {}.", self.__class__.__module__, data.id, repr(argv), queue, getattr(settings, "CELERY_ALWAYS_EAGER", None), ) ) celery_run.apply_async((data.id, runtime_dir, argv), queue=queue)
Example #12
Source File: state.py From resolwe with Apache License 2.0 | 6 votes |
def update_constants(): """Recreate channel name constants with changed settings. This kludge is mostly needed due to the way Django settings are patched for testing and how modules need to be imported throughout the project. On import time, settings are not patched yet, but some of the code needs static values immediately. Updating functions such as this one are then needed to fix dummy values. """ global MANAGER_CONTROL_CHANNEL, MANAGER_EXECUTOR_CHANNELS global MANAGER_LISTENER_STATS, MANAGER_STATE_PREFIX redis_prefix = getattr(settings, "FLOW_MANAGER", {}).get("REDIS_PREFIX", "") MANAGER_CONTROL_CHANNEL = "{}.control".format(redis_prefix) MANAGER_EXECUTOR_CHANNELS = ManagerChannelPair( "{}.result_queue".format(redis_prefix), "{}.result_queue_response".format(redis_prefix), ) MANAGER_STATE_PREFIX = "{}.state".format(redis_prefix) MANAGER_LISTENER_STATS = "{}.listener_stats".format(redis_prefix)
Example #13
Source File: models.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def clean(self): """Validate the BoardPermissions model. Check that the read permission is valid with respect to the relative to the global ACCOUNT_REQUIRED setting. Check that the other permissions are valid relative to """ super(BoardPermissions, self).clean() errors = {} if getattr(settings, 'ACCOUNT_REQUIRED', True) and self.read_board == AuthLevels.collaborators.anyone.key: errors['read_board'] = _('Cannot set permission to public because site permits only registered users') if self.add_comments > self.read_comments: errors['add_comments'] = _('Cannot be more permissive than the "read comments" permission') if self.edit_elements > self.add_elements: errors['edit_elements'] = _('Cannot be more permissive than the "add elements" permission') if self.read_comments > self.read_board: errors['read_comments'] = _('Cannot be more permissive than the "read board" permission') if self.add_elements > self.read_board: errors['add_elements'] = _('Cannot be more permissive than the "read board" permission') if self.edit_board > self.edit_elements: errors['edit_board'] = _('Cannot be more permissive than the "edit elements" permission') if len(errors) > 0: raise ValidationError(errors)
Example #14
Source File: createadmin.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def handle(self, *args, **options): """Handle the command invocation.""" email = getattr(settings, 'ADMIN_EMAIL_ADDRESS', None) username = getattr(settings, 'ADMIN_USERNAME', None) password = getattr(settings, 'ADMIN_PASSWORD', None) if not email or not username or not password: raise CommandError('ADMIN_USERNAME, ADMIN_PASSWORD, and ADMIN_EMAIL_ADDRESS must be set') admin = User(username=username, email=email) admin.set_password(password) admin.is_superuser = True admin.is_staff = True admin.save() msg = 'Successfully configured admin %s (%s)' % (username, email) self.stdout.write(self.style.SUCCESS(msg)) # pylint: disable=no-member
Example #15
Source File: __init__.py From resolwe with Apache License 2.0 | 6 votes |
def get_apps_tools(): """Get applications' tools and their paths. Return a dict with application names as keys and paths to tools' directories as values. Applications without tools are omitted. """ tools_paths = {} for app_config in apps.get_app_configs(): proc_path = os.path.join(app_config.path, "tools") if os.path.isdir(proc_path): tools_paths[app_config.name] = proc_path custom_tools_paths = getattr(settings, "RESOLWE_CUSTOM_TOOLS_PATHS", []) if not isinstance(custom_tools_paths, list): raise KeyError("`RESOLWE_CUSTOM_TOOLS_PATHS` setting must be a list.") for seq, custom_path in enumerate(custom_tools_paths): custom_key = "_custom_{}".format(seq) tools_paths[custom_key] = custom_path return tools_paths
Example #16
Source File: senddigest.py From open-synthesis with GNU General Public License v3.0 | 6 votes |
def handle(self, *args, **options): """Handle the command invocation.""" if options['frequency'] == 'daily': self.report(send_digest_emails(DigestFrequency.daily)) elif options['frequency'] == 'weekly': digest_day = getattr(settings, 'DIGEST_WEEKLY_DAY') current_day = timezone.now().weekday() if current_day == digest_day or options['force']: if current_day != digest_day and options['force']: msg = 'Forcing weekly digest to be sent (scheduled=%s, current=%s)' % (digest_day, current_day) self.stdout.write(self.style.WARNING(msg)) # pylint: disable=no-member self.report(send_digest_emails(DigestFrequency.weekly)) else: msg = 'Skipping weekly digest until day %s (current=%s)' % (digest_day, current_day) self.stdout.write(self.style.WARNING(msg)) # pylint: disable=no-member else: raise CommandError('Expected frequency "daily" or "weekly"')
Example #17
Source File: create_instance.py From trove-dashboard with Apache License 2.0 | 5 votes |
def __init__(self, request=None, context_seed=None, entry_point=None, *args, **kwargs): super(LaunchInstance, self).__init__(request, context_seed, entry_point, *args, **kwargs) self.attrs['autocomplete'] = ( settings.HORIZON_CONFIG.get('password_autocomplete'))
Example #18
Source File: signals.py From resolwe with Apache License 2.0 | 5 votes |
def commit_signal(data_id): """Nudge manager at the end of every Data object save event.""" if not getattr(settings, "FLOW_MANAGER_DISABLE_AUTO_CALLS", False): immediate = getattr(settings, "FLOW_MANAGER_SYNC_AUTO_CALLS", False) async_to_sync(manager.communicate)( data_id=data_id, save_settings=False, run_sync=immediate )
Example #19
Source File: mongoutils.py From drf-mongo-filters with GNU General Public License v2.0 | 5 votes |
def _iter_test_databases(cls): for alias, params in settings.MONGO_DATABASES.items(): test_params = dict(params) test_params['name'] = 'test_' + params['name'] yield (alias, test_params)
Example #20
Source File: runtests.py From django-mptt-comments with MIT License | 5 votes |
def run_tests(*test_args): if not test_args: test_args = ['tests'] os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(test_args) sys.exit(bool(failures))
Example #21
Source File: mongoutils.py From drf-mongo-filters with GNU General Public License v2.0 | 5 votes |
def mongo_connect(): for alias, params in settings.MONGO_DATABASES.items(): p = dict(params) connect(p.pop('name'), alias=alias, **p)
Example #22
Source File: context_processors.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def invite(dummy_request): """Return a template context with the site's invitation configuration.""" return { 'invite_request_url': getattr(settings, 'INVITE_REQUEST_URL', None), }
Example #23
Source File: test_site.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def test_privacy_policy(self): """Test that the privacy policy panel is displayed if a URL is set.""" url = 'https://github.com/twschiller/open-synthesis/blob/master/PRIVACY.md' setattr(settings, 'PRIVACY_URL', url) response = self.client.get(reverse('openach:about')) self.assertContains(response, 'Privacy Policy', status_code=200)
Example #24
Source File: test_site.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def test_no_privacy_policy(self): """Test that the privacy policy panel is not displayed if a URL is not set.""" setattr(settings, 'PRIVACY_URL', None) response = self.client.get(reverse('openach:about')) self.assertNotContains(response, 'Privacy Policy', status_code=200)
Example #25
Source File: test_site.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def test_can_render_about_page_with_donate(self): """Test that any user can view an about page with a donate link if a Bitcoin address is set.""" setattr(settings, 'DONATE_BITCOIN_ADDRESS', self.address) response = self.client.get(reverse('openach:about')) self.assertIsNotNone(response) self.assertContains(response, 'Donate', status_code=200) self.assertContains(response, self.address, status_code=200)
Example #26
Source File: test_site.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def test_can_generate_bitcoin_qrcode(self): """Test SVG QR Code generation.""" setattr(settings, 'DONATE_BITCOIN_ADDRESS', self.address) response = self.client.get(reverse('openach:bitcoin_donate')) self.assertEqual(response.status_code, 200) # should probably also test for content type image/svg+xml here
Example #27
Source File: test_site.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def test_can_render_about_page(self): """Test that any user can view the about page.""" setattr(settings, 'DONATE_BITCOIN_ADDRESS', None) response = self.client.get(reverse('openach:about')) self.assertIsNotNone(response) self.assertNotContains(response, 'Donate')
Example #28
Source File: test_site.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def test_show_banner(self): """Test that the banner message shows on all pages.""" msg = 'Test banner message' setattr(settings, 'BANNER_MESSAGE', msg) for page in ['index', 'boards', 'about']: response = self.client.get(reverse('openach:{}'.format(page))) self.assertContains(response, msg, status_code=200)
Example #29
Source File: test_admin.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def test_settings_created(self): """Test that a settings object is created when the user is created.""" self.client.post('/accounts/signup/', data=self.valid_data) user = User.objects.filter(username=self.username).first() self.assertIsNotNone(user.settings, 'User settings object not created')
Example #30
Source File: test_digest.py From open-synthesis with GNU General Public License v3.0 | 5 votes |
def setUp(self): super().setUp() self.daily = self.user self.weekly = self.other def setup_user(user, freq): user.date_joined = timezone.now() + datetime.timedelta(days=-2) user.save() user.settings.digest_frequency = freq.key user.settings.save() setup_user(self.daily, DigestFrequency.daily) setup_user(self.weekly, DigestFrequency.weekly)