當前位置: 首頁>>代碼示例>>Python>>正文


Python conf.settings方法代碼示例

本文整理匯總了Python中django.conf.settings方法的典型用法代碼示例。如果您正苦於以下問題:Python conf.settings方法的具體用法?Python conf.settings怎麽用?Python conf.settings使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.conf的用法示例。


在下文中一共展示了conf.settings方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: encode_jwt

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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") 
開發者ID:Humanitec,項目名稱:django-oauth-toolkit-jwt,代碼行數:19,代碼來源:utils.py

示例2: decode_jwt

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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 
開發者ID:Humanitec,項目名稱:django-oauth-toolkit-jwt,代碼行數:23,代碼來源:utils.py

示例3: _filter_checks_on_permission

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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 
開發者ID:mvantellingen,項目名稱:django-healthchecks,代碼行數:18,代碼來源:checker.py

示例4: setUp

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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') 
開發者ID:GamesDoneQuick,項目名稱:donation-tracker,代碼行數:19,代碼來源:test_speedrun.py

示例5: forwards_func

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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
            ) 
開發者ID:twschiller,項目名稱:open-synthesis,代碼行數:24,代碼來源:0036_defaultpermissions.py

示例6: private_profile

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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) 
開發者ID:twschiller,項目名稱:open-synthesis,代碼行數:24,代碼來源:profiles.py

示例7: clean

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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) 
開發者ID:twschiller,項目名稱:open-synthesis,代碼行數:27,代碼來源:models.py

示例8: handle

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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 
開發者ID:twschiller,項目名稱:open-synthesis,代碼行數:19,代碼來源:createadmin.py

示例9: handle

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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"') 
開發者ID:twschiller,項目名稱:open-synthesis,代碼行數:19,代碼來源:senddigest.py

示例10: test_email_weekly_command_digest_day

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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') 
開發者ID:twschiller,項目名稱:open-synthesis,代碼行數:20,代碼來源:test_digest.py

示例11: test_email_weekly_command_other_day

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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') 
開發者ID:twschiller,項目名稱:open-synthesis,代碼行數:23,代碼來源:test_digest.py

示例12: client

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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) 
開發者ID:openstack,項目名稱:freezer-web-ui,代碼行數:18,代碼來源:api.py

示例13: _get_service_url

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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 
開發者ID:openstack,項目名稱:freezer-web-ui,代碼行數:27,代碼來源:api.py

示例14: submit

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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) 
開發者ID:genialis,項目名稱:resolwe,代碼行數:23,代碼來源:celery.py

示例15: update_constants

# 需要導入模塊: from django import conf [as 別名]
# 或者: from django.conf import settings [as 別名]
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) 
開發者ID:genialis,項目名稱:resolwe,代碼行數:22,代碼來源:state.py


注:本文中的django.conf.settings方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。