2
0
Эх сурвалжийг харах

Replace cache with wagtail-cache (#49)

* Removing cache functionality and replacing with wagtail-cache

* Updating to use wagtail-cache==0.2 and updating docs

* Update codered-editor.js
Vince Salvino 6 жил өмнө
parent
commit
422cfec696

+ 1 - 2
coderedcms/admin_urls.py

@@ -1,11 +1,10 @@
 from django.urls import include, path, re_path
 from wagtailimportexport import urls as wagtailimportexport_urls
 from wagtail.admin import urls as wagtailadmin_urls
-from coderedcms.views import clear_cache, import_pages_from_csv_file
+from coderedcms.views import import_pages_from_csv_file
 
 
 urlpatterns = [
-    path('codered/clearcache', clear_cache, name="clear_cache"),
     path('codered/import-export/import_from_csv/', import_pages_from_csv_file, name="import_from_csv"),
     re_path(r'', include(wagtailadmin_urls)),
     re_path(r'', include(wagtailimportexport_urls)),

+ 0 - 6
coderedcms/models/wagtailsettings_models.py

@@ -314,12 +314,6 @@ Sitemap: /sitemap.xml"""
             ],
             _('Robots.txt')
         ),
-        MultiFieldPanel(
-            [
-                HelpPanel(template='coderedcms/includes/wagtailadmin_cache.html',),
-            ],
-            _('Performance')
-        )
     ]
 
     class Meta:

+ 2 - 1
coderedcms/project_template/project_name/settings/base.py

@@ -33,6 +33,8 @@ INSTALLED_APPS = [
     'modelcluster',
     'taggit',
     'wagtailfontawesome',
+    'wagtailcache',
+    'wagtailimportexport',
 
     # Wagtail
     'wagtail.contrib.forms',
@@ -49,7 +51,6 @@ INSTALLED_APPS = [
     'wagtail.contrib.modeladmin',
     'wagtail.contrib.table_block',
     'wagtail.admin',
-    'wagtailimportexport',
 
     # Django
     'django.contrib.admin',

+ 1 - 1
coderedcms/project_template/project_name/settings/dev.py

@@ -10,7 +10,7 @@ ALLOWED_HOSTS = ['*']
 
 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
 
-CODERED_CACHE_PAGES = False
+WAGTAIL_CACHE = False
 
 try:
     from .local import *

+ 1 - 1
coderedcms/search_urls.py

@@ -1,7 +1,7 @@
 from django.urls import re_path
+from wagtailcache.cache import cache_page
 
 from coderedcms.views import search
-from coderedcms.utils import cache_page
 
 urlpatterns = [
     re_path(r'', cache_page(search), name='codered_search'),

+ 0 - 3
coderedcms/settings.py

@@ -7,9 +7,6 @@ PROJECT_DIR = settings.PROJECT_DIR if getattr(settings, 'PROJECT_DIR') else os.p
 BASE_DIR = settings.BASE_DIR if getattr(settings, 'BASE_DIR') else os.path.dirname(PROJECT_DIR)
 
 DEFAULTS = {
-    'CACHE_PAGES': True,
-    'CACHE_BACKEND': 'default',
-
     'PROTECTED_MEDIA_URL': '/protected/',
     'PROTECTED_MEDIA_ROOT': os.path.join(BASE_DIR, 'protected'),
     'PROTECTED_MEDIA_UPLOAD_WHITELIST': [],

+ 1 - 19
coderedcms/static/js/codered-editor.js

@@ -10,22 +10,4 @@ $(document).ready(function(){
             $fieldset.show('fast');
         }
     });
-
-    $(document).on('click', 'a.codered-clearcache', function(event) {
-        event.preventDefault();
-        $el = $(this);
-        // show spinner
-        $el.addClass('icon icon-spinner');
-        oldtext = $el.html();
-        $el.html($el.data("clicked-text"));
-        // make ajax call
-        $.ajax({
-            url: $el.attr('href')
-        })
-        .always(function(msg) {
-            $el.after("<div>" + msg + "</div>")
-            $el.removeClass('icon icon-spinner');
-            $el.html(oldtext);
-        });
-    })
-});
+});

+ 0 - 26
coderedcms/templates/coderedcms/includes/wagtailadmin_cache.html

@@ -1,26 +0,0 @@
-{% load coderedcms_tags %}
-
-<div class="field">
-    <label>Page cache:</label>
-    <div class="field-content">
-        {% if 'CACHE_PAGES'|codered_settings %}
-        <p>
-            <b>ENABLED</b>
-        </p>
-        <p>
-            Cached pages are automatically refreshed every <b>{% cache_timeout %}</b>.<br>
-            To modify this, change the <code>TIMEOUT</code> value of the <code>{{'CACHE_BACKEND'|codered_settings}}</code> cache backend in the project settings.
-        </p>
-        <p>
-            {% include "coderedcms/includes/wagtailadmin_clearcache.html" %}
-        </p>
-        {% else %}
-        <p>
-            <b>DISABLED</b>
-        </p>
-        <p>
-            To enable caching, set <code>CODERED_CACHE_PAGES = True</code> in the project settings.
-        </p>
-        {% endif %}
-    </div>
-</div>

+ 0 - 1
coderedcms/templates/coderedcms/includes/wagtailadmin_clearcache.html

@@ -1 +0,0 @@
-<a href="{% url 'clear_cache' %}" class="button button-longrunning codered-clearcache" data-clicked-text="Clearing cache…">Clear cache</a>

+ 0 - 8
coderedcms/templatetags/coderedcms_tags.py

@@ -2,7 +2,6 @@ import string
 import random
 from django import template
 from django.conf import settings
-from django.core.cache import caches
 from django.forms import ClearableFileInput
 from django.utils.html import mark_safe
 from django.utils.formats import localize
@@ -99,13 +98,6 @@ def bootstrap_settings(value):
 def django_settings(value):
     return getattr(settings, value)
 
-@register.simple_tag
-def cache_timeout():
-    timeout = caches[cr_settings['CACHE_BACKEND']].default_timeout
-    if isinstance(timeout, int):
-        return utils.seconds_to_readable(timeout)
-    return str(timeout)
-
 @register.simple_tag
 def query_update(querydict, key=None, value=None):
     """

+ 1 - 1
coderedcms/urls.py

@@ -3,10 +3,10 @@ from django.contrib.auth.views import LoginView
 from wagtail.contrib.sitemaps.views import sitemap
 from wagtail.core.urls import serve_pattern, WAGTAIL_FRONTEND_LOGIN_TEMPLATE
 from wagtail.core import views as wagtail_views
+from wagtailcache.cache import cache_page
 
 from coderedcms.settings import cr_settings
 from coderedcms.views import robots, serve_protected_file
-from coderedcms.utils import cache_page
 
 urlpatterns = [
     # CodeRed custom URLs

+ 0 - 71
coderedcms/utils.py

@@ -1,11 +1,6 @@
-from functools import wraps
-from django.core.cache import caches
 from django.core.validators import URLValidator
 from django.core.exceptions import ValidationError
-from django.middleware.cache import CacheMiddleware
 from django.utils.html import mark_safe
-from django.utils.translation import ugettext_lazy as _
-from wagtail.core import hooks
 
 from coderedcms.settings import cr_settings
 
@@ -31,69 +26,3 @@ def attempt_protected_media_value_conversion(request, value):
     except AttributeError:
         pass
     return new_value
-
-def clear_cache():
-    if cr_settings['CACHE_PAGES']:
-        cache = caches[cr_settings['CACHE_BACKEND']]
-        cache.clear()
-
-def cache_page(view_func):
-    """
-    Decorator that determines whether or not to cache a page or serve a cached page.
-    """
-    @wraps(view_func)
-    def _wrapped_view_func(request, *args, **kwargs):
-        if cr_settings['CACHE_PAGES']:
-
-            # check if request is cacheable
-            request.is_preview = getattr(request, 'is_preview', False)
-            is_cacheable = request.method in ('GET', 'HEAD') and not request.is_preview and not request.user.is_authenticated
-            for fn in hooks.get_hooks('is_request_cacheable'):
-                result = fn(request)
-                if isinstance(result, bool):
-                    is_cacheable = result
-
-            if is_cacheable:
-                cache = caches[cr_settings['CACHE_BACKEND']]
-                djcache = CacheMiddleware(
-                    cache_alias=cr_settings['CACHE_BACKEND'],
-                    cache_timeout=cache.default_timeout, # override CacheMiddleware's default timeout
-                    key_prefix=None
-                )
-                response = djcache.process_request(request)
-                if response:
-                    response['X-Crcms-Cache'] = 'hit'
-                    return response
-
-                # since we don't have a response at this point, run the view.
-                response = view_func(request, *args, **kwargs)
-                response['X-Crcms-Cache'] = 'miss'
-                djcache.process_response(request, response)
-
-                return response
-
-        # as a fall-back, just run the view function.
-        return view_func(request, *args, **kwargs)
-
-    return _wrapped_view_func
-
-def seconds_to_readable(seconds):
-    """
-    Converts int seconds to a human readable string.
-    """
-    if seconds <= 0:
-        return '{0} {1}'.format(str(seconds), _('seconds'))
-
-    mins, secs = divmod(seconds, 60)
-    hrs, mins = divmod(mins, 60)
-    days, hrs = divmod(hrs, 24)
-    pretty_time = ''
-    if days > 0:
-        pretty_time += ' {0} {1}'.format(str(days), _('days') if days > 1 else _('day'))
-    if hrs > 0:
-        pretty_time += ' {0} {1}'.format(str(hrs), _('hours') if hrs > 1 else _('hour'))
-    if mins > 0:
-        pretty_time += ' {0} {1}'.format(str(mins), _('minutes') if mins > 1  else _('minute'))
-    if secs > 0:
-        pretty_time += ' {0} {1}'.format(str(secs), _('seconds') if secs > 1  else _('second'))
-    return pretty_time

+ 1 - 7
coderedcms/views.py

@@ -14,7 +14,6 @@ from wagtail.admin import messages
 from wagtail.search.backends import db, get_search_backend
 from wagtail.search.models import Query
 
-from coderedcms import utils
 from coderedcms.forms import SearchForm
 from coderedcms.importexport import convert_csv_to_json, import_pages, ImportPagesFromCSVFileForm
 from coderedcms.models import CoderedPage, get_page_models, GeneralSettings
@@ -113,12 +112,6 @@ def serve_protected_file(request, path):
     raise Http404()
 
 
-@login_required
-def clear_cache(request):
-    utils.clear_cache()
-    return HttpResponse("Cache has been cleared.")
-
-
 def robots(request):
     robots = GeneralSettings.for_site(request.site).robots
     return render(
@@ -128,6 +121,7 @@ def robots(request):
         content_type='text/plain'
     )
 
+
 @login_required
 def import_pages_from_csv_file(request):
     """

+ 3 - 3
coderedcms/wagtail_hooks.py

@@ -7,6 +7,7 @@ from django.utils.html import format_html
 from wagtail.contrib.forms.models import AbstractForm
 from wagtail.core import hooks
 from wagtail.core.models import UserPagePermissionsProxy, get_page_models
+from wagtailcache.cache import clear_cache
 
 from coderedcms import utils
 from coderedcms.models import CoderedFormPage
@@ -29,9 +30,9 @@ def collapsible_js():
 
 @hooks.register('after_create_page')
 @hooks.register('after_edit_page')
-def clear_cache(request, page):
+def clear_wagtailcache(request, page):
     if page.live:
-        utils.clear_cache()
+        clear_cache()
 
 
 @hooks.register('filter_form_submissions_for_user')
@@ -64,4 +65,3 @@ def serve_document_directly(document, request):
     response['Content-Disposition'] = 'inline;filename="{0}"'.format(document.filename)
     response['Content-Encoding'] = content_encoding
     return response
-    

+ 4 - 3
docs/getting_started/customize_develop.rst

@@ -17,10 +17,11 @@ Building on the concept of wagtail hooks, there are some additional hooks in Cod
 is_request_cacheable
 ^^^^^^^^^^^^^^^^^^^^
 
+This hook is provided by `wagtail-cache <https://github.com/coderedcorp/wagtail-cache>`_.
 The callable passed into this hook should take a ``request`` argument, and return a ``bool``
-indicating whether or not the response to this request should be cached (served from the
-cache if it is already cached). Not returning, or returning anything other than a bool will
-not affect the caching decision. For example::
+indicating whether or not the response to this request should be cached (served from the cache
+if it is already cached). Not returning, or returning anything other than a bool will not
+affect the caching decision. For example::
 
     from wagtail.core import hooks
 

+ 2 - 1
docs/releases/v0.10.0.rst

@@ -10,4 +10,5 @@ New features:
 
 Maintenance:
 
-* Replace Wagtail version in admin with CodeRed CMS version.
+* Replace Wagtail version with CodeRed CMS version in admin.
+* Replace built-in cache with `wagtail-cache <https://github.com/coderedcorp/wagtail-cache/>`_.

+ 4 - 1
setup.py

@@ -42,15 +42,18 @@ setup(
     install_requires=[
         'django-bootstrap4',
         'django>=1.11,<2.2',
+        'geocoder>=1.38.1,<2.0',
         'pygments>=2.2.0,<3.0',
         'wagtail==2.3.*',
         'wagtailfontawesome>=1.1.3,<2.0',
-        'geocoder>=1.38.1,<2.0',
+        'wagtail-cache==0.2.*',
         'wagtail-import-export>=0.1,<0.2'
     ],
     extras_require={
         'dev': [
+            'pylint-django',
             'sphinx',
+            'twine',
         ]
     },
     entry_points="""