Example #1
0
 def __init__(self, relation=None, **kwargs):
     super().__init__(**kwargs)
     self.relation = relation
     self.sqlrelation = db.relationship(relation)
     self.query = lambda: db.session.query(relation)
     self.widget = AsyncFileUploadWidget(
         relation=self.relation,
         query=self.query
     )
Example #2
0
class GalleryImage(OrderableMixin, DataObject, db.Model):
    caption = db.Column(db.String(250))
    image_id = db.Column(db.ForeignKey(FileObject.id))
    image = db.relationship("FileObject")

    page_id = db.Column(db.ForeignKey("superpage.id"))
    page = db.relationship("SuperPage")

    @classmethod
    def get_cms_form(cls):
        form = Form
        form.caption = fields.StringField("Caption")
        form.image_id = AsyncFileUploadField(relation=ImageObject)
        form.page_id = fields.IntegerField()
        form.submit = fields.SubmitField("Submit")
        return form

    def __init__(self):
        self.init_order()
Example #3
0
def create_live_table(cls):

    tablename = cls.__tablename__ + "_live"
    if tablename in created_tables or cls.__tablename__ in created_tables:
        return
    created_tables.append(tablename)
    columns = []

    print("Creating Live table for: %s" % cls.__tablename__)

    ins = sainspect(cls)

    versioned_basetable = tablename
    baseclass = tuple()
    for c in inspect.getmro(cls):
        if c != cls and c.__name__ in versioned_classes:
            versioned_basetable = c.__table__.name + "_live"
            baseclass = (c.LiveType, ) + baseclass
        elif c != cls and c.__name__ != "VersionedMixin":
            baseclass = (c, ) + baseclass

    # Reverse baseclass mro
    baseclass = baseclass[::-1]


    for c in cls.__table__.columns:
        # What is happening
        # TODO: Check if this also works with different relationships...
        new_keys = []
        if c.foreign_keys:
            for k in c.foreign_keys:
                key_target = k.column.table.name
                if key_target in versioned_tables:
                    new_keys.append(db.ForeignKey(key_target + "_live." + k.column.key))
                else:
                    new_keys.append(db.ForeignKey(k.target_fullname))

            columns.append(db.Column(c.key, db.Integer(),
                                     new_keys[0],
                                     primary_key=c.primary_key,
                                     default=c.default))
        else:
            columns.append(c.copy())

    cls.LiveTable = table = sa.schema.Table(
        tablename,
        cls.__table__.metadata,
        *columns
    )

    args = {}

    for key, value in cls.__dict__.items():
        if type(value) is types.FunctionType:
            args.update({key: value})

    args.update({
        "__table__": table
    })

    for column in columns:
        args[column.name] = column

    backrefs = []
    rs = [r for r in ins.relationships]
    for r in rs:
        if r.parent == cls.__mapper__:
            print("There is a relation defined %s with Key: %r" % (cls.__name__, r))
            print(r.target)
            if hasattr(r.target, 'fullname') and r.target.fullname.endswith("version"):
                continue

            if r.key in backrefs:
                continue

            key = r.key
            target = ""
            if hasattr(r.target, 'fullname') and r.target.fullname in versioned_tables:
                target = r.mapper.entity.__name__ + "Live"
            else:
                if r.direction == MANYTOONE:
                    args[key] = db.relationship(r.mapper)
                else:
                    primaryjoin = copy.copy(r.primaryjoin)
                    primaryjoin.left = args[primaryjoin.left.key]
                    args[key] = db.relationship(r.mapper,
                                                viewonly=True,
                                                primaryjoin=primaryjoin,
                                                foreign_keys=[primaryjoin.right])
                continue

            if hasattr(r, "backref") and r.backref:
                print(r.backref)
                backref_key = r.backref[0]
                backrefs.append(backref_key)
                backref = r.backref[1]
                print(backref["remote_side"].arg)
                remote_side = None
                if hasattr(backref["remote_side"].cls, "LiveType") or backref["remote_side"].cls == cls:
                    orig_arg = backref["remote_side"].arg
                    arg_v = orig_arg.split(".")
                    arg_v[0] += "Live"
                    remote_side = ".".join(arg_v)
                    print(remote_side)
                    args[key] = db.relationship(target, backref=db.backref(backref_key, remote_side=remote_side), cascade="none, ")
                else:
                    args[key] = db.relationship(target, cascade="none, ")
            else:
                args[key] = db.relationship(target, cascade="none, ")

    if args.get("__create_live__"):
        del args["__create_live__"]

    if args.get("before_insert"): del args["before_insert"]
    if args.get("before_update"): del args["before_update"]
    if args.get("__versioned__"): del args["__versioned__"]

    args["template"] = getattr(cls, "template") if hasattr(cls, "template") else ""

    # print(methods)
    cls.LiveType = type(
        '%sLive' % cls.__name__,
        baseclass,
        args
    )
    cls.LiveType.__create_live__ = False
    mapper_args = {}
    if hasattr(cls, "__mapper_args__"):
        mapper_args = cls.__mapper_args__

    for key, arg in mapper_args.items():
        if key == "polymorphic_on":
            # remap column!
            mapper_args[key] = table.columns[arg.name]
        elif key == "polymorphic_identity":
            mapper_args[key] += "_live"

    live_mapper = mapper(cls, cls.LiveTable,
                         non_primary=True,
                         **mapper_args)

    cls.live_mapper = live_mapper
    return cls.LiveTable
