コード例 #1
0
ファイル: crookbook.py プロジェクト: the-allanc/crookbook
    def described_maker(cls):
        def repr_(self):
            return ('<{0.__class__.__name__} ' + inner + '>').format(self)

        setattr(cls, '__repr__', repr_)

        if '__str__' not in cls.__dict__:

            def str_(self):
                return repr(self)

            setattr(cls, '__str__', str_)

        return six.python_2_unicode_compatible(cls)
コード例 #2
0
    def create_history_m2m_model(self, model, through_model):
        attrs = {
            "__module__": self.module,
            "__str__": lambda self: "{} as of {}".format(
                self._meta.verbose_name, self.history.history_date
            ),
        }

        app_module = "%s.models" % model._meta.app_label

        if model.__module__ != self.module:
            # registered under different app
            attrs["__module__"] = self.module
        elif app_module != self.module:
            # Abuse an internal API because the app registry is loading.
            app = apps.app_configs[model._meta.app_label]
            models_module = app.name
            attrs["__module__"] = models_module

        # Get the primary key to the history model this model will look up to
        attrs["m2m_history_id"] = self._get_history_id_field()
        attrs["history"] = models.ForeignKey(
            model, db_constraint=False, on_delete=models.DO_NOTHING,
        )

        fields = self.copy_fields(through_model)
        attrs.update(fields)

        name = self.get_history_model_name(through_model)
        registered_models[through_model._meta.db_table] = through_model
        meta_fields = {"verbose_name": name}

        if self.app:
            meta_fields["app_label"] = self.app

        attrs.update(Meta=type(str("Meta"), (), meta_fields))

        m2m_history_model = type(str(name), (models.Model,), attrs)

        return (
            python_2_unicode_compatible(m2m_history_model)
            if django.VERSION < (2,)
            else m2m_history_model
        )
コード例 #3
0
def Sinopsis(txt):
    OPEN = six.ensure_str(txt, 'utf-8')
    try:
        # try:
        #     if 'Plot:' in OPEN:
        #         Sinopsis = re.findall('(Plot:.+?)</p>', OPEN, re.DOTALL)[0]
        #     else:
        #         Sinopsis = re.findall('</p>\n<p>(.+?)</p><p>', OPEN, re.DOTALL)[0]
        #
        # except:
        #     Sinopsis = re.findall('</p>\n<p>(.+?)</p>\n<p style', OPEN, re.DOTALL)[0]
        part = re.sub('<.*?>', '', OPEN)
        part = re.sub(r'\.\s+', '.', part)
        desc = clear_Title(part)
        if six.PY2:
            desc = desc.decode('ascii', errors='ignore')
        else:
            desc = six.python_2_unicode_compatible(six.ensure_str(desc))
        return desc
    except BaseException:
        return 'N/A'
コード例 #4
0
    def save(self, *args, **kwargs):
        if not self.key:
            self.key = self.generate_key()
        return super(RefreshToken, self).save(*args, **kwargs)

    def generate_key(self):
        return binascii.hexlify(os.urandom(20)).decode()

    def revoke(self):
        self.delete()
        return self.__class__.objects.create(user=self.user, app=self.app)

    def __str__(self):
        return self.key

    def __repr__(self):
        return 'RefreshToken(pk=%r, key=%r, user=%r, app=%r, created=%r)' % (
            self.pk,
            self.key,
            getattr(self, 'user', None),
            self.app,
            self.created,
        )


try:
    from six import python_2_unicode_compatible
    RefreshToken = python_2_unicode_compatible(RefreshToken)
except:
    pass
