Python django.conf.settings() Examples

The following are 30 code examples for showing how to use django.conf.settings(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf , or try the search function .

Example 1
Project: django-oauth-toolkit-jwt   Author: Humanitec   File: utils.py    License: MIT License 6 votes vote down vote up
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
Project: django-oauth-toolkit-jwt   Author: Humanitec   File: utils.py    License: MIT License 6 votes vote down vote up
def decode_jwt(jwt_value):
    """
    :type jwt_value: str
    """
    try:
        headers_enc, payload_enc, verify_signature = jwt_value.split(".")
    except ValueError:
        raise jwt.InvalidTokenError()

    payload_enc += '=' * (-len(payload_enc) % 4)  # add padding
    payload = json.loads(base64.b64decode(payload_enc).decode("utf-8"))

    algorithms = getattr(settings, 'JWT_JWS_ALGORITHMS', ['HS256', 'RS256'])
    public_key_name = 'JWT_PUBLIC_KEY_{}'.format(payload['iss'].upper())
    public_key = getattr(settings, public_key_name, None)
    if not public_key:
        raise ImproperlyConfigured('Missing setting {}'.format(
                                   public_key_name))

    decoded = jwt.decode(jwt_value, public_key, algorithms=algorithms)
    return decoded 
Example 3
Project: django-healthchecks   Author: mvantellingen   File: checker.py    License: MIT License 6 votes vote down vote up
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 4
Project: donation-tracker   Author: GamesDoneQuick   File: test_speedrun.py    License: Apache License 2.0 6 votes vote down vote up
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 5
Project: open-synthesis   Author: twschiller   File: 0036_defaultpermissions.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 6
Project: open-synthesis   Author: twschiller   File: profiles.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 7
Project: open-synthesis   Author: twschiller   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 8
Project: open-synthesis   Author: twschiller   File: createadmin.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 9
Project: open-synthesis   Author: twschiller   File: senddigest.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 10
Project: open-synthesis   Author: twschiller   File: test_digest.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 11
Project: open-synthesis   Author: twschiller   File: test_digest.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 12
Project: ideascube   Author: ideascube   File: forms.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 13
Project: freezer-web-ui   Author: openstack   File: api.py    License: Apache License 2.0 6 votes vote down vote up
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 14
Project: freezer-web-ui   Author: openstack   File: api.py    License: Apache License 2.0 6 votes vote down vote up
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 15
Project: resolwe   Author: genialis   File: celery.py    License: Apache License 2.0 6 votes vote down vote up
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 16
Project: resolwe   Author: genialis   File: state.py    License: Apache License 2.0 6 votes vote down vote up
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 17
Project: resolwe   Author: genialis   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
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 18
Project: django-classified   Author: slyapustin   File: context_processors.py    License: MIT License 5 votes vote down vote up
def common_values(request):
    return {
        'DCF': dcf_settings,
        'FACEBOOK_APP_ID': getattr(settings, 'FACEBOOK_APP_ID', ''),
        'GOOGLE_ANALYTICS_PROPERTY_ID': getattr(settings, 'GOOGLE_ANALYTICS_PROPERTY_ID', ''),
        'GOOGLE_SITE_VERIFICATION_ID': getattr(settings, 'GOOGLE_SITE_VERIFICATION_ID', ''),
        'area_list': Area.objects.all(),
        'area': Area.get_for_request(request)
    } 
Example 19
Project: django-json-widget   Author: jmrivas86   File: runtests.py    License: MIT License 5 votes vote down vote up
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 20
Project: django-places   Author: oscarmcm   File: admin.py    License: MIT License 5 votes vote down vote up
def position_map(self, instance):
        if instance.location is not None:
            return '<img src="http://maps.googleapis.com/maps/api/staticmap?center=%(latitude)s,%(longitude)s&zoom=%(zoom)s&size=%(width)sx%(height)s&maptype=roadmap&markers=%(latitude)s,%(longitude)s&sensor=false&visual_refresh=true&scale=%(scale)s&key=%(key)s" width="%(width)s" height="%(height)s">' % {
                'latitude': instance.location.latitude,
                'longitude': instance.location.longitude,
                'key': getattr(settings, 'PLACES_MAPS_API_KEY'),
                'zoom': 15,
                'width': 100,
                'height': 100,
                'scale': 2
            } 
Example 21
Project: django-places   Author: oscarmcm   File: conf.py    License: MIT License 5 votes vote down vote up
def __init__(self, django_settings):
        self.django_settings = django_settings

        for setting in self.required_settings:
            prefixed_name = '%s_%s' % (self.prefix, setting)
            if not hasattr(self.django_settings, prefixed_name):
                raise ImproperlyConfigured(
                    "The '%s' setting is required." % prefixed_name
                ) 
Example 22
Project: django-places   Author: oscarmcm   File: conf.py    License: MIT License 5 votes vote down vote up
def __getattr__(self, name):
        prefixed_name = '%s_%s' % (self.prefix, name)
        if hasattr(django_settings, prefixed_name):
            return getattr(django_settings, prefixed_name)
        if name in self.defaults:
            return self.defaults[name]
        raise AttributeError(
            "'AppSettings' object does not have a '%s' attribute" % name
        ) 
Example 23
Project: puput   Author: APSL   File: routes.py    License: MIT License 5 votes vote down vote up
def entries_by_author(self, request, author, *args, **kwargs):
        self.search_type = _('author')
        self.search_term = author
        field_name = 'owner__%s' % getattr(settings, 'PUPUT_USERNAME_FIELD', 'username')
        self.entries = self.get_entries().filter(**{field_name: author})
        return Page.serve(self, request, *args, **kwargs) 
Example 24
Project: puput   Author: APSL   File: utils.py    License: MIT License 5 votes vote down vote up
def get_image_model_path():
    from django.conf import settings
    return getattr(settings, 'WAGTAILIMAGES_IMAGE_MODEL', 'wagtailimages.Image') 
Example 25
Project: puput   Author: APSL   File: __init__.py    License: MIT License 5 votes vote down vote up
def _setup(self):
        self._wrapped = Settings(app_settings, django_settings) 
Example 26
def init_config(self, request, app_list):
        self.request = request
        self.app_list = app_list

        self.config = getattr(settings, 'ADMIN_REORDER', None)
        if not self.config:
            # ADMIN_REORDER settings is not defined.
            raise ImproperlyConfigured('ADMIN_REORDER config is not defined.')

        if not isinstance(self.config, (tuple, list)):
            raise ImproperlyConfigured(
                'ADMIN_REORDER config parameter must be tuple or list. '
                'Got {config}'.format(config=self.config))

        admin_index = admin.site.index(request)
        try:
            # try to get all installed models
            app_list = admin_index.context_data['app_list']
        except KeyError:
            # use app_list from context if this fails
            pass

        # Flatten all models from apps
        self.models_list = []
        for app in app_list:
            for model in app['models']:
                model['model_name'] = self.get_model_name(
                    app['app_label'], model['object_name'])
                self.models_list.append(model) 
Example 27
Project: django-accounting   Author: dulacp   File: context_processors.py    License: MIT License 5 votes vote down vote up
def metadata(request):
    """
    Add some generally useful metadata to the template context
    """
    return {
        'display_version': getattr(settings,
            'DISPLAY_VERSION', 'N/A'),
        'display_short_version': getattr(settings,
            'DISPLAY_SHORT_VERSION', 'N/A'),
        'version': getattr(settings,
            'VERSION', 'N/A'),
    } 
Example 28
Project: django-fontawesome   Author: redouane   File: __init__.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def as_html(self):
        if not self.id:
            return ''

        prefix = getattr(settings, 'FONTAWESOME_PREFIX', 'fa')
        return format_html('<i class="{0} {0}-{1}"></i>', prefix, self.id) 
Example 29
Project: django-fontawesome   Author: redouane   File: fontawesome.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fontawesome_icon(icon, title='', large=False, fixed=False, spin=False, li=False,
    rotate=False, border=False, color=False):

    return mark_safe('<i title="{title}" class="{prefix} {prefix}-{icon}{large}{fixed}{spin}{li}{rotate}{border}" {color}></i>'.format(
        title=title,
        prefix=getattr(settings, 'FONTAWESOME_PREFIX', 'fa'),
        icon=icon,
        large=' fa-lg' if large is True else '',
        fixed=' fa-fw' if fixed else '',
        spin=' fa-spin' if spin else '',
        li=' fa-li' if li else '',
        rotate=' fa-rotate-%s' % str(rotate) if rotate else '',
        border=' fa-border' if border else '',
        color='style="color:%s;"' % color if color else ''
    )) 
Example 30
Project: django-fontawesome   Author: redouane   File: fontawesome.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def fontawesome_stylesheet():
    href = getattr(settings, 'FONTAWESOME_CSS_URL', static('fontawesome/css/font-awesome.min.css'))
    link = format_html('<link href="{0}" rel="stylesheet" media="all">', href)
    return link