Python django.conf.settings.py() Examples

The following are 30 code examples for showing how to use django.conf.settings.py(). 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.settings , or try the search function .

Example 1
Project: django-phone-verify   Author: CuriousLearner   File: services.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _check_required_settings(self):
        required_settings = {
            "BACKEND",
            "OPTIONS",
            "TOKEN_LENGTH",
            "MESSAGE",
            "APP_NAME",
            "SECURITY_CODE_EXPIRATION_TIME",
            "VERIFY_SECURITY_CODE_ONLY_ONCE",
        }
        user_settings = set(settings.PHONE_VERIFICATION.keys())
        if not required_settings.issubset(user_settings):
            raise ImproperlyConfigured(
                "Please specify following settings in settings.py: {}".format(
                    ", ".join(required_settings - user_settings)
                )
            ) 
Example 2
Project: django-qiniu-storage   Author: glasslion   File: auth.py    License: MIT License 6 votes vote down vote up
def authenticate(self, username=None, password=None):
        login_valid = (settings.ADMIN_LOGIN == username)
        pwd_valid = (settings.ADMIN_PASSWORD == password)
        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. Note that we can set password
                # to anything, because it won't be checked; the password
                # from settings.py will.
                user = User(username=username, password=password)
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None 
Example 3
Project: tom_base   Author: TOMToolkit   File: facility.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_facility_status(self):
        """
        Returns a dictionary describing the current availability of the Facility
        telescopes. This is intended to be useful in observation planning.
        The top-level (Facility) dictionary has a list of sites. Each site
        is represented by a site dictionary which has a list of telescopes.
        Each telescope has an identifier (code) and an status string.

        The dictionary hierarchy is of the form:

        `facility_dict = {'code': 'XYZ', 'sites': [ site_dict, ... ]}`
        where
        `site_dict = {'code': 'XYZ', 'telescopes': [ telescope_dict, ... ]}`
        where
        `telescope_dict = {'code': 'XYZ', 'status': 'AVAILABILITY'}`

        See lco.py for a concrete implementation example.
        """
        return {} 
Example 4
Project: tom_base   Author: TOMToolkit   File: alerts.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_service_classes():
    """
    Gets the broker classes available to this TOM as specified by ``TOM_ALERT_CLASSES`` in ``settings.py``. If none are
    specified, returns the default set.

    :returns: dict of broker classes, with keys being the name of the broker and values being the broker class
    :rtype: dict
    """
    try:
        TOM_ALERT_CLASSES = settings.TOM_ALERT_CLASSES
    except AttributeError:
        TOM_ALERT_CLASSES = DEFAULT_ALERT_CLASSES

    service_choices = {}
    for service in TOM_ALERT_CLASSES:
        mod_name, class_name = service.rsplit('.', 1)
        try:
            mod = import_module(mod_name)
            clazz = getattr(mod, class_name)
        except (ImportError, AttributeError):
            raise ImportError(f'Could not import {service}. Did you provide the correct path?')
        service_choices[clazz.name] = clazz
    return service_choices 
Example 5
Project: tom_base   Author: TOMToolkit   File: tom_setup.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_hint_preference(self):
        help_message_info = (
            'Help messages can be configured to appear to give suggestions on commonly customized functions. If '
            'enabled now, they can be turned off by changing HINTS_ENABLED to False in settings.py.\n'
        )
        prompt = 'Would you like to enable hints? {}'.format(self.style.WARNING('[y/N] '))
        self.stdout.write(help_message_info)
        while True:
            response = input(prompt).lower()
            if not response or response == 'n':
                self.context['HINTS_ENABLED'] = False
            elif response == 'y':
                self.context['HINTS_ENABLED'] = True
            else:
                self.stdout.write('Invalid response. Please try again.')
                continue

            break 