コード例 #5
0
ファイル: models.py プロジェクト: sourcery-ai-bot/feincms
        def _create_content_base(cls):
            """
            This is purely an internal method. Here, we create a base class for
            the concrete content types, which are built in
            ``create_content_type``.

            The three fields added to build a concrete content type class/model
            are ``parent``, ``region`` and ``ordering``.
            """

            # We need a template, because of the possibility of restricting
            # content types to a subset of all available regions. Each region
            # object carries a list of all allowed content types around.
            # Content types created before a region is initialized would not be
            # available in the respective region; we avoid this problem by
            # raising an ImproperlyConfigured exception early.
            cls._needs_templates()

            class Meta:
                abstract = True
                app_label = cls._meta.app_label
                ordering = ["ordering"]

            def __str__(self):
                return (
                    "%s<pk=%s, parent=%s<pk=%s, %s>, region=%s," " ordering=%d>"
                ) % (
                    self.__class__.__name__,
                    self.pk,
                    self.parent.__class__.__name__,
                    self.parent.pk,
                    self.parent,
                    self.region,
                    self.ordering,
                )

            def render(self, **kwargs):
                """
                Default render implementation, tries to call a method named
                after the region key before giving up.

                You'll probably override the render method itself most of the
                time instead of adding region-specific render methods.
                """

                render_fn = getattr(self, "render_%s" % self.region, None)

                if render_fn:
                    return render_fn(**kwargs)

                raise NotImplementedError

            def get_queryset(cls, filter_args):
                return cls.objects.select_related().filter(filter_args)

            attrs = {
                # The basic content type is put into
                # the same module as the CMS base type.
                # If an app_label is not given, Django
                # needs to know where a model comes
                # from, therefore we ensure that the
                # module is always known.
                "__module__": cls.__module__,
                "__str__": __str__,
                "render": render,
                "get_queryset": classmethod(get_queryset),
                "Meta": Meta,
                "parent": models.ForeignKey(
                    cls, related_name="%(class)s_set", on_delete=models.CASCADE
                ),
                "region": models.CharField(max_length=255),
                "ordering": models.IntegerField(_("ordering"), default=0),
            }

            # create content base type and save reference on CMS class

            name = "_Internal%sContentTypeBase" % cls.__name__
            if hasattr(sys.modules[cls.__module__], name):
                warnings.warn(
                    "The class %s.%s has the same name as the class that "
                    "FeinCMS auto-generates based on %s.%s. To avoid database"
                    "errors and import clashes, rename one of these classes."
                    % (cls.__module__, name, cls.__module__, cls.__name__),
                    RuntimeWarning,
                )

            cls._feincms_content_model = six.python_2_unicode_compatible(
                type(str(name), (models.Model,), attrs)
            )

            # list of concrete content types
            cls._feincms_content_types = []

            # list of concrete content types having methods which may be called
            # before or after rendering the content:
            #
            # def process(self, request, **kwargs):
            #     May return a response early to short-circuit the
            #     request-response cycle
            #
            # def finalize(self, request, response)
            #     May modify the response or replace it entirely by returning
            #     a new one
            #
            cls._feincms_content_types_with_process = []
            cls._feincms_content_types_with_finalize = []

            # list of item editor context processors, will be extended by
            # content types
            if hasattr(cls, "feincms_item_editor_context_processors"):
                cls.feincms_item_editor_context_processors = list(
                    cls.feincms_item_editor_context_processors
                )
            else:
                cls.feincms_item_editor_context_processors = []

            # list of templates which should be included in the item editor,
            # will be extended by content types
            if hasattr(cls, "feincms_item_editor_includes"):
                cls.feincms_item_editor_includes = dict(
                    cls.feincms_item_editor_includes
                )
            else:
                cls.feincms_item_editor_includes = {}
