Ejemplo n.º 1
0
    def test_20_jinja2ext_cache(self):
        somevar = ''.join([random.choice(string.ascii_letters) for x in range(6)])

        testkeys = [
            make_template_fragment_key("fragment1"),
            make_template_fragment_key("fragment1", vary_on=["key1"]),
            make_template_fragment_key("fragment1", vary_on=["key1", somevar])
        ]
        delkey = make_template_fragment_key("fragment2")

        with self.app.test_request_context():
            # Test if elements are cached
            render_template("test_template.html", somevar=somevar, timeout=60)
            for k in testkeys:
                assert self.cache.get(k) == somevar
            assert self.cache.get(delkey) == somevar

            # Test timeout=del to delete key
            render_template("test_template.html", somevar=somevar, timeout="del")
            for k in testkeys:
                assert self.cache.get(k) == somevar
            assert self.cache.get(delkey) is None

            # Test rendering templates from strings
            output = render_template_string(
                """{% cache 60 "fragment3" %}{{somevar}}{% endcache %}""",
                somevar=somevar
            )
            assert self.cache.get(make_template_fragment_key("fragment3")) == somevar
            assert output == somevar
Ejemplo n.º 2
0
    def test_20_jinja2ext_cache(self):
        somevar = ''.join(
            [random.choice(string.ascii_letters) for x in range(6)])

        testkeys = [
            make_template_fragment_key("fragment1"),
            make_template_fragment_key("fragment1", vary_on=["key1"]),
            make_template_fragment_key("fragment1", vary_on=["key1", somevar])
        ]
        delkey = make_template_fragment_key("fragment2")

        with self.app.test_request_context():
            # Test if elements are cached
            render_template("test_template.html", somevar=somevar, timeout=60)
            for k in testkeys:
                assert self.cache.get(k) == somevar
            assert self.cache.get(delkey) == somevar

            # Test timeout=del to delete key
            render_template("test_template.html",
                            somevar=somevar,
                            timeout="del")
            for k in testkeys:
                assert self.cache.get(k) == somevar
            assert self.cache.get(delkey) is None

            # Test rendering templates from strings
            output = render_template_string(
                """{% cache 60 "fragment3" %}{{somevar}}{% endcache %}""",
                somevar=somevar)
            assert self.cache.get(
                make_template_fragment_key("fragment3")) == somevar
            assert output == somevar
Ejemplo n.º 3
0
    def post_edit(self, id):
        """ Post Route for Edit an item
            TODO: Ability to edit title/url for posts
        """
        commentForm = self._commentForm(request)
        item = Item.query.get_or_404(id)
        if commentForm.validate_on_submit():
            item.text = self._clean_text(commentForm.text.data)
            item.last_changed = datetime.utcnow()
            item = db.session.merge(item)
            db.session.commit()

            #TODO: Delete only necessary items
            cache.delete_memoized(Item.get_children)
            cache.delete_memoized(Item.get_item_and_children)
            key = make_template_fragment_key("item_text", vary_on=[item.__str__(), item.changed])
            cache.delete(key)

            flash('Edit saved', 'info')
            response = make_response(render_template('item/item.html',
                        item = item, form = commentForm, title=item.title, edit=True))
            next_url = url_for('frontend.item_edit', id=item.id)

            response.headers['X-PJAX-URL'] = next_url
            return response
        else:
            return render_template('item/item.html',
                        item = item, form = commentForm, title=item.title, edit=True)
Ejemplo n.º 4
0
def make_redis_cache_key(cache_prefix, category=''):
    user_id = 'ANONYMOUS'
    if current_user.is_authenticated():
        user_id = current_user.string_id
    cache_key = make_template_fragment_key(cache_prefix,
        vary_on=[user_id, category])
    # Add prefix to the cache key and a *
    return '{0}{1}*'.format(app.config['CACHE_KEY_PREFIX'], cache_key)
Ejemplo n.º 5
0
def invalidate_jinja2_cache(sender, collection=None, lang=None, **extra):
    """
    Invalidate collection cache
    """
    from invenio.ext.cache import cache
    if lang is None:
        lang = current_app.config['CFG_SITE_LANG']
    cache.delete(make_template_fragment_key(collection.name, vary_on=[lang]))
Ejemplo n.º 6
0
def invalidate_jinja2_cache(sender, collection=None, lang=None, **extra):
    """
    Invalidate collection cache
    """
    from invenio.ext.cache import cache
    if lang is None:
        lang = current_app.config['CFG_SITE_LANG']
    cache.delete(make_template_fragment_key(collection.name, vary_on=[lang]))