Example 6
Project: tom_base   Author: TOMToolkit   File: harvester.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_service_classes():
    """
    Gets the harvester classes available to this TOM as specified by ``TOM_HARVESTER_CLASSES`` in ``settings.py``. If
    none are specified, returns the default set.

    :returns: dict of harvester classes, with keys being the name of the catalog and values being the harvester class
    :rtype: dict
    """
    try:
        TOM_HARVESTER_CLASSES = settings.TOM_HARVESTER_CLASSES
    except AttributeError:
        TOM_HARVESTER_CLASSES = DEFAULT_HARVESTER_CLASSES

    service_choices = {}
    for service in TOM_HARVESTER_CLASSES:
        mod_name, class_name = service.rsplit('.', 1)
        try:
            mod = import_module(mod_name)
            clazz = getattr(mod, class_name)
        except (ImportError, AttributeError):
            raise ImportError('Could not import {}. Did you provide the correct path?'.format(service))
        service_choices[clazz.name] = clazz
    return service_choices 
Example 7
Project: zulip   Author: zulip   File: deliver_scheduled_messages.py    License: Apache License 2.0 6 votes vote down vote up
def handle(self, *args: Any, **options: Any) -> None:

        if settings.EMAIL_DELIVERER_DISABLED:
            # Here doing a check and sleeping indefinitely on this setting might
            # not sound right. Actually we do this check to avoid running this
            # process on every server that might be in service to a realm. See
            # the comment in zproject/settings.py file about renaming this setting.
            sleep_forever()

        while True:
            messages_to_deliver = ScheduledMessage.objects.filter(
                scheduled_timestamp__lte=timezone_now(),
                delivered=False)
            if messages_to_deliver:
                for message in messages_to_deliver:
                    with transaction.atomic():
                        do_send_messages([self.construct_message(message)])
                        message.delivered = True
                        message.save(update_fields=['delivered'])

            cur_time = timezone_now()
            time_next_min = (cur_time + timedelta(minutes=1)).replace(second=0, microsecond=0)
            sleep_time = (time_next_min - cur_time).total_seconds()
            time.sleep(sleep_time) 
Example 8
Project: django-traffic   Author: koslibpro   File: middleware.py    License: MIT License 6 votes vote down vote up
def __init__(self, get_response=None):
        self.get_response = get_response

        if hasattr(settings, 'TRAFFIC_INDEX_NAME'):
            self.index_name = getattr(settings, 'TRAFFIC_INDEX_NAME')
        else:
            self.index_name = "django-traffic"

        # if settings.ES_CLIENT:
        if hasattr(settings, 'ES_CLIENT'):
            self.es = settings.ES_CLIENT
        else:
            assert settings.ES_HOST, 'ES_HOST definition in settings.py is required'
            self.es = Elasticsearch(
                hosts=[settings.ES_HOST]
            )

        super(ESTrafficInfoMiddleware, self).__init__(get_response=get_response) 
Example 9
Project: urbanfootprint   Author: CalthorpeAnalytics   File: create_datadump.py    License: GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):

        rsync = spawn.find_executable('rsync')
        if rsync is None:
            raise CommandError('rsync not found')

        pg_dump = spawn.find_executable('pg_dump')
        if pg_dump is None:
            raise CommandError('pg_dump not found')

        if options['destination_folder'] == '':
            raise CommandError('--destination-folder not specified in command line nor settings.py')

        # make sure destination folder exists
        if not os.path.exists(options['destination_folder']):
            try:
                os.makedirs(options['destination_folder'])
            except Exception, e:
                raise Exception("Cannot create directory with user %s. Exception %s" % (
                    pwd.getpwuid(os.getuid())[0],
                    e.message)) 
