Ejemplo n.º 1
0
class ProxyPagination(BasePagination):
    """
    A simple configurable pagination proxy.
    """
    default_pager = import_from_string(settings.PROXY_PAGINATION_DEFAULT,
                                       'PROXY_PAGINATION_DEFAULT')
    pager_query_param = settings.PROXY_PAGINATION_PARAM or 'pager'
    mapping = {
        alias: import_from_string(path, 'PROXY_PAGINATION_MAPPING')
        for alias, path in settings.PROXY_PAGINATION_MAPPING.items()
    }

    def __init__(self):
        self.pager = self.default_pager()

    def paginate_queryset(self, queryset, request, view=None):
        alias = request.query_params.get(self.pager_query_param)
        self.pager = self.mapping.get(alias, self.default_pager)()
        return self.pager.paginate_queryset(queryset, request, view=view)

    def get_paginated_response(self, data):
        return self.pager.get_paginated_response(data)

    def to_html(self):
        return self.pager.to_html()

    def get_results(self, data):
        return self.pager.get_results(data)

    def get_fields(self, view):
        return self.pager.get_fields(view)

    def get_schema_fields(self, view):
        return self.pager.get_schema_fields(view)
Ejemplo n.º 2
0
def perform_import(val, setting_name):
    """
    If the given setting is a string import notation,
    then perform the necessary import or imports.
    """
    if isinstance(val, six.string_types):
        return import_from_string(val, setting_name)
    elif isinstance(val, (list, tuple)):
        return [import_from_string(item, setting_name) for item in val]
    elif isinstance(val, dict):
        return {import_from_string(k, setting_name): import_from_string(v, setting_name) for k, v in val.items()}
    return val
Ejemplo n.º 3
0
def perform_import(val, setting_name):
    """
    If the given setting is a string import notation,
    then perform the necessary import or imports.
    """
    if isinstance(val, six.string_types):
        return import_from_string(val, setting_name)
    elif isinstance(val, (list, tuple)):
        return [import_from_string(item, setting_name) for item in val]
    elif isinstance(val, dict):
        return {import_from_string(k, setting_name): import_from_string(v, setting_name) for k, v in val.items()}
    return val
Ejemplo n.º 4
0
    def list(self, request, *args, **kwargs):
        # don't use 'format' param as it's kind of reserved by DRF
        output = self.request.query_params.get('output')
        if output in ['xlsx', 'csv']:
            if not self.dataset:
                return Response(status=status.HTTP_400_BAD_REQUEST, data="No dataset specified")
            qs = self.filter_queryset(self.get_queryset())

            # exporter class
            exporter_class = DefaultExporter
            if hasattr(settings, 'EXPORTER_CLASS') and settings.EXPORTER_CLASS:
                try:
                    exporter_class = import_from_string(settings.EXPORTER_CLASS, 'EXPORTER_CLASS')
                except Exception:
                    logger.exception("Error while importing exporter class: {}".format(settings.EXPORTER_CLASS))

            exporter = exporter_class(self.dataset, qs)
            now = datetime.datetime.now()
            file_name = self.dataset.name + '_' + now.strftime('%Y-%m-%d-%H%M%S')
            if output == 'xlsx':
                file_name += '.xlsx'
                wb = exporter.to_workbook()
                response = WorkbookResponse(wb, file_name)
            else:
                # csv
                file_name += '.csv'
                response = CSVFileResponse(file_name=file_name)
                exporter.to_csv(response)
            return response
        else:
            return super(RecordViewSet, self).list(request, *args, **kwargs)
Ejemplo n.º 5
0
def import_value_or_module(val, setting_name):
    try:
        # first try to import as a value from a module
        return import_from_string(val, setting_name)
    except ImportError as e:
        # if that fails, try to import as an entire module
       return importlib.import_module(val)
Ejemplo n.º 6
0
    def get_allowed_versions(cls):
        if not hasattr(cls, '_allowed_versions'):
            drf_settings = getattr(settings, 'REST_FRAMEWORK', {})
            versioning_class_name = drf_settings.get(
                'DEFAULT_VERSIONING_CLASS', None)

            if versioning_class_name is None:
                raise NotImplementedError(
                    'A default versioning class needs to be defined in the DRF settings.'
                )

            versioning_class = import_from_string(
                versioning_class_name, setting_name='DEFAULT_VERSIONING_CLASS')
            allowed_versions = getattr(versioning_class, 'allowed_versions',
                                       [])

            if not allowed_versions:
                raise NotImplementedError(
                    'No allowed_versions were available in the versioning class.'
                )

            if not isinstance(allowed_versions, list):
                raise TypeError(
                    'The allowed_versions in the versioning class needs to be a '
                    'list, order is important.')
            cls._allowed_versions = allowed_versions
        return cls._allowed_versions