Example #4
0
class SiteTree(VersionedMixin, PolymorphicMixin, OrderableMixin, DataObject,
               db.Model):
    """
    The SiteTree is the database model from which all pages have to inherit.
    It defines the parent/children relationships of the page tree.
    It also defines everything that's needed to get nice URL slugs working.
    """

    parent_id = db.Column(db.Integer, db.ForeignKey('sitetree.id'))
    name = db.Column(db.String)
    urlsegment = db.Column(db.String(250), nullable=False)

    template = "page.html"

    children = db.relationship(
        'SiteTree',
        cascade="all",
        # many to one + adjacency list - remote_side
        # is required to reference the 'remote'
        # column in the join condition.
        backref=db.backref("parent", remote_side='SiteTree.id'),
        order_by='SiteTree.sort_order')

    allowed_children = []
    can_be_root = True
    icon = 'glyphicon glyphicon-file'

    def get_siblings(self):
        return SiteTree.query.filter(SiteTree.parent_id == self.parent_id)

    @classmethod
    def default_template(cls):
        return cls.__name__.lower() + ".html"

    def parents(self):
        tree_el = self.parent
        parents = []
        while tree_el:
            parents.append(tree_el)
            tree_el = tree_el.parent
        return parents

    @staticmethod
    def get_sitetree(parent_id=None):
        base_page = SiteTree.query.filter(SiteTree.parent_id == parent_id)\
                                  .order_by(SiteTree.sort_order.asc())
        dest_list = []
        for p in base_page:
            dest_dict = {}
            SiteTree.recursive_build_tree(p, dest_dict)
            dest_list.append(dest_dict)
        return dest_list

    @staticmethod
    def recursive_build_tree(root_node, dest_dict):
        dest_dict.update(root_node.jqtree_dict())
        children = root_node.children
        if children:
            dest_dict['children'] = []
            for child in children:
                temp_dict = {}
                dest_dict['children'].append(temp_dict)
                SiteTree.recursive_build_tree(child, temp_dict)
        else:
            return

    @classmethod
    def get_cms_form(cls):
        form = super().get_cms_form()
        return form

    def append_child(self, child):
        self.children.append(child)

    def parent_at_level(self, level=1):
        level = level - 1
        parents = self.parents()
        n_parents = len(parents)
        if n_parents > level:
            return parents[level]
        if n_parents == level:
            return self
        else:
            return False

    def menu(self, level=1):
        # This returns the menu with
        # self as reference
        level = level - 1
        parents = self.parents()
        n_parents = len(parents)
        if n_parents > level:
            cls = self.__class__
            level_parent = parents[level]
            result = cls.query.filter(cls.parent_id == level_parent.id).all()
            return result
        if n_parents == level:
            return self.children
        else:
            return False

    def as_dict(self):
        d = dict()
        try:
            d = super().as_dict()
        except Exception as e:
            """
            This is due to problems with wsgi and reloading:
            http://stackoverflow.com/questions/9722343/python-super-behavior-not-dependable
            """
            for c in self.__class__.mro():
                if c != self.__class__:
                    super_object = super(c, self)
                    if hasattr(super_object, 'as_dict'):
                        d.update(super_object.as_dict())
        d.update({
            "parent_id": self.parent_id,
            "name": self.name,
            "type": self.type
        })
        return d

    def jqtree_dict(self):
        return {
            "text": self.name,
            "parent_id": self.parent_id,
            "created_on": self.created_on,
            "type": self.__class__.__name__,
            "li_attr": {
                "data-pageid": str(self.id)
            },
            "a_attr": {
                "href": url_for("PagesCMSController.edit_page",
                                page_id=self.id)
            }
        }

    @staticmethod
    def get_by_url(url, cls=None):
        if not cls:
            cls = SiteTree
        vars = url.split('/')
        node = cls.query.filter(cls.urlsegment == vars[0]).first()
        if not node:
            abort(404)

        for var in vars[1:]:
            node = cls.query.filter(cls.urlsegment == var,
                                    cls.parent_id == node.id).first()
            if not node:
                abort(404)
        return node

    def get_url(self):
        if self.urlsegment == current_app.config[
                "SILVERFLASK_HOME_URLSEGMENT"]:
            return "/"
        self_url = "/" + self.urlsegment
        url = ""
        el = self

        while el.parent:
            url = "/" + el.parent.urlsegment
            el = el.parent
        url += self_url
        return url

    def set_parent(self, parent_id):
        if not parent_id:
            if self.can_be_root:
                self.parent_id = None
                return
            else:
                raise Exception("This page type can not be a root node!")
        else:
            parent = SiteTree.query.get(int(parent_id))
            if parent:
                if hasattr(
                        parent, 'allowed_children'
                ) and self.__class__.__name__ in parent.allowed_children:
                    self.parent_id = parent_id
                else:
                    raise Exception("Parent not allowed!")
            else:
                raise Exception("Parent not existing!")
        return

    def __init__(self):
        pass
        # self.database.extend(super(SiteTree, self).database)

    @classmethod
    def create_slug(cls, target, id=None):
        possible_slug = slugify(target.name, to_lower=True)
        slug = possible_slug
        count = 0

        def get_query(target, slug, id=None):
            query = cls.query.filter(cls.parent_id == target.parent_id,
                                     cls.urlsegment == slug)
            if id:
                query = query.filter(cls.id != id)
            return query

        while get_query(target, slug, id).count() > 0:
            slug = "{0}-{1}".format(possible_slug, count)
        target.urlsegment = slug

    @classmethod
    def pagetypes(cls):
        polymorphic_map = cls.__mapper__.polymorphic_map
        sitetree_props = {}
        for mapper in polymorphic_map.values():
            if mapper.class_ != cls:
                mapped_class = mapper.class_
                sitetree_props[mapped_class.__name__] = {
                    'allowed_children': mapped_class.allowed_children,
                    'icon':
                    mapped_class.icon if mapped_class.icon else 'default'
                }
        return sitetree_props

    @classmethod
    def before_insert(cls, mapper, context, target):
        target.create_slug(target)

    @classmethod
    def before_update(cls, mapper, context, target):
        target.create_slug(target, target.id)