Example 10
Project: openwisp-utils   Author: openwisp   File: apps.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def configure_rest_framework_defaults(self):
        # merge the default DRF settings defined in openwisp-utils
        # and the default DRF settings defined in the app inheriting this class
        default_settings = DEFAULT_REST_FRAMEWORK_SETTINGS
        app_settings = getattr(self, 'REST_FRAMEWORK_SETTINGS', {})
        merged_default_settings = deep_merge_dicts(default_settings, app_settings)
        # get the DRF settings defined in settings.py, if any
        current_settings = getattr(settings, 'REST_FRAMEWORK', {})

        # loop over the default settings dict
        for key, value in merged_default_settings.items():
            # if any key is a dictionary, and the same key
            # is also defined in settings.py
            # merge the two dicts, giving precedence
            # to what is defined in settings.py
            if isinstance(value, dict) and key in current_settings:
                value.update(current_settings[key])
                current_settings[key] = value
                continue
            # otherwise just set it as default value
            current_settings.setdefault(key, value)

        # explicitly set it in settings.py
        setattr(settings, 'REST_FRAMEWORK', current_settings) 
Example 11
Project: celery-monitor   Author: jimmy201602   File: bootstrapped_goodies_tags.py    License: GNU General Public License v3.0 6 votes vote down vote up
def language_selector(context):
    """ displays a language selector dropdown in the admin, based on Django "LANGUAGES" context.
        requires:
            * USE_I18N = True / settings.py
            * LANGUAGES specified / settings.py (otherwise all Django locales will be displayed)
            * "set_language" url configured (see https://docs.djangoproject.com/en/dev/topics/i18n/translation/#the-set-language-redirect-view)
    """
    output = ""
    i18 = getattr(settings, 'USE_I18N', False)
    if i18:
        template = "admin/language_selector.html"
        context['i18n_is_set'] = True
        try:
            output = render_to_string(template, context)
        except:
            pass
    return output 
Example 12
Project: govready-q   Author: GovReady   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_profile_picture_absolute_url(self):
        # Because of invitations, profile photos are not protected by
        # authorization. But to prevent user enumeration and to bust
        # caches when photos change, we include in the URL some
        # information about the internal data of the profile photo,
        # which is checked in views_landing.py's user_profile_photo().

        # Get the current profile photo.
        try:
            pic = self._get_setting("picture")
            if pic is None:
                return
        except:
            return None

        # We've got the content. Make a fingerprint.
        import xxhash, base64
        payload = pic['content_dataurl']
        fingerprint = base64.urlsafe_b64encode(
                        xxhash.xxh64(payload).digest()
                       ).decode('ascii').rstrip("=")
        return settings.SITE_ROOT_URL + "/media/users/%d/photo/%s" % (
            self.id,
            fingerprint
        ) 
Example 13
Project: govready-q   Author: GovReady   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def create(admin_user=None, **kargs): # admin_user is a required kwarg
        # See admin.py::OrganizationAdmin also.

        assert admin_user

        # Create instance by passing field values to the ORM.
        org = Organization.objects.create(**kargs)

        # And initialize the root Task of the Organization with this user as its editor.
        org.get_organization_project().set_system_task("organization", admin_user)

        # And make that user an admin of the Organization.
        pm, isnew = ProjectMembership.objects.get_or_create(user=admin_user, project=org.get_organization_project())
        pm.is_admin = True
        pm.save()

        return org 