Ejemplo n.º 7
0
class SpeciesMixin(object):
    species_facade_class = NoSpeciesFacade
    if settings.SPECIES_FACADE_CLASS:
        try:
            species_facade_class = import_from_string(settings.SPECIES_FACADE_CLASS, 'SPECIES_FACADE_CLASS')
        except Exception as e:
            msg = "Error while importing the species facade class {}".format(settings.SPECIES_FACADE_CLASS)
            logger.exception(msg)
Ejemplo n.º 8
0
    def child(self):
        if not hasattr(self, '_child'):
            child_class, args, kwargs = self._child_specification

            if six.text_type(child_class):
                child_class = import_from_string(child_class, None)

            self._child = child_class(*args, **kwargs)

        return self._child
Ejemplo n.º 9
0
    def child(self):
        if not hasattr(self, '_child'):
            child_class, args, kwargs = self._child_specification

            if six.text_type(child_class):
                child_class = import_from_string(child_class, None)

            self._child = child_class(*args, **kwargs)

        return self._child
Ejemplo n.º 10
0
def import_base(base, transformation='Unknown'):
    """Import the base of transformation as a serializer or field.

    Args:
        transformation: ``Transformation`` class with this base. (optional)
        base: Fully qualified class name of serializer, field or a specific serializer's field.

    Returns:
        Tuple of the ``Serializer`` or ``Field``. If a ``Serializer`` with a
        specific field, the name of the field will also be returned.
        tuple
    """
    try:
        serializer = import_from_string(base, 'bases')
        assert_versioned_mixin(serializer)
        return serializer, None
    except (ValueError, ImportError):
        parts = base.split('.')
        try:
            serializer_name = '.'.join(parts[:-1])
            field_name = parts[-1]
        except IndexError:
            logger.error(
                '{transformation} has an invalid base: "{base}".\nCould not import '
                'it as a serializer nor field.'.format(
                    transformation=transformation, base=base))
            return None, None
        try:
            serializer = import_from_string(serializer_name, 'bases')
            assert_versioned_mixin(serializer)
            return serializer, field_name
        except (ValueError, ImportError):
            logger.error(
                '{transformation} has an invalid base: "{base}".\nCould not import '
                'the serializer "{serializer}" with the field "{field_name}".'.
                format(transformation=transformation,
                       base=base,
                       serializer=serializer_name,
                       field_name=field_name))
            raise
    return None, None
Ejemplo n.º 11
0
def extract_function(func_name):
    """
    Return a function out of a namespace

    Return None if the function is not loadable
    """
    func = None
    try:
        func = import_from_string(func_name, '')
    except (ImportError, ValueError):
        logger.error("An error has occurred impossible to import %s",
                     func_name)
    return func
Ejemplo n.º 12
0
def get_view_description(view_cls, html=False, request=None):
    documenters = []

    if hasattr(view_cls, 'documenter_classes'):
        for cls in view_cls.documenter_classes:
            documenters.append(cls())
    else:
        for cls in APIDOC_DEFAULT_DOCUMENTER_CLASSES:
            documenter_class = import_from_string(cls, "APIDOC_DEFAULT_DOCUMENTER_CLASS")
            documenters.append(documenter_class())

    for documenter in documenters:
        description = documenter.get_description(view_cls, html, request)
        if description:
            return description

    return ""
Ejemplo n.º 13
0
def get_view_description(view_cls, html=False, request=None):
    documenters = []

    if hasattr(view_cls, 'documenter_classes'):
        for cls in view_cls.documenter_classes:
            documenters.append(cls())
    else:
        for cls in APIDOC_DEFAULT_DOCUMENTER_CLASSES:
            documenter_class = import_from_string(
                cls, "APIDOC_DEFAULT_DOCUMENTER_CLASS")
            documenters.append(documenter_class())

    for documenter in documenters:
        description = documenter.get_description(view_cls, html, request)
        if description:
            return description

    return ""
Ejemplo n.º 14
0
"""
SaaS Rest Framework settings initialization
"""
from django.conf import settings
from rest_framework.settings import import_from_string


REST_SETTINGS = getattr(settings, 'REST_FRAMEWORK', {})

SAAS_SETTINGS = REST_SETTINGS.get('SAAS', {})

SAAS_MODEL = import_from_string(SAAS_SETTINGS.get('MODEL'),
                                'MODEL'
                                ) if SAAS_SETTINGS.get('MODEL') else None

SAAS_LOOKUP_FIELD = SAAS_SETTINGS.get('LOOKUP_FIELD', 'id')
Ejemplo n.º 15
0
from bossoidc.models import Keycloak as KeycloakModel
from jwkest.jwt import JWT

