Ejemplo n.º 1
0
    def create_type_of_from_doc_param(cls, type_string: str) -> Optional[type]:
        from avishan.models import AvishanModel

        if type_string.find('[') > 0:
            found = cls.create_type_from_doc_param(type_string=type_string)
            if found is Attribute.TYPE.ARRAY:
                return AvishanModel.get_model_with_class_name(
                    type_string[type_string.find('[') + 1:-1])
        if isinstance(type_string, str):
            return AvishanModel.get_model_with_class_name(type_string)
        return None
Ejemplo n.º 2
0
def find_and_check_user():
    """
    Populate current_request object with data from token. Then check for user "active" authorization
    :return:
    """
    from avishan.models import AvishanModel

    if not get_current_request().avishan.decoded_token:
        AuthException(AuthException.ERROR_IN_TOKEN)

    authentication_type_class = AvishanModel.get_model_with_class_name(
        get_current_request().avishan.decoded_token['at_n'])
    try:
        authentication_type_object: 'AuthenticationType' = authentication_type_class.objects.get(
            id=get_current_request().avishan.decoded_token['at_id'])
        user_user_group = authentication_type_object.user_user_group
    except authentication_type_class.DoesNotExist:
        raise AuthException(AuthException.ACCOUNT_NOT_FOUND)

    if not user_user_group.is_active:
        raise AuthException(AuthException.GROUP_ACCOUNT_NOT_ACTIVE)
    if not user_user_group.base_user.is_active:
        raise AuthException(AuthException.ACCOUNT_NOT_ACTIVE)
    if authentication_type_object.last_login is None or \
            authentication_type_object.last_login.timestamp() != get_current_request().avishan.decoded_token['lgn'] \
            or authentication_type_object.last_logout:
        get_current_request().avishan.add_token = False
        raise AuthException(AuthException.DEACTIVATED_TOKEN)

    authentication_type_object.last_used = timezone.now()
    authentication_type_object.save()
    authentication_type_object._populate_current_request()
 def get_model_by_snake_case_name(name: str) -> Optional[type]:
     from avishan.models import AvishanModel
     for model in AvishanModel.get_non_abstract_models():
         model: AvishanModel
         if model.class_snake_case_name() == name:
             return model
     return None
    def get_models(app_name: str = None) -> list:
        from avishan.models import AvishanModel

        def get_sub_classes(parent):
            subs = [parent]
            for child in parent.__subclasses__():
                subs += get_sub_classes(child)
            return subs

        total = []
        if not app_name:
            for model in AvishanModel.__subclasses__():
                total += get_sub_classes(model)
            return list(set(total))

        return [x for x in AvishanModel.get_models() if x._meta.app_label == app_name]
Ejemplo n.º 5
0
    def __init__(self, parameter: inspect.Parameter):
        from avishan.models import AvishanModel

        if parameter is inspect.Parameter.empty or parameter.name in [
                'self', 'cls'
        ]:
            raise ValueError

        default = self.NO_DEFAULT
        if parameter.default is not inspect.Parameter.empty:
            default = parameter.default
        super().__init__(name=parameter.name,
                         type=self.define_representation_type(parameter),
                         default=default)
        temp = parameter.annotation
        if self.type is Attribute.TYPE.OBJECT:
            if isinstance(parameter.annotation, str):
                self.type_of = AvishanModel.get_model_with_class_name(
                    parameter.annotation)
            else:
                try:
                    from typing import _Union
                    if isinstance(parameter.annotation, _Union):
                        for item in parameter.annotation.__args__:
                            temp = item
                            break
                except Exception:
                    pass
                self.type_of = temp
        if self.type is Attribute.TYPE.ARRAY:
            temp = parameter.annotation.__args__[0]
            found_here = False
            try:
                from typing import _ForwardRef
                if isinstance(temp, _ForwardRef):
                    temp = AvishanModel.get_model_with_class_name(
                        temp.__forward_arg__)
                    found_here = True
            except Exception:
                pass

            if not found_here:
                temp = Attribute.type_finder(temp)
            self.type_of = temp
        self.is_required = self.define_is_required(parameter)
Ejemplo n.º 6
0
    def type_finder(entry) -> 'Attribute.TYPE':
        from avishan.models import AvishanModel
        if entry == 'datetime.datetime':
            entry = datetime.datetime
        elif entry == 'datetime.date':
            entry = datetime.date
        elif entry == 'datetime.time':
            entry = datetime.time

        try:
            from typing import _Union
            if isinstance(entry, _Union):
                for item in entry.__args__:
                    return Attribute.type_finder(item)
        except ImportError:
            pass

        for target, pool in Attribute._TYPE_POOL.items():
            for swimmer in pool:
                if entry is swimmer:
                    return target

        # instanced type
        for target, pool in Attribute._TYPE_POOL.items():
            for swimmer in pool:
                if swimmer is str:
                    continue
                if isinstance(entry, swimmer):
                    return target

        # inherited type
        for target, pool in Attribute._TYPE_POOL.items():
            for swimmer in pool:
                if inspect.isclass(entry) and issubclass(entry, swimmer):
                    return target

        # string of type
        for target, pool in Attribute._TYPE_POOL.items():
            for swimmer in pool:
                if entry == swimmer.__name__:
                    return target

        if (isinstance(entry, str) and AvishanModel.get_model_with_class_name(entry) is not None) \
                or isinstance(entry, ModelBase):
            return Attribute.TYPE.OBJECT

        if entry.many_to_many:
            return Attribute.TYPE.ARRAY

        raise NotImplementedError()