Example 14
Project: wharf   Author: palfrey   File: auth.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def authenticate(self, request, username=None, password=None):
        login_valid = (settings.ADMIN_LOGIN == username)
        if settings.ADMIN_PASSWORD.startswith("pbkdf2_sha256"):
            pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
        else:
            pwd_valid = password == settings.ADMIN_PASSWORD
        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. There's no need to set a password
                # because only the password from settings.py is checked.
                user = User(username=username)
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None 
Example 15
Project: django-oss-storage   Author: aliyun   File: auth.py    License: MIT License 6 votes vote down vote up
def authenticate(self, username=None, password=None):
        """
        Username and password authentication
        """
        login_valid = (settings.ADMIN_LOGIN == username)
        pwd_valid = (settings.ADMIN_PASSWORD == password)

        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. Note that we can set password
                # to anything, because it won't be checked; the password
                # from settings.py will.
                user = User(username=username, password=password)
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None 
Example 16
Project: texta   Author: texta-tk   File: importer.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, es_url, configuration, data_access_object, file_system_storer):
        """
        :param es_url: Elasticsearch instance's URL.
        :param configuration: DATASET_IMPORTER dict from texta/settings.py, which includes necessary parameters for importer.
        :param data_access_object: An attempt to separate Django's DatasetImport model object from import to reduce coupling and enhance testing.
        :param file_system_storer: Same as above. Django's built-in FileSystemStorage for storing data from requests to disk.
        :type es_url: string
        :type configuration: dict
        """
        self._es_url = es_url

        self._root_directory = configuration['directory']
        self._n_processes = configuration['import_processes']
        self._process_batch_size = configuration['process_batch_size']
        self._index_sqlite_path = configuration['sync']['index_sqlite_path']

        self._dao = data_access_object
        self._file_system_storer = file_system_storer

        self._active_import_jobs = {} 
Example 17
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def run_manage(self, args, settings_file=None):
        def safe_remove(path):
            try:
                os.remove(path)
            except OSError:
                pass

        conf_dir = os.path.dirname(conf.__file__)
        template_manage_py = os.path.join(conf_dir, 'project_template', 'manage.py-tpl')

        test_manage_py = os.path.join(self.test_dir, 'manage.py')
        shutil.copyfile(template_manage_py, test_manage_py)

        with open(test_manage_py, 'r') as fp:
            manage_py_contents = fp.read()
        manage_py_contents = manage_py_contents.replace(
            "{{ project_name }}", "test_project")
        with open(test_manage_py, 'w') as fp:
            fp.write(manage_py_contents)
        self.addCleanup(safe_remove, test_manage_py)

        return self.run_test('./manage.py', args, settings_file) 
Example 18
Project: django-phone-verify   Author: CuriousLearner   File: test_services.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_exception_is_raised_when_improper_settings(client):
    with pytest.raises(ImproperlyConfigured) as exc:
        PhoneVerificationService(phone_number="+13478379634")
        assert (
            exc.info
            == "Please specify following settings in settings.py: OPTIONS, TOKEN_LENGTH"
        ) 
Example 19
Project: django-mailjet   Author: kidig   File: backends.py    License: MIT License 5 votes vote down vote up
def __init__(self, fail_silently=False, *args, **kwargs):
        super(MailjetBackend, self).__init__(fail_silently=fail_silently, *args, **kwargs)

        try:
            self._api_key = settings.MAILJET_API_KEY
            self._api_secret = settings.MAILJET_API_SECRET
        except AttributeError:
            if not fail_silently:
                raise ImproperlyConfigured("Please set MAILJET_API_KEY and MAILJET_API_SECRET in settings.py to use Mailjet")

        self.client = Client(auth=(self._api_key, self._api_secret)) 
Example 20
Project: django-imgix   Author: pancentric   File: imgix_tags.py    License: ISC License 5 votes vote down vote up
def get_kwargs(alias, aliases, kwargs):

    # Check if we are using an alias or inline arguments
    if not alias:
        return kwargs
    elif not aliases:
        raise ImproperlyConfigured(
            "No aliases set. Please set IMGIX_ALIASES in settings.py"
        )
    elif alias not in aliases:
        raise ImproperlyConfigured(
            "Alias {0} not found in IMGIX_ALIASES".format(alias)
        )
    else:
        return aliases[alias] 