Ejemplo n.º 7
0
def make_redis_cache_key(cache_prefix, category=''):
    user_id = 'ANONYMOUS'
    if current_user.is_authenticated():
        user_id = current_user.string_id
    cache_key = make_template_fragment_key(cache_prefix,
                                           vary_on=[user_id, category])
    # Add prefix to the cache key and a *
    return '{0}{1}*'.format(app.config['CACHE_KEY_PREFIX'], cache_key)
Ejemplo n.º 8
0
def delete_redis_cache_post(uuid, user_id=None, all_users=False):
    if all_users:
        cache_key = make_template_fragment_key('post', vary_on=[uuid])
    else:
        if user_id:
            user_id = str(user_id)
        else:
            if current_user.is_authenticated():
                user_id = current_user.string_id
            else:
                user_id = "ANONYMOUS"

        cache_key = make_template_fragment_key('post', vary_on=[uuid, user_id])

    # Add prefix to the cache key
    if not redis_client:
        return
    key = '{0}{1}*'.format(app.config['CACHE_KEY_PREFIX'], cache_key)
    keys_list = redis_client.keys(key)
    for key in keys_list:
        redis_client.delete(key)
Ejemplo n.º 9
0
def delete_redis_cache_template(template_item,
                                uuid,
                                user_id=None,
                                all_users=True):
    """Delete a redis cached template fragment. Supports various options for
    filtering the right keys.

    :type template_item: string
    :param template_item: Prefix for the template, e.g. 'node_view'

    :type uuid: string
    :param uuid: The unique identifier for the item displayed in the template.
        Usually the string version of the Node ObjectID.

    :type user_id: string
    :param user_id: User ID cache, use for filtering per-user caches (useful to
        display cached rating pages)
    """
    if all_users:
        cache_key = make_template_fragment_key(template_item, vary_on=[uuid])
    else:
        if user_id:
            user_id = str(user_id)
        else:
            if current_user.is_authenticated():
                user_id = current_user.string_id
            else:
                user_id = "ANONYMOUS"

        cache_key = make_template_fragment_key(template_item,
                                               vary_on=[uuid, user_id])

    # Add prefix to the cache key
    if not redis_client:
        return
    key = '{0}{1}*'.format(app.config['CACHE_KEY_PREFIX'], cache_key)
    keys_list = redis_client.keys(key)
    for key in keys_list:
        redis_client.delete(key)
Ejemplo n.º 10
0
def delete_redis_cache_post(uuid, user_id=None, all_users=False):
    if all_users:
        cache_key = make_template_fragment_key('post',
            vary_on=[uuid])
    else:
        if user_id:
            user_id = str(user_id)
        else:
            if current_user.is_authenticated():
                user_id = current_user.string_id
            else:
                user_id = "ANONYMOUS"

        cache_key = make_template_fragment_key('post',
            vary_on=[uuid, user_id])

    # Add prefix to the cache key
    if not redis_client:
        return
    key = '{0}{1}*'.format(app.config['CACHE_KEY_PREFIX'], cache_key)
    keys_list = redis_client.keys(key)
    for key in keys_list: redis_client.delete(key)
Ejemplo n.º 11
0
class CacheExtension(Extension):
    tags = set(['cache'])

    def parse(self, parser):
        lineno = parser.stream.next().lineno

        #: Parse timeout
        args = [parser.parse_expression()]

        #: Parse fragment name
        #: Grab the fragment name if it exists
        #: otherwise, default to the old method of using the templates
        #: lineno to maintain backwards compatibility.
        if parser.stream.skip_if('comma'):
            args.append(parser.parse_expression())
        else:
            args.append(nodes.Const("%s%s" % (parser.filename, lineno)))

        #: Parse vary_on parameters
        vary_on = []
        while parser.stream.skip_if('comma'):
            vary_on.append(parser.parse_expression())

        if vary_on:
            args.append(nodes.List(vary_on))
        else:
            args.append(nodes.Const([]))

        body = parser.parse_statements(['name:endcache'], drop_needle=True)
        return nodes.CallBlock(self.call_method('_cache', args), [], [],
                               body).set_lineno(lineno)

    def _cache(self, timeout, fragment_name, vary_on, caller):
        try:
            cache = getattr(self.environment, JINJA_CACHE_ATTR_NAME)
        except AttributeError, e:
            raise e

        key = make_template_fragment_key(fragment_name, vary_on=vary_on)

        #: Delete key if timeout is 'del'
        if timeout == "del":
            cache.delete(key)
            return caller()

        rv = cache.get(key)
        if rv is None:
            rv = caller()
            cache.set(key, rv, timeout)
        return rv