Ejemplo n.º 7
0
def create_dbml_file(address: str):
    dbml = {
        'tables': []
    }
    for model in AvishanModel.get_models():
        dbml['tables'].append(convert_model_to_object(model))
    print(f"DBML READ FOR {len(dbml['tables'])} TABLES")
    from pathlib import Path
    folder = ""
    parts = address.split("/")
    for part in parts[:-1]:
        folder += part + "/"
    Path(folder).mkdir(parents=True, exist_ok=True)
    writer(dbml, address)
    print("DBML FILE CREATED")
Ejemplo n.º 8
0
    def __init__(self):
        self.packs = []
        for item in get_avishan_config().CHAYI_PROJECT_PACKAGE:
            self.packs.append([
                item[0], f'package {item[1]}.models;\n\n'
                f'import {item[1]}.constants.Constants;\n'
            ])

        self.files = {}
        self.tab_size = 0
        for model in AvishanModel.get_models():
            if model._meta.abstract or model.export_ignore:
                continue
            self.files[model.class_name() +
                       ".java"] = self.model_file_creator(model)

        self.model_file_predefined_models(self.files)

        self.compress_files(self.packs, self.files)
Ejemplo n.º 9
0
    def type_caster(entry, target_type: 'Attribute.TYPE'):
        from avishan.models import AvishanModel

        if entry is None:
            return None

        if target_type is Attribute.TYPE.STRING:
            cast_class = str
        elif target_type is Attribute.TYPE.INT:
            cast_class = int
        elif target_type is Attribute.TYPE.FLOAT:
            cast_class = float
        elif target_type is Attribute.TYPE.DATETIME:
            cast_class = datetime.datetime
        elif target_type is Attribute.TYPE.DATE:
            cast_class = datetime.date
        elif target_type is Attribute.TYPE.BOOLEAN:
            cast_class = bool
        else:
            return entry

        return AvishanModel.cast_type_data(cast_class, entry)
Ejemplo n.º 10
0
    def faker_assign_faking_method(cls, key: str,
                                   value: Parameter) -> Callable:
        from avishan.models import AvishanModel

        if not isinstance(value, Parameter):
            raise ValueError(
                f'parameter {key} in class {cls.__name__} should have type hint to fake it.'
            )
        if key == 'kwargs':
            raise ValueError(f'kwargs in class {cls.__name__} is not valid')

        if value.default is None:
            return lambda: None

        if isinstance(value.annotation, models.base.ModelBase):
            if issubclass(value.annotation, AvishanModel):
                return lambda: value.annotation.fake_it()
            raise NotImplementedError()

        try:
            return {
                bool: cls._bool_fake,
                str: cls._str_fake,
                int: cls._int_fake,
                float: cls._float_fake,
                datetime: cls._datetime_fake,
                date: cls._date_fake,
                time: cls._time_fake
            }[value.annotation]
        except KeyError:
            pass

        if isinstance(value.annotation.__args__[0], ForwardRef):
            list_of = AvishanModel.get_model_with_class_name(
                value.annotation.__args__[0].__forward_arg__)
        else:
            list_of = value.annotation.__args__[0]
        return lambda: list_of.fake_list()
Ejemplo n.º 11
0
from django.db import models

from avishan.models import AvishanModel


def maker(source: list) -> list:
    output = []
    for item in source:
        if isinstance(item, models.Field):
            output.append(item.name)
        else:
            output.append(item)
    return output


for model in AvishanModel.get_non_abstract_models():
    model: AvishanModel
    model_admin_dict = {
        'list_filter': maker(model.django_admin_list_filter),
        'list_max_show_all': model.django_admin_list_max_show_all,
        'list_per_page': model.django_admin_list_per_page,
        'raw_id_fields': maker(model.django_admin_raw_id_fields),
        'readonly_fields': maker(model.django_admin_readonly_fields),
        'search_fields': maker(model.django_admin_search_fields),
    }
    for field in model.get_full_fields():
        if isinstance(field, models.DateField) and (field.auto_now_add
                                                    or field.auto_now):
            model_admin_dict['readonly_fields'].append(field.name)
    if model.django_admin_date_hierarchy:
        model_admin_dict['date_hierarchy'] = model.django_admin_date_hierarchy
Ejemplo n.º 12
0
 def get_redoc_schema_models(cls):
     from avishan.models import AvishanModel
     return AvishanModel.get_non_abstract_models()
Ejemplo n.º 13
0
 def get_model_with_class_name(class_name: str) -> Optional[type]:
     from avishan.models import AvishanModel
     for item in AvishanModel.get_models():
         if item.class_name() == class_name:
             return item
     return None
Ejemplo n.º 14
0
 def get_non_abstract_models(app_name: str = None) -> List[type]:
     from avishan.models import AvishanModel
     return [x for x in AvishanModel.get_models(app_name) if x._meta.abstract is False]
Ejemplo n.º 15
0
 def all_subclasses(parent_class):
     from avishan.models import AvishanModel
     return set(parent_class.__subclasses__()).union(
         [s for c in parent_class.__subclasses__() for s in AvishanModel.all_subclasses(c)])