Example 21
Project: OasisPlatform   Author: OasisLMF   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def storage_link(self, storage_obj):
           """
           Return link to file storage based on 'STORAGE_TYPE' value in settings.py

            storage_obj should point to a `RelatedFile` Obj

           STORAGE_TYPE;
                'Default': local filesystem -> return filename
                'AWS-S3': Remote Object Store -> Return URL with expire time
           """
           # GUARD check for file, return None it missing
           if not hasattr(storage_obj, 'file'):
               return None
           if not storage_obj.file:
               return None

           # S3 storage links
           if settings.STORAGE_TYPE in ['aws-s3', 's3', 'aws']:
                if settings.AWS_SHARED_BUCKET:
                    # Return object key for shared S3 bucket
                    return path.join(
                        storage_obj.file.storage.location,
                        storage_obj.file.name,
                    )
                else:
                    # Return Download URL to S3 Object
                    return storage_obj.file.storage.url(storage_obj.file.name)

           # Shared FS filename
           else:
                return storage_obj.file.name 
Example 22
Project: tom_base   Author: TOMToolkit   File: tom_setup.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_config(self):
        self.status('Generating settings.py... ')
        template = get_template('tom_setup/settings.tmpl')
        rendered = template.render(self.context)

        # TODO: Ugly hack to get project name
        settings_location = os.path.join(BASE_DIR, os.path.basename(BASE_DIR), 'settings.py')
        if not os.path.exists(settings_location):
            msg = 'Could not determine settings.py location. Writing settings.py out to {}. Please copy file to \
                   the proper location after script finishes.'.format(settings_location)
            self.stdout.write(self.style.WARNING(msg))
        with open(settings_location, 'w+') as settings_file:
            settings_file.write(rendered)

        self.ok() 
Example 23
Project: tom_base   Author: TOMToolkit   File: tom_setup.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_urls(self):
        self.status('Generating urls.py... ')
        template = get_template('tom_setup/urls.tmpl')
        rendered = template.render(self.context)

        # TODO: Ugly hack to get project name
        urls_location = os.path.join(BASE_DIR, os.path.basename(BASE_DIR), 'urls.py')
        if not os.path.exists(urls_location):
            msg = 'Could not determine urls.py location. Writing urls.py out to {}. Please copy file to \
                   the proper location after script finishes.'.format(urls_location)
            self.stdout.write(self.style.WARNING(msg))
        with open(urls_location, 'w+') as urls_file:
            urls_file.write(rendered)

        self.ok() 
Example 24
Project: tom_base   Author: TOMToolkit   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_default_target_type(self):
        """
        Returns the user-configured target type specified in ``settings.py``, if it exists, otherwise returns sidereal

        :returns: User-configured target type or global default
        :rtype: str
        """
        try:
            return settings.TARGET_TYPE
        except AttributeError:
            return Target.SIDEREAL 
Example 25
Project: tom_base   Author: TOMToolkit   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_target_type(self):
        """
        Gets the type of the target to be created from the query parameters. If none exists, use the default target
        type specified in ``settings.py``.

        :returns: target type
        :rtype: str
        """
        obj = self.request.GET or self.request.POST
        target_type = obj.get('type')
        # If None or some invalid value, use default target type
        if target_type not in (Target.SIDEREAL, Target.NON_SIDEREAL):
            target_type = self.get_default_target_type()
        return target_type 
Example 26
Project: tom_base   Author: TOMToolkit   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        """
        Handles the POST requests to this view. Routes the information from the request and query parameters to the
        appropriate utility method in ``groups.py``.

        :param request: the request object passed to this view
        :type request: HTTPRequest
        """
        query_string = request.POST.get('query_string', '')
        grouping_id = request.POST.get('grouping')
        filter_data = QueryDict(query_string)
        try:
            grouping_object = TargetList.objects.get(pk=grouping_id)
        except Exception as e:
            messages.error(request, 'Cannot find the target group with id={}; {}'.format(grouping_id, e))
            return redirect(reverse('tom_targets:list') + '?' + query_string)
        if not request.user.has_perm('tom_targets.view_targetlist', grouping_object):
            messages.error(request, 'Permission denied.')
            return redirect(reverse('tom_targets:list') + '?' + query_string)

        if 'add' in request.POST:
            if request.POST.get('isSelectAll') == 'True':
                add_all_to_grouping(filter_data, grouping_object, request)
            else:
                targets_ids = request.POST.getlist('selected-target')
                add_selected_to_grouping(targets_ids, grouping_object, request)
        if 'remove' in request.POST:
            if request.POST.get('isSelectAll') == 'True':
                remove_all_from_grouping(filter_data, grouping_object, request)
            else:
                targets_ids = request.POST.getlist('selected-target')
                remove_selected_from_grouping(targets_ids, grouping_object, request)
        return redirect(reverse('tom_targets:list') + '?' + query_string) 
