Exemple #1
0
    def add_map_feature_types(self, types):
        """
        add_map_feature_types(self, types)

        types is a list of map feature class names.

        Add these types to the instance config,
        save the instance!!!,
        and create udf rows for udfs that have settings defaults,
        if they don't already exist.
        """
        from treemap.models import MapFeature  # prevent circular import
        from treemap.audit import add_default_permissions

        classes = [MapFeature.get_subclass(type) for type in types]

        dups = set(types) & set(self.map_feature_types)
        if len(dups) > 0:
            raise ValidationError('Map feature types already added: %s' % dups)

        self._map_feature_types = list(self.map_feature_types) + list(types)
        self.save()

        for type, clz in zip(types, classes):
            settings = (getattr(clz, 'udf_settings', {}))
            for udfc_name, udfc_settings in settings.items():
                if udfc_settings.get('defaults'):
                    get_or_create_udf(self, type, udfc_name)

        add_default_permissions(self, models=classes)
Exemple #2
0
    def __init__(self, acl=None, bucket=None, **settings):
        # check if some of the settings we've provided as class attributes
        # need to be overwritten with values passed in here
        for name, value in settings.items():
            if name in self.__dict__:
                setattr(self, name, value)

        # For backward-compatibility of old differing parameter names
        if acl is not None:
            self.default_acl = acl
        if bucket is not None:
            self.bucket_name = bucket

        self.location = (self.location or '').lstrip('/')
        # Backward-compatibility: given the anteriority of the SECURE_URL setting
        # we fall back to https if specified in order to avoid the construction
        # of unsecure urls.
        if self.secure_urls:
            self.url_protocol = 'https:'

        self._entries = {}
        self._bucket = None
        self._connection = None

        if not self.access_key and not self.secret_key:
            self.access_key, self.secret_key = self._get_access_keys()
    def __init__(self, settings, *args, **kwargs):
        """
        Initialization method.

        Args:
            settings (dict): subsettings.
            name (str): the name of the setting.
            default (dict): default value given to the setting.
            required (bool): whether the setting is required or not.
            prefix (str):
                the setting's prefix (overrides ``AppSettings.Meta`` prefix).
            call_default (bool): whether to call the default (if callable).
            transform_default (bool): whether to transform the default value.
            validators (list of callables): list of additional validators to use.
            key_type: the type of the dict keys.
            value_type (type): the type of dict values.
            min_length (int): minimum length of the iterable (included).
            max_length (int): maximum length of the iterable (included).
            empty (bool): whether empty iterable is allowed. Deprecated in favor of min_length.
        """
        super().__init__(*args, **kwargs)
        for subname, subsetting in settings.items():
            if subsetting.name == "":
                subsetting.name = subname
            subsetting.parent_setting = self
        self.settings = settings
def custom_settings(context):
    from custom_settings.models import Setting
    settings = {
        'headers_excursions': Setting.objects.get_value('headers_excursions'),
        'headers_travel': Setting.objects.get_value('headers_travel'),
    }

    out = {}

    for key, value in settings.items():
        items = value.split('/')
        while len(items) < 5:
            items.append('')

        out[key] = {
            'people': items[0],
            'default_price': items[1],
            'price_line': {
                0: items[4],
                1: items[3],
                2: items[2],
            }
        }

    out['CUSTOMS'] = out
    return out
    def __init__(self, **settings):
        # check if some of the settings provided as class attributes
        # should be overwritten
        for name, value in settings.items():
            if hasattr(self, name):
                setattr(self, name, value)

        validate_settings(self)

        self.last_headers_name = None
        self.last_headers_value = None

        self.os_options = {
            'tenant_id': self.tenant_id,
            'tenant_name': self.tenant_name,
            'user_domain_id': self.user_domain_id,
            'user_domain_name': self.user_domain_name,
            'project_domain_id': self.project_domain_id,
            'project_domain_name': self.project_domain_name,
            'region_name': self.region_name,
        }
        self.os_options.update(self.os_extra_options)

        if not self.lazy_connect:
            self.swift_conn
Exemple #6
0
    def add_map_feature_types(self, types):
        """
        add_map_feature_types(self, types)

        types is a list of map feature class names.

        Add these types to the instance config,
        save the instance!!!,
        and create udf rows for udfs that have settings defaults,
        if they don't already exist.
        """
        from treemap.models import MapFeature  # prevent circular import
        from treemap.audit import add_default_permissions

        classes = [MapFeature.get_subclass(type) for type in types]

        dups = set(types) & set(self.map_feature_types)
        if len(dups) > 0:
            raise ValidationError('Map feature types already added: %s' % dups)

        self._map_feature_types = list(self.map_feature_types) + list(types)
        self.save()

        for type, clz in zip(types, classes):
            settings = (getattr(clz, 'udf_settings', {}))
            for udfc_name, udfc_settings in settings.items():
                if udfc_settings.get('defaults'):
                    get_or_create_udf(self, type, udfc_name)

        add_default_permissions(self, models=classes)
