"""
Settings and configuration for Django.

Read values from the module specified by the DJANGO_SETTINGS_MODULE 
environment
variable, and then from django.conf.global_settings; see the 
global_settings.py
for a list of all possible variables.
"""

import importlib
import os
import time
import traceback
import warnings
from pathlib import Path

import django
from django.conf import global_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.functional import LazyObject, empty

ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"

PASSWORD_RESET_TIMEOUT_DAYS_DEPRECATED_MSG = (
'The PASSWORD_RESET_TIMEOUT_DAYS setting is deprecated. Use '
'PASSWORD_RESET_TIMEOUT instead.'
)

DEFAULT_HASHING_ALGORITHM_DEPRECATED_MSG = (
'The DEFAULT_HASHING_ALGORITHM transitional setting is deprecated. '
'Support for it and tokens, cookies, sessions, and signatures that use '
'SHA-1 hashing algorithm will be removed in Django 4.0.'
)


class SettingsReference(str):
"""
String subclass which references a current settings value. It's treated as
the value in memory but serializes to a settings.NAME attribute reference.
"""
def __new__(self, value, setting_name):
return str.__new__(self, value)

def __init__(self, value, setting_name):
self.setting_name = setting_name


class LazySettings(LazyObject):
"""
A lazy proxy for either global Django settings or a custom settings object.
The user can manually configure settings prior to using them. Otherwise,
Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
"""
def _setup(self, name=None):
"""
Load the settings module pointed to by the environment variable. This
is used the first time settings are needed, if the user hasn't
configured settings manually.
"""
settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
if not settings_module:
desc = ("setting %s" % name) if name else "settings"
raise ImproperlyConfigured(
"Requested %s, but settings are not configured. "
"You must either define the environment variable %s "
"or call settings.configure() before accessing settings."
%(desc, ENVIRONMENT_VARIABLE_django)

self._wrapped = Settings(settings_module)
def __repr__(self):
# Hardcode the class name as otherwise it yields 'Settings'.
if self._wrapped is empty:
return '<LazySettings [Unevaluated]>'
return '<LazySettings "%(settings_module)s">' %{
'settings_module': self._wrapped.SETTINGS_MODULE
}
def __getattr__(self, name):
"""Return the value of a setting and cache it in self.__dict__."""
if self._wrapped is empty:
self._setup(name)
val = getattr(self._wrapped, name)
self.__dict__[name] = val
returnvalue
def __setattr__(self, name, value):
"""
Set the value of setting. Clear all cached values if _wrapped changes
(@override_settings does this) or clear single values when set.
"""
if name == '_wrapped':
self.__dict__.clear()
else:
self.__dict__.pop(name, None)
super().__setattr__ (name, value)


def __delattr__(self, name):
"""Delete a setting and clear it from cache if needed."""
super().__delattr__(name)

self.__dict__.pop(name, None)

def configure(self, default_settings=global_settings, **options):
"""
Called to manually configure the settings. The 'default_settings'
parameter sets where to retrieve any unspecified values from (its
argument must support attribute access (__getattr__)).
"""
if self._wrapped is not empty:
raise RuntimeError('Settings already configured.')
holder = UserSettingsHolder(default_settings)
for name, value in options.items():
if not name.isupper():
raise TypeError\
('Setting %r must be uppercase.' % name)
setattr(holder, name, value)
self._wrapped = holder

@staticmethod
def _add_script_prefix(value):
"""
Add SCRIPT_NAME prefix to relative paths.

Useful when the app is being served at a subpath and manually prefixing
subpath to STATIC_URL and MEDIA_URL in settings is inconvenient.
"""
# Don't apply prefix to absolute paths and URLs.
if value.startswith(('http://', 'https://', '/')):
return value
from django.urls import get_script_prefix
return '%s%s' % (get_script_prefix(), value)

@property
def configured(self):
"""Return True if the settings have already been configured."""
return self._wrapped is not empty

@property
def PASSWORD_RESET_TIMEOUT_DAYS(self):
stack = traceback.extract_stack()
# Show a warning if the setting is used outside of Django.
# Stack index: -1 this line, -2 the caller.
filename, _, _, _ = stack[-2]
if not filename.startswith(os.path.dirname(django.__file__)):
warnings.warn(
PASSWORD_RESET_TIMEOUT_DAYS_DEPRECATED_MSG,
RemovedInDjango40Warning,
stacklevel=2,
)
return self.__getattr__('PASSWORD_RESET_TIMEOUT_DAYS')

@property
def static_url (self):
return self._add_script_prefix(self.__getattr__('STATIC_URL'))

@property
def media_url (self):
return self._add_script_prefix\
(self.__getattr__('MEDIA_URL'))

class Settings:
def __init__(self, settings_module):
# update this dict from global settings (but only for ALL_CAPS settings)
for setting in dir(global_settings):
if setting.isupper():
setattr(self, setting, getattr(global_settings, setting))

# store the settings module in case someone later cares
self.SETTINGS_MODULE = settings_module

mod = importlib.import_module(self.SETTINGS_MODULE)

tuple_settings = (
"INSTALLED_APPS",
"TEMPLATE_DIRS",
"LOCALE_PATHS",
)
self._explicit_settings = set()
for setting in dir(mod):
if setting.isupper():
setting_value = getattr(mod, setting)

if (setting in tuple_settings and
not isinstance(setting_value, (list, tuple))):
raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % 
setting)
setattr(self, setting, setting_value)
self._explicit_settings.add(setting)

if not self.SECRET_KEY:
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")