Example 27
Project: tom_base   Author: TOMToolkit   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        """
        Saves Target model data to the database, including extra fields. After saving to the database, also runs the
        hook ``target_post_save``. The hook run is the one specified in ``settings.py``.

        :Keyword Arguments:
            * extras (`dict`): dictionary of key/value pairs representing target attributes
        """
        extras = kwargs.pop('extras', {})
        names = kwargs.pop('names', [])

        created = False if self.id else True
        super().save(*args, **kwargs)

        if created:
            for extra_field in settings.EXTRA_FIELDS:
                if extra_field.get('default') is not None:
                    TargetExtra(target=self, key=extra_field['name'], value=extra_field.get('default')).save()

        for k, v in extras.items():
            target_extra, _ = TargetExtra.objects.get_or_create(target=self, key=k)
            target_extra.value = v
            target_extra.save()

        for name in names:
            name, _ = TargetName.objects.get_or_create(target=self, name=name)
            name.save()

        if not created:
            run_hook('target_post_save', target=self, created=created) 
Example 28
Project: tom_base   Author: TOMToolkit   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def tags(self):
        """
        Gets all ``TargetExtra`` fields associated with this ``Target``, provided the key is `NOT` defined in
        ``settings.py`` ``EXTRA_FIELDS``

        :returns: Dictionary of key/value pairs representing target attributes
        :rtype: dict
        """
        defined_extras = [extra_field['name'] for extra_field in settings.EXTRA_FIELDS]
        return {te.key: te.value for te in self.targetextra_set.exclude(key__in=defined_extras)} 
Example 29
Project: tom_base   Author: TOMToolkit   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        """
        Saves the current `DataProduct` instance. Before saving, validates the `data_product_type` against those
        specified in `settings.py`.
        """
        for dp_type, dp_values in settings.DATA_PRODUCT_TYPES.items():
            if not self.data_product_type or self.data_product_type == dp_values[0]:
                break
        else:
            raise ValidationError('Not a valid DataProduct type.')
        return super().save() 
Example 30
Project: tom_base   Author: TOMToolkit   File: data_processor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run_data_processor(dp):
    """
    Reads the `data_product_type` from the dp parameter and imports the corresponding `DataProcessor` specified in
    `settings.py`, then runs `process_data` and inserts the returned values into the database.

    :param dp: DataProduct which will be processed into a list
    :type dp: DataProduct

    :returns: QuerySet of `ReducedDatum` objects created by the `run_data_processor` call
    :rtype: `QuerySet` of `ReducedDatum`
    """

    try:
        processor_class = settings.DATA_PROCESSORS[dp.data_product_type]
    except Exception:
        processor_class = DEFAULT_DATA_PROCESSOR_CLASS

    try:
        mod_name, class_name = processor_class.rsplit('.', 1)
        mod = import_module(mod_name)
        clazz = getattr(mod, class_name)
    except (ImportError, AttributeError):
        raise ImportError('Could not import {}. Did you provide the correct path?'.format(processor_class))

    data_processor = clazz()
    data = data_processor.process_data(dp)

    reduced_datums = [ReducedDatum(target=dp.target, data_product=dp, data_type=dp.data_product_type,
                                   timestamp=datum[0], value=datum[1]) for datum in data]
    ReducedDatum.objects.bulk_create(reduced_datums)

    return ReducedDatum.objects.filter(data_product=dp)