コード例 #6
0
    def _ufl_type_decorator_(cls):
        # Determine integer typecode by oncrementally counting all types
        typecode = Expr._ufl_num_typecodes_
        Expr._ufl_num_typecodes_ += 1

        # Determine handler name by a mapping from "TypeName" to "type_name"
        handler_name = camel2underscore(cls.__name__)

        # is_scalar implies is_index_free
        if is_scalar:
            _is_index_free = True
        else:
            _is_index_free = is_index_free

        # Store type traits
        cls._ufl_class_ = cls
        set_trait(cls, "handler_name", handler_name, inherit=False)
        set_trait(cls, "typecode", typecode, inherit=False)
        set_trait(cls, "is_abstract", is_abstract, inherit=False)

        set_trait(cls, "is_terminal", is_terminal, inherit=True)
        set_trait(cls, "is_literal", is_literal, inherit=True)
        set_trait(cls, "is_terminal_modifier", is_terminal_modifier,
                  inherit=True)
        set_trait(cls, "is_shaping", is_shaping, inherit=True)
        set_trait(cls, "is_in_reference_frame", is_in_reference_frame,
                  inherit=True)
        set_trait(cls, "is_restriction", is_restriction, inherit=True)
        set_trait(cls, "is_evaluation", is_evaluation, inherit=True)
        set_trait(cls, "is_differential", is_differential, inherit=True)

        set_trait(cls, "is_scalar", is_scalar, inherit=True)
        set_trait(cls, "is_index_free", _is_index_free, inherit=True)

        # Number of operands can often be determined automatically
        _num_ops = determine_num_ops(cls, num_ops, unop, binop, rbinop)
        set_trait(cls, "num_ops", _num_ops)

        # Attach builtin type wrappers to Expr
        """# These are currently handled in the as_ufl implementation in constantvalue.py
        if wraps_type is not None:
            if not isinstance(wraps_type, type):
                msg = "Expecting a type, not a {0.__name__} for the wraps_type argument in definition of {1.__name__}."
                raise TypeError(msg.format(type(wraps_type), cls))

            def _ufl_from_type_(value):
                return cls(value)
            from_type_name = "_ufl_from_{0}_".format(wraps_type.__name__)
            setattr(Expr, from_type_name, staticmethod(_ufl_from_type_))
        """

        # Attach special function to Expr.
        # Avoids the circular dependency problem of making
        # Expr.__foo__ return a Foo that is a subclass of Expr.
        """# These are currently attached in exproperators.py
        if unop:
            def _ufl_expr_unop_(self):
                return cls(self)
            setattr(Expr, unop, _ufl_expr_unop_)
        if binop:
            def _ufl_expr_binop_(self, other):
                try:
                    other = Expr._ufl_coerce_(other)
                except:
                    return NotImplemented
                return cls(self, other)
            setattr(Expr, binop, _ufl_expr_binop_)
        if rbinop:
            def _ufl_expr_rbinop_(self, other):
                try:
                    other = Expr._ufl_coerce_(other)
                except:
                    return NotImplemented
                return cls(other, self)
            setattr(Expr, rbinop, _ufl_expr_rbinop_)
        """

        # Make sure every non-abstract class has its own __hash__ and
        # __eq__.  Python 3 will set __hash__ to None if cls has
        # __eq__, but we've implemented it in a separate function and
        # want to inherit/use that for all types. Allow overriding by
        # setting use_default_hash=False.
        if use_default_hash:
            cls.__hash__ = compute_expr_hash

        # FIXME: Apply this if everything beomes unicode
        if 0:
            cls = six.python_2_unicode_compatible(cls)

        # NB! This function conditionally adds some methods to the
        # class!  This approach significantly reduces the amount of
        # small functions to implement across all the types but of
        # course it's a bit more opaque.
        attach_implementations_of_indexing_interface(cls,
                                                     inherit_shape_from_operand,
                                                     inherit_indices_from_operand)

        # Update Expr
        update_global_expr_attributes(cls)

        # Apply a range of consistency checks to detect bugs in type
        # implementations that Python doesn't check for us, including
        # some checks that a static language compiler would do for us
        check_abstract_trait_consistency(cls)
        check_has_slots(cls)
        check_is_terminal_consistency(cls)
        check_implements_required_methods(cls)
        check_implements_required_properties(cls)
        check_type_traits_consistency(cls)

        return cls