Exemple #7
0
 def get_settings(self):
     settings = {
         "django.use_l10n": self.use_l10n,
         "channels.core.auth": self.auth_settings,
         "channels.core.reconnection_policy": self.reconnection_policy,
         "channels.core.socket_address": self.socket_address}
     return {k: v for k, v in settings.items() if v is not None}
Exemple #8
0
 def update_field(settings):
     # Identifier is lower-cased above to match the calling convention
     # of update endpoints, so we shouldn't overwrite it :(
     field.update({
         k: v
         for k, v in settings.items()
         if v is not None and k != 'identifier'
     })
Exemple #9
0
    def __init__(self, **settings):
        # check if some of the settings we've provided as class attributes
        # need to be overwritten with values passed in here
        for name, value in settings.items():
            if hasattr(self, name):
                setattr(self, name, value)

        self._bucket = None
        self._client = None
Exemple #10
0
    def __init__(self, **settings):
        # check if some of the settings we've provided as class attributes
        # need to be overwritten with values passed in here
        for name, value in settings.items():
            if hasattr(self, name):
                setattr(self, name, value)

        self._bucket = None
        self._client = None
Exemple #11
0
    def __init__(self, **settings):
        # check if some of the settings provided as class attributes
        # should be overwritten
        for name, value in settings.items():
            if hasattr(self, name):
                setattr(self, name, value)

        self.last_headers_name = None
        self.last_headers_value = None

        # Get authentication token
        self.storage_url, self.token = swiftclient.get_auth(
            self.api_auth_url,
            self.api_username,
            self.api_key,
            auth_version=self.auth_version,
            os_options={"tenant_name": self.tenant_name},
        )
        self.http_conn = swiftclient.http_connection(self.storage_url)

        # Check container
        try:
            swiftclient.head_container(self.storage_url,
                                       self.token,
                                       self.container_name,
                                       http_conn=self.http_conn)
        except swiftclient.ClientException:
            if self.auto_create_container:
                swiftclient.put_container(self.storage_url,
                                          self.token,
                                          self.container_name,
                                          http_conn=self.http_conn)
            else:
                raise ImproperlyConfigured("Container %s does not exist." %
                                           self.container_name)

        if self.auto_base_url:
            # Derive a base URL based on the authentication information from
            # the server, optionally overriding the protocol, host/port and
            # potentially adding a path fragment before the auth information.
            self.base_url = self.storage_url + '/'
            if self.override_base_url is not None:
                # override the protocol and host, append any path fragments
                split_derived = urlparse.urlsplit(self.base_url)
                split_override = urlparse.urlsplit(self.override_base_url)
                split_result = [''] * 5
                split_result[0:2] = split_override[0:2]
                split_result[2] = (split_override[2] +
                                   split_derived[2]).replace('//', '/')
                self.base_url = urlparse.urlunsplit(split_result)

            self.base_url = urlparse.urljoin(self.base_url,
                                             self.container_name)
            self.base_url += '/'
        else:
            self.base_url = self.override_base_url
def get_parsed_client_urls(client: Client) -> dict:
    """
    Get MB_URLS with inserted the client URL
    """
    settings = dict(mb_settings(client))
    url = client.url
    for key, value in settings.items():
        if isinstance(value, str) and '{}' in value:
            settings[key] = value.format(url) if url else None

    return settings
    def __init__(self, **settings):
        # check if some of the settings provided as class attributes
        # should be overwritten
        for name, value in settings.items():
            if hasattr(self, name):
                setattr(self, name, value)

        self.last_headers_name = None
        self.last_headers_value = None

        # Get authentication token
        self.storage_url, self.token = swiftclient.get_auth(
            self.api_auth_url,
            self.api_username,
            self.api_key,
            auth_version=self.auth_version,
            os_options={"tenant_name": self.tenant_name},
        )
        self.http_conn = swiftclient.http_connection(self.storage_url)

        # Check container
        try:
            swiftclient.head_container(self.storage_url, self.token,
                                       self.container_name,
                                       http_conn=self.http_conn)
        except swiftclient.ClientException:
            if self.auto_create_container:
                swiftclient.put_container(self.storage_url, self.token,
                                          self.container_name,
                                          http_conn=self.http_conn)
            else:
                raise ImproperlyConfigured(
                    "Container %s does not exist." % self.container_name)

        if self.auto_base_url:
            # Derive a base URL based on the authentication information from
            # the server, optionally overriding the protocol, host/port and
            # potentially adding a path fragment before the auth information.
            self.base_url = self.storage_url + '/'
            if self.override_base_url is not None:
                # override the protocol and host, append any path fragments
                split_derived = urlparse.urlsplit(self.base_url)
                split_override = urlparse.urlsplit(self.override_base_url)
                split_result = [''] * 5
                split_result[0:2] = split_override[0:2]
                split_result[2] = (split_override[2] +
                                   split_derived[2]).replace('//', '/')
                self.base_url = urlparse.urlunsplit(split_result)

            self.base_url = urlparse.urljoin(self.base_url,
                                             self.container_name)
            self.base_url += '/'
        else:
            self.base_url = self.override_base_url