if self.is_overridden('PASSWORD_RESET_TIMEOUT_DAYS'):
if self.is_overridden('PASSWORD_RESET_TIMEOUT'):
raise ImproperlyConfigured(
'PASSWORD_RESET_TIMEOUT_DAYS/PASSWORD_RESET_TIMEOUT are '
'mutually exclusive.'
)
setattr(self, 'PASSWORD_RESET_TIMEOUT', self.PASSWORD_RESET_TIMEOUT_DAYS * 
60 * 60 * 24)
warnings.warn(PASSWORD_RESET_TIMEOUT_DAYS_DEPRECATED_MSG, 
RemovedInDjango40Warning)

if self.is_overridden('DEFAULT_HASHING_ALGORITHM'):
warnings.warn(DEFAULT_HASHING_ALGORITHM_DEPRECATED_MSG, 
RemovedInDjango40Warning)

if hasattr(time, 'tzset') and self.TIME_ZONE:
# When we can, attempt to validate the timezone. If we can't find
# this file, no check happens and it's harmless.
zoneinfo_root = Path('/usr/share/zoneinfo')
zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split('/'))
if zoneinfo_root.exists() and not zone_info_file.exists():
raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
# Move the time zone info into os.environ. See ticket #2315 for why
# we don't do this unconditionally (breaks Windows).
os.environ['TZ'] = self.TIME_ZONE
time.tzset()

def is_overridden(self, setting):
return setting in self._explicit_settings

def __repr__(self):
return '<%(cls)s "%(settings_module)s">' % {
'cls': self.__class__.__name__,
'settings_module': self.SETTINGS_MODULE,
}


class UserSettingsHolder:
"""Holder for user configured settings."""
# SETTINGS_MODULE doesn't make much sense in the manually configured
# (standalone) case.
SETTINGS_MODULE = None

def __init__(self, default_settings):
"""
Requests for configuration variables not in this class are satisfied
from the module specified in default_settings (if possible).
"""
self.__dict__['_deleted'] = set()
self.default_settings = default_settings

def __getattr__(self, name):
if not name.isupper() or name in self._deleted:
raise AttributeError
return getattr(self.default_settings, name)

def __setattr__(self, name, value):
self._deleted.discard(name)
if name == 'PASSWORD_RESET_TIMEOUT_DAYS':
setattr(self, 'PASSWORD_RESET_TIMEOUT', value * 60 * 60 * 24)
warnings.warn(PASSWORD_RESET_TIMEOUT_DAYS_DEPRECATED_MSG, 
RemovedInDjango40Warning)
if name == 'DEFAULT_HASHING_ALGORITHM':
warnings.warn(DEFAULT_HASHING_ALGORITHM_DEPRECATED_MSG, 
RemovedInDjango40Warning)
super().__setattr__(name, value)

def __delattr__(self, name):
self._deleted.add(name)
if hasattr(self, name):
super().__delattr__(name)

def __dir__(self):
return sorted(
s for s in [*self.__dict__, *dir(self.default_settings)]
if s not in self._deleted
)

def is_overridden(self, setting):
deleted = (setting in self._deleted)
set_locally = (setting in self.__dict__)
set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: 
False)(setting)
return deleted or set_locally or set_on_default

def __repr__(self):
return '<%(cls)s>' % {
'cls': self.__class__.__name__,
}


settings = LazySettings()

Here is the Code now facing many issues 
I cloned this project from Git and want to run it.
On Tuesday, August 10, 2021 at 5:16:02 PM UTC+5 bscho...@schollnick.net 
wrote:

> Thank you very much for your kind words. I am facing this errors :
>
> > ',' or ')' expected
> > Unexpected indent
> > Statement expected, found Py:DEDENT
>
> for the last 2,3 days. Kindly help me out.
>
>
> You need to share your code.
>
> Pycharm should be dropping you exactly on the line that is resulting in 
> this error.
>
> Without it, we are guessing.
>
> - Benjamin
>
> On Aug 10, 2021, at 8:03 AM, Rana Zain <iamrana...@gmail.com> wrote:
>
>
>
> On Monday, August 9, 2021 at 5:43:06 PM UTC+5 Kasper Laudrup wrote:
>
>> On 09/08/2021 14.24, Rana Zain wrote: 
>> > 
>> > Thank you so much everyone. It's work. 
>> > 
>> > I have another problem. I am facing this issue in Pycharm .  I tried 
>> > spaces & tabs. 
>> > 
>> > Error is :"Unindent does not match any outer indentation level"" 
>>
>> Python uses indentation for scoping unlike most other programming 
>> languages. That is very important and basic knowledge and doesn't have 
>> anything to do with Pycharm. 
>>
>> I would suggest you start by finding a tutorial, book or similar on 
>> Python for absolute beginners and then take it slowly from there. 
>>
>> A quick search showed this: 
>>
>> https://python.land/python-tutorial 
>>
>> But others might have some better suggestions. 
>>
>> Good luck on learning Python. It's a nice and very forgiving language so 
>> you'll make progress very quickly, but like with most other things, you 
>> do need some amount of patience to get started. 
>>
>> Kind regards, 
>>
>> Kasper Laudrup 
>>
>>
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-users...@googlegroups.com.
>
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/94bde1d2-ba4e-480e-8ef6-f71f1626a88en%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/django-users/94bde1d2-ba4e-480e-8ef6-f71f1626a88en%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d441ebf4-e873-404c-9416-b6acb24c1e3an%40googlegroups.com.

Reply via email to