本文整理汇总了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")
示例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
示例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
示例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')
示例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
)
示例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)
示例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)
示例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
示例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"')
示例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')
示例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')
示例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)
示例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
示例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)
示例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)