Exemple #14
0
 def _build_key(cls, urls, timeout, **settings):
     # Order the settings by key and then turn it into a string with
     # repr. There are a lot of edge cases here, but the worst that
     # happens is that the key is different and so you get a new
     # Elasticsearch. We'll probably have to tweak this.
     settings = sorted(settings.items(), key=lambda item: item[0])
     settings = repr([(k, v) for k, v in settings])
     # elasticsearch allows URLs to be a string, so we make sure to
     # account for that when converting whatever it is into a tuple.
     if isinstance(urls, string_types):
         urls = (urls,)
     else:
         urls = tuple(urls)
     # Generate a tuple of all the bits and return that as the key
     # because that's hashable.
     key = (urls, timeout, settings)
     return key
Exemple #15
0
 def _build_key(cls, urls, timeout, **settings):
     # Order the settings by key and then turn it into a string with
     # repr. There are a lot of edge cases here, but the worst that
     # happens is that the key is different and so you get a new
     # Elasticsearch. We'll probably have to tweak this.
     settings = sorted(settings.items(), key=lambda item: item[0])
     settings = repr([(k, v) for k, v in settings])
     # elasticsearch allows URLs to be a string, so we make sure to
     # account for that when converting whatever it is into a tuple.
     if isinstance(urls, string_types):
         urls = (urls, )
     else:
         urls = tuple(urls)
     # Generate a tuple of all the bits and return that as the key
     # because that's hashable.
     key = (urls, timeout, settings)
     return key
Exemple #16
0
    def allValues(cls, user=None):
        """
        Return a dict of "all" defined global settings.

        This performs a single database lookup,
        and then any settings which are not *in* the database
        are assigned their default values
        """

        results = cls.objects.all()

        if user is not None:
            results = results.filter(user=user)

        # Query the database
        settings = {}

        for setting in results:
            if setting.key:
                settings[setting.key.upper()] = setting.value

        # Specify any "default" values which are not in the database
        for key in cls.GLOBAL_SETTINGS.keys():

            if key.upper() not in settings:

                settings[key.upper()] = cls.get_setting_default(key)

        for key, value in settings.items():
            validator = cls.get_setting_validator(key)

            if cls.validator_is_bool(validator):
                value = InvenTree.helpers.str2bool(value)
            elif cls.validator_is_int(validator):
                try:
                    value = int(value)
                except ValueError:
                    value = cls.get_setting_default(key)

            settings[key] = value

        return settings
Exemple #17
0
    def add_map_feature_types(self, types):
        from treemap.models import MapFeature  # prevent circular import
        from treemap.audit import add_default_permissions

        classes = [MapFeature.get_subclass(type) for type in types]

        dups = set(types) & set(self.map_feature_types)
        if len(dups) > 0:
            raise ValidationError('Map feature types already added: %s' % dups)

        self.map_feature_types = list(self.map_feature_types) + list(types)
        self.save()

        for type, clz in zip(types, classes):
            settings = (getattr(clz, 'udf_settings', {}))
            for udfc_name, udfc_settings in settings.items():
                if udfc_settings.get('defaults'):
                    get_or_create_udf(self, type, udfc_name)

        add_default_permissions(self, models=classes)
def settings_list(request):
    """
    Custom admin view that displays the settings for this Django project.
    """

    if not request.user.is_superuser:
        return HttpResponseRedirect(reverse('admin:index'))

    settings = get_safe_settings()

    for setting in PRIVATE_SETTINGS:
        if setting in settings:
            settings[setting] = '********************'

    sorted_settings = sorted(settings.items())

    return render_to_response('admin/settings_list.html', RequestContext(request, {
        'title': 'Django Settings',
        'sorted_settings': sorted_settings,
    }))