Example #5
0
def create_live_table(cls):
    tablename = cls.__tablename__ + "_live"
    if tablename in created_tables or cls.__tablename__ in created_tables:
        return
    created_tables.append(tablename)
    columns = []
    logger.debug("Creating Live table for: %s" % cls.__tablename__)

    ins = sainspect(cls)

    versioned_basetable = tablename
    baseclass = tuple()
    for c in inspect.getmro(cls):
        if c != cls and c.__name__ in versioned_classes:
            versioned_basetable = c.__table__.name + "_live"
            baseclass = (c.LiveType, ) + baseclass
        elif c != cls and c.__name__ != "VersionedMixin":
            baseclass = (c, ) + baseclass

    # Reverse baseclass mro
    baseclass = baseclass[::-1]

    for c in cls.__table__.columns:
        # What is happening
        # TODO: Check if this also works with different relationships...
        new_keys = []
        if c.foreign_keys:
            for k in c.foreign_keys:
                key_target = k.column.table.name
                if key_target in versioned_tables:
                    new_keys.append(
                        db.ForeignKey(key_target + "_live." + k.column.key))
                else:
                    new_keys.append(db.ForeignKey(k.target_fullname))

            columns.append(
                db.Column(c.key,
                          db.Integer(),
                          new_keys[0],
                          primary_key=c.primary_key,
                          default=c.default))
        else:
            columns.append(c.copy())

    cls.LiveTable = table = sa.schema.Table(tablename, cls.__table__.metadata,
                                            *columns)

    args = {}
    for key, value in cls.__dict__.items():
        if type(value) is types.FunctionType:
            args.update({key: value})

    args.update({"__table__": table})

    for column in columns:
        args[column.name] = column

    backrefs = []
    rs = [r for r in ins.relationships]
    for r in rs:
        if r.parent == cls.__mapper__:
            print("There is a relation defined %s with Key: %r" %
                  (cls.__name__, r))

            if hasattr(r.target,
                       'fullname') and r.target.fullname.endswith("version"):
                continue

            if r.key in backrefs:
                continue

            key = r.key
            target = ""
            if hasattr(r.target,
                       'fullname') and r.target.fullname in versioned_tables:
                target = r.mapper.entity.__name__ + "Live"
            else:
                if r.direction == MANYTOONE:
                    args[key] = db.relationship(r.mapper)
                elif r.direction == MANYTOMANY:
                    # if hasattr(r, 'secondary') and r.secondary:
                    #     print("SECONDARY for ... ", r)
                    #     kwargs['secondary'] = r.secondary
                    primaryjoin = copy.copy(r.primaryjoin)
                    primaryjoin.left = args[primaryjoin.left.key]
                    secondaryjoin = copy.copy(r.secondaryjoin)
                    args[key] = db.relationship(
                        r.mapper,
                        viewonly=True,
                        primaryjoin=primaryjoin,
                        foreign_keys=[primaryjoin.right, secondaryjoin.right],
                        secondary=r.secondary,
                        secondaryjoin=secondaryjoin)
                else:
                    primaryjoin = copy.copy(r.primaryjoin)
                    primaryjoin.left = args[primaryjoin.left.key]
                    args[key] = db.relationship(
                        r.mapper,
                        viewonly=True,
                        primaryjoin=primaryjoin,
                        foreign_keys=[primaryjoin.right])
                continue

            kwargs = {}
            if hasattr(r, "backref") and r.backref:
                backref_key = r.backref[0]
                backrefs.append(backref_key)
                backref = r.backref[1]
                remote_side = None
                if hasattr(backref["remote_side"].cls,
                           "LiveType") or backref["remote_side"].cls == cls:
                    orig_arg = backref["remote_side"].arg
                    arg_v = orig_arg.split(".")
                    arg_v[0] += "Live"
                    remote_side = ".".join(arg_v)
                    kwargs['backref'] = db.backref(backref_key,
                                                   remote_side=remote_side)

            args[key] = db.relationship(target, cascade="none, ", **kwargs)

    if args.get("before_insert"): del args["before_insert"]
    if args.get("before_update"): del args["before_update"]
    if args.get("__versioned__"): del args["__versioned__"]

    args["template"] = getattr(cls, "template") if hasattr(cls,
                                                           "template") else ""

    mapper_args = {}
    if hasattr(cls, "__mapper_args__"):
        mapper_args = cls.__mapper_args__

    args['__versioned_draft_class__'] = cls
    args['__create_live__'] = False

    cls.LiveType = type('%sLive' % cls.__name__, baseclass, args)

    cls.LiveType.__create_live__ = False

    for key, arg in mapper_args.items():
        if key == "polymorphic_on":
            mapper_args[key] = table.columns[arg]

    live_mapper = mapper(cls, cls.LiveTable, non_primary=True, **mapper_args)

    cls.live_mapper = live_mapper
    return cls.LiveTable