Ejemplo n.º 12
0
def delete_redis_cache_template(template_item, uuid, user_id=None, all_users=True):
    """Delete a redis cached template fragment. Supports various options for
    filtering the right keys.

    :type template_item: string
    :param template_item: Prefix for the template, e.g. 'node_view'

    :type uuid: string
    :param uuid: The unique identifier for the item displayed in the template.
        Usually the string version of the Node ObjectID.

    :type user_id: string
    :param user_id: User ID cache, use for filtering per-user caches (useful to
        display cached rating pages)
    """
    if all_users:
        cache_key = make_template_fragment_key(template_item,
            vary_on=[uuid])
    else:
        if user_id:
            user_id = str(user_id)
        else:
            if current_user.is_authenticated():
                user_id = current_user.string_id
            else:
                user_id = "ANONYMOUS"

        cache_key = make_template_fragment_key(template_item,
            vary_on=[uuid, user_id])

    # Add prefix to the cache key
    if not redis_client:
        return
    key = '{0}{1}*'.format(app.config['CACHE_KEY_PREFIX'], cache_key)
    keys_list = redis_client.keys(key)
    for key in keys_list: redis_client.delete(key)
Ejemplo n.º 13
0
    def _cache(self, timeout, fragment_name, vary_on,  caller):
        try:
            cache = getattr(self.environment, JINJA_CACHE_ATTR_NAME)
        except AttributeError as e:
            raise e

        key = make_template_fragment_key(fragment_name, vary_on=vary_on)

        #: Delete key if timeout is 'del'
        if timeout == "del":
            cache.delete(key)
            return caller()

        rv = cache.get(key)
        if rv is None:
            rv = caller()
            cache.set(key, rv, timeout)
        return rv
Ejemplo n.º 14
0
    def _cache(self, timeout, fragment_name, vary_on, caller):
        try:
            cache = getattr(self.environment, JINJA_CACHE_ATTR_NAME)
        except AttributeError as e:
            raise e

        key = make_template_fragment_key(fragment_name, vary_on=vary_on)

        #: Delete key if timeout is 'del'
        if timeout == "del":
            cache.delete(key)
            return caller()

        rv = cache.get(key)
        if rv is None:
            rv = caller()
            cache.set(key, rv, timeout)
        return rv
Ejemplo n.º 15
0
    def post(self, name):
        """ Submit changes for user.
            NOT used to create a new user (that is done via flask-security)
        """
        user = User.find_user_by_name(name).first_or_404()
        form = UserForm()
        if user == current_user and form.validate_on_submit(): 
            old_name = current_user.name
            if form.email.data != '':   
                user.email = form.email.data
            user.name = form.name.data
            user.twitter_handle = form.twitter.data
            db.session.commit()

            key = make_template_fragment_key("user", vary_on=[old_name])
            cache.delete(key)

            flash('Your edits are saved, thanks.', category = 'info')
            return redirect(url_for('.user', name=form.name.data)) 
Ejemplo n.º 16
0
    def post(self, name):
        """ Submit changes for user.
            NOT used to create a new user (that is done via flask-security)
        """
        user = User.find_user_by_name(name).first_or_404()
        form = UserForm()
        if user == current_user and form.validate_on_submit():
            old_name = current_user.name
            if form.email.data != '':
                user.email = form.email.data
            user.name = form.name.data
            user.twitter_handle = form.twitter.data
            db.session.commit()

            key = make_template_fragment_key("user", vary_on=[old_name])
            cache.delete(key)

            flash('Your edits are saved, thanks.', category='info')
            return redirect(url_for('.user', name=form.name.data))
Ejemplo n.º 17
0
    def post_edit(self, id):
        """ Post Route for Edit an item
            TODO: Ability to edit title/url for posts
        """
        commentForm = self._commentForm(request)
        item = Item.query.get_or_404(id)
        if commentForm.validate_on_submit():
            item.text = self._clean_text(commentForm.text.data)
            item.last_changed = datetime.utcnow()
            item = db.session.merge(item)
            db.session.commit()

            #TODO: Delete only necessary items
            cache.delete_memoized(Item.get_children)
            cache.delete_memoized(Item.get_item_and_children)
            key = make_template_fragment_key(
                "item_text", vary_on=[item.__str__(), item.changed])
            cache.delete(key)

            flash('Edit saved', 'info')
            response = make_response(
                render_template('item/item.html',
                                item=item,
                                form=commentForm,
                                title=item.title,
                                edit=True))
            next_url = url_for('frontend.item_edit', id=item.id)

            response.headers['X-PJAX-URL'] = next_url
            return response
        else:
            return render_template('item/item.html',
                                   item=item,
                                   form=commentForm,
                                   title=item.title,
                                   edit=True)