Exemple #19
0
    def put(self, request, device_id=None):
        # Basic sanity check on the values we're trying to send
        for group, settings in request.DATA.items():
            if not type(settings) == dict:
                return Response(status=status.HTTP_400_BAD_REQUEST)
            else:
                for key, val in settings.items():
                    if not isinstance(val, (int, float, bool, str, unicode)):
                        return Response(status=status.HTTP_400_BAD_REQUEST)

        username, password, cloud_fqdn = get_credentials(request)

        if not username or not password or not cloud_fqdn:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        conn = DeviceCloudConnector(username, password, cloud_fqdn)

        try:
            settings = conn.set_device_settings(device_id,
                                                settings=request.DATA)
        except HTTPError, e:
            return Response(status=e.response.status_code,
                            data=e.response.text)
Exemple #20
0
def override_api_settings(**settings):
    old_settings = {}

    for k, v in settings.items():
        # Save settings
        try:
            old_settings[k] = api_settings.user_settings[k]
        except KeyError:
            pass

        # Install temporary settings
        api_settings.user_settings[k] = v

        # Delete any cached settings
        try:
            delattr(api_settings, k)
        except AttributeError:
            pass

    yield

    for k in settings.keys():
        # Delete temporary settings
        api_settings.user_settings.pop(k)

        # Restore saved settings
        try:
            api_settings.user_settings[k] = old_settings[k]
        except KeyError:
            pass

        # Delete any cached settings
        try:
            delattr(api_settings, k)
        except AttributeError:
            pass
Exemple #21
0
 def update_field(settings):
     # Identifier is lower-cased above to match the calling convention
     # of update endpoints, so we shouldn't overwrite it :(
     field.update({k: v for k, v in settings.items()
                   if v is not None and k != 'identifier'})
Exemple #22
0
 def wrapped(self, *args, **kwargs):
     self.factory.settings.update(settings)
     for key, value in settings.items():
         setattr(self.provider, key, value)
     fn(self, *args, **kwargs)
    def __init__(self, **settings):
        # check if some of the settings provided as class attributes
        # should be overwritten
        for name, value in settings.items():
            if hasattr(self, name):
                setattr(self, name, value)

        validate_settings(self)

        self.last_headers_name = None
        self.last_headers_value = None

        self.os_options = {
            'tenant_id': self.tenant_id,
            'tenant_name': self.tenant_name,
            'user_domain_id': self.user_domain_id,
            'user_domain_name': self.user_domain_name,
            'project_domain_id': self.project_domain_id,
            'project_domain_name': self.project_domain_name
        }
        self.os_options.update(self.os_extra_options)

        # Get authentication token
        self.storage_url, self.token = swiftclient.get_auth(
            self.api_auth_url,
            self.api_username,
            self.api_key,
            auth_version=self.auth_version,
            os_options=self.os_options)
        self.http_conn = swiftclient.http_connection(self.storage_url)

        # Check container
        try:
            swiftclient.head_container(self.storage_url,
                                       self.token,
                                       self.container_name,
                                       http_conn=self.http_conn)
        except swiftclient.ClientException:
            headers = {}
            if self.auto_create_container:
                if self.auto_create_container_public:
                    headers['X-Container-Read'] = '.r:*'
                if self.auto_create_container_allow_orgin:
                    headers['X-Container-Meta-Access-Control-Allow-Origin'] = \
                        self.auto_create_container_allow_orgin
                swiftclient.put_container(self.storage_url,
                                          self.token,
                                          self.container_name,
                                          http_conn=self.http_conn,
                                          headers=headers)
            else:
                raise ImproperlyConfigured(
                    "Container %s does not exist." % self.container_name)

        if self.auto_base_url:
            # Derive a base URL based on the authentication information from
            # the server, optionally overriding the protocol, host/port and
            # potentially adding a path fragment before the auth information.
            self.base_url = self.storage_url + '/'
            if self.override_base_url is not None:
                # override the protocol and host, append any path fragments
                split_derived = urlparse.urlsplit(self.base_url)
                split_override = urlparse.urlsplit(self.override_base_url)
                split_result = [''] * 5
                split_result[0:2] = split_override[0:2]
                split_result[2] = (split_override[2] + split_derived[2]
                                   ).replace('//', '/')
                self.base_url = urlparse.urlunsplit(split_result)

            self.base_url = urlparse.urljoin(self.base_url,
                                             self.container_name)
            self.base_url += '/'
        else:
            self.base_url = self.override_base_url