示例#1
0
class ContentAccessors(object):
    """
    A mixin class for response objects that provides a couple of useful
    accessors for unittesting.
    """
    def xml(self):
        """Get an etree if possible."""
        if 'xml' not in self.mimetype:
            raise AttributeError('Not a XML response (Content-Type: %s)' %
                                 self.mimetype)
        for module in [
                'xml.etree.ElementTree', 'ElementTree',
                'elementtree.ElementTree'
        ]:
            etree = import_string(module, silent=True)
            if etree is not None:
                return etree.XML(self.body)

        raise RuntimeError(
            'You must have ElementTree installed to use TestResponse.xml')

    xml = cached_property(xml)

    def lxml(self):
        """Get an lxml etree if possible."""
        if 'html' not in self.mimetype and 'xml' not in self.mimetype:
            raise AttributeError('Not an HTML/XML response')
        from lxml import etree
        try:
            from lxml.html import fromstring
        except ImportError:
            fromstring = etree.HTML

        if self.mimetype == 'text/html':
            return fromstring(self.data)
        return etree.XML(self.data)

    lxml = cached_property(lxml)

    def json(self):
        """Get the result of simplejson.loads if possible."""
        if 'json' not in self.mimetype:
            raise AttributeError('Not a JSON response')
        try:
            from simplejson import loads
        except:
            from json import loads

        return loads(self.data)

    json = cached_property(json)
示例#2
0
 def node(cls):
     """
     Link back to node
     """
     parentclass.workflow_revision = cached_property(lambda self: ProxyDict(
         self, 'revisions', cls, 'workflow_label', 'node'))
     return relationship(parentclass, backref=backref('revisions', lazy='dynamic', cascade='all, delete-orphan'))
示例#3
0
            ~User.id.in_(db.session.query(JobApplication.replied_by_id).filter(
                JobApplication.replied_by_id != None, JobApplication.replied_at >= datetime.utcnow() - agelimit)),
            ~User.id.in_(db.session.query(JobPost.user_id).filter(
                JobPost.user_id != None, JobPost.created_at >= datetime.utcnow() - newlimit))
            )  # NOQA
        )

    # One-way flags (no elegant way to do a reverse query)

    has_boards = UserFlag('admin',
        __("Has a sub-board"),
        lambda user: Board.query.filter(
            Board.userid.in_(user.user_organizations_owned_ids())
            ).notempty(),
        None
        )


def _user_flags(self):
    cache_key = 'user/flags/' + str(self.id)
    flags = cache.get(cache_key)
    if not flags:
        flags = {}
        for key, func in UserFlags.__dict__.items():
            if isinstance(func, UserFlag):
                flags[key] = func.for_user(self)
        cache.set(cache_key, flags, timeout=3600)  # Cache for one hour
    return flags

User.flags = cached_property(_user_flags)
示例#4
0
    kind = f(unicode, required=True, choices=CONTACT_TYPES, default='text')
    scope = f(unicode, choices=CONTACT_SCOPES, default=CONTACT_SCOPES[0])
    value = f(unicode, required=True)

    # XXX validators?

    """
    # contact data; maybe should be references.
    # also validators should be added.
    email = f(unicode)
    phone = f(unicode,
              default=lambda d: d.phone_mobile or d.phone_home or d.phone_work)
    phone_mobile = f(unicode)
    phone_home = f(unicode)
    phone_work = f(unicode)
    url = f(unicode)
    """

    def __unicode__(self):
        return u'{summary} {kind} {value} ({scope})'.format(**self)

# class Actor(...):
#    @cached_property
#    def contacts(self):
#        db = self._saved_state.storage
#        return Contact.objects(db).where(actor=self.pk)

# TODO use Docu's reverse relationship API when it's ready
Actor.contacts = cached_property(lambda self: Contact.objects(self._saved_state.storage).where(actor=self.pk))