import json


def load_user_roles(user, roles):
    pass


LOAD_USER_ROLES = getattr(settings, 'LOAD_USER_ROLES', None)
if LOAD_USER_ROLES is None:
    # DP NOTE: had issues with import_from_string loading bossoidc.backend.load_user_roles
    LOAD_USER_ROLES_FUNCTION = load_user_roles
else:
    LOAD_USER_ROLES_FUNCTION = import_from_string(LOAD_USER_ROLES,
                                                  'LOAD_USER_ROLES')


def update_user_data(user, token):
    pass


UPDATE_USER_DATA = getattr(settings, 'UPDATE_USER_DATA', None)
if UPDATE_USER_DATA is None:
    UPDATE_USER_DATA_FUNCTION = update_user_data
else:
    UPDATE_USER_DATA_FUNCTION = import_from_string(UPDATE_USER_DATA,
                                                   'UPDATE_USER_DATA')


def check_username(username: str):
Ejemplo n.º 16
0
 def io_class(self):
     return import_from_string(self.class_name, self.name)
Ejemplo n.º 17
0
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.conf import settings
from rest_framework.settings import import_from_string
from data_wizard import registry

LOADER_PATH = getattr(settings, 'DATA_WIZARD_LOADER',
                      'data_wizard.loaders.FileLoader')
Loader = import_from_string(LOADER_PATH, 'DATA_WIZARD_LOADER')


class Run(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    template = models.ForeignKey('self', null=True, blank=True)
    record_count = models.IntegerField(null=True, blank=True)
    loader = models.CharField(max_length=255, default=LOADER_PATH)
    serializer = models.CharField(max_length=255, null=True, blank=True)

    content_type = models.ForeignKey(ContentType, null=True, blank=True)
    object_id = models.PositiveIntegerField(null=True, blank=True)
    content_object = GenericForeignKey()

    def __str__(self):
        return "Run for %s" % self.content_object

    def save(self, *args, **kwargs):
        is_new = not self.id
        super(Run, self).save(*args, **kwargs)
        if is_new:
            self.add_event('created')
Ejemplo n.º 18
0
        else:
            return ""

    @classmethod
    def update_docstring(cls, documented_cls, base_doc, docstring, method_name):
        text, yaml = cls._get_text_and_yaml(docstring)
        if not base_doc:
            base_doc = ""

        text = base_doc + "\n\n" + text + "\n\n" + cls._generate_text(documented_cls, method_name)
        yaml += "\n\n" + cls._generate_yaml(documented_cls, method_name)
        return cls._format_docstring(text, yaml)


if hasattr(settings, "AUTODOC_DEFAULT_CLASSESS"):
    DEFAULT_CLASSESS = [import_from_string(x, "") for x in settings.AUTODOC_DEFAULT_CLASSESS]
else:
    DEFAULT_CLASSESS = (BaseInfoAutodoc, PermissionsAutodoc, OrderingAndFilteringAutodoc, PaginationAutodoc,
                        VersioningAutodoc, OnDemandFieldsAutodoc)


def autodoc(base_doc="", classess=DEFAULT_CLASSESS, add_classess=None, skip_classess=None):
    def copy_method(cls, method_name, method):
        """ create facade for a method with preservation of original docstring """
        @wraps(method)
        def shadow_method(self, *args, **kwargs):
            return method(self, *args, **kwargs)
        shadow_method.__doc__ = method.__doc__
        setattr(cls, method_name, shadow_method)

    def wrapped(cls):
Ejemplo n.º 19
0
 def io_class(self):
     return import_from_string(self.class_name, self.name)
Ejemplo n.º 20
0
from bossoidc.models import Keycloak as KeycloakModel
from jwkest.jwt import JWT

import json


def load_user_roles(user, roles):
    pass


LOAD_USER_ROLES = getattr(settings, 'LOAD_USER_ROLES', None)
if LOAD_USER_ROLES is None:
    # DP NOTE: had issues with import_from_string loading bossoidc.backend.load_user_roles
    LOAD_USER_ROLES_FUNCTION = load_user_roles
else:
    LOAD_USER_ROLES_FUNCTION = import_from_string(LOAD_USER_ROLES,
                                                  'LOAD_USER_ROLES')


def check_username(username):
    if len(username) > 30:  # Django User username is 30 character limited
        raise AuthenticationFailed(_('Username is too long for Django'))


def update_user_data(user, token):
    pass


def get_user_by_id(request, id_token):
    """ Taken from djangooidc.backends.OpenIdConnectBackend and made common for
    drf-oidc-auth to make use of the same create user functionality
    """