Example #6
0
class User(DataObject, UserMixin, db.Model):
    """
    The base User model. Defines the following fields:

    username = String, and unique,
    firstname, lastname = String

    email = String, unique

    The password is set with user.set_password("password"), and then stored with
    encryption.

    """
    username = db.Column(db.String, unique=True)

    firstname = db.Column(db.String)
    lastname = db.Column(db.String)

    email = db.Column(db.String, unique=True)

    password = db.Column(db.String)

    confirmed_at = db.Column(db.DateTime)
    is_enabled = db.Column(db.Boolean(), nullable=False, server_default='1')

    roles = db.relationship('Role',
                            secondary=UserRoles.__tablename__,
                            backref=db.backref('users', lazy='dynamic'))

    auto_form_exclude = DataObject.auto_form_exclude + [
        'confirmed_at', 'is_enabled'
    ]

    def __init__(self, username, password, email=None, is_enabled=True):
        self.username = username
        self.password = current_app.user_manager.hash_password(password)
        self.email = email
        self.is_enabled = is_enabled

    @property
    def name(self):
        return str(self.firstname) + " " + str(self.lastname)

    def is_authenticated(self):
        if isinstance(self, AnonymousUserMixin):
            return False
        else:
            return True

    def is_active(self):
        return True

    def is_anonymous(self):
        if isinstance(self, AnonymousUserMixin):
            return True
        else:
            return False

    def get_id(self):
        return self.id

    def __repr__(self):
        return '<User %r>' % self.username

    def set_password(self, new_password):
        self.password = current_app.user_manager.hash_password(new_password)

    def as_dict(self):
        d = super().as_dict()
        if d["password"]:
            del d["password"]
        d.update({"name": self.name})
        return d

    @classmethod
    def get_cms_form(cls):
        form = super().get_cms_form()
        roles = [(r.id, r.name) for r in db.session.query(Role).all()]
        form.add_to_tab(
            "Root.Main",
            fields.PasswordField("New Password", [
                validators.EqualTo('new_password_confirmation',
                                   message='Passwords must match')
            ],
                                 name='new_password'))
        form.add_to_tab(
            "Root.Main",
            fields.PasswordField("Repeat New Password",
                                 name='new_password_confirmation'))
        form.add_to_tab(
            "Root.Main",
            QuerySelectMultipleField('Role',
                                     query_factory=lambda: Role.query,
                                     get_label=lambda x: x.name,
                                     get_pk=lambda x: x.id,
                                     name='roles'))
        del form.fields["password"]
        return form