Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add basic cache support

Roland Geidercfb01967d4c2
diff --git a/wger/exercises/models.py b/wger/exercises/models.py
index 6e35ff5fe..095a9b9e5 100644
--- a/wger/exercises/models.py
+++ b/wger/exercises/models.py
@@ -22,8 +22,11 @@ from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext
from django.core.urlresolvers import reverse
from django.core import mail
+from django.core.cache import cache
from wger.utils.constants import EMAIL_FROM
+from wger.utils.cache import delete_template_fragment_cache
+from wger.utils.cache import cache_mapper
class Language(models.Model):
@@ -39,6 +42,9 @@ class Language(models.Model):
full_name = models.CharField(max_length=30,
verbose_name=_('Language full name'))
+ #
+ # Django methods
+ #
def __unicode__(self):
'''
Return a more human-readable representation
@@ -51,6 +57,9 @@ class Language(models.Model):
'''
return reverse('config:language-view', kwargs={'pk': self.id})
+ #
+ # Own methods
+ #
def get_owner_object(self):
'''
Muscle has no owner information
@@ -175,6 +184,10 @@ class Exercise(models.Model):
editable=False)
'''The exercise's language'''
+ #
+ # Django methods
+ #
+
# Metaclass to set some other properties
class Meta:
ordering = ["name", ]
@@ -186,6 +199,50 @@ class Exercise(models.Model):
return reverse('wger.exercises.views.exercises.view',
kwargs={'id': self.id, 'slug': slugify(self.name)})
+ def save(self, *args, **kwargs):
+ '''
+ Reset all cached infos
+ '''
+
+ super(Exercise, self).save(*args, **kwargs)
+
+ # Cached objects
+ cache.delete(cache_mapper.get_exercise_key(self))
+ cache.delete(cache_mapper.get_exercise_muscle_bg_key(self))
+
+ # Cached template fragments
+ delete_template_fragment_cache('muscle-overview', self.language_id)
+ delete_template_fragment_cache('exercise-overview', self.language_id)
+ delete_template_fragment_cache('exercise-detail-header', self.id, self.language_id)
+ delete_template_fragment_cache('exercise-detail-muscles', self.id, self.language_id)
+
+ def delete(self, *args, **kwargs):
+ '''
+ Reset all cached infos
+ '''
+
+ # Cached objects
+ cache.delete(cache_mapper.get_exercise_key(self))
+ cache.delete(cache_mapper.get_exercise_muscle_bg_key(self))
+
+ # Cached template fragments
+ delete_template_fragment_cache('muscle-overview', self.language_id)
+ delete_template_fragment_cache('exercise-overview', self.language_id)
+ delete_template_fragment_cache('exercise-detail-heder', self.language_id)
+ delete_template_fragment_cache('exercise-detail-muscles', self.language_id)
+
+ super(Exercise, self).delete(*args, **kwargs)
+
+ def __unicode__(self):
+ '''
+ Return a more human-readable representation
+ '''
+ return self.name
+
+ #
+ # Own methods
+ #
+
def get_owner_object(self):
'''
Exercise has no owner information
@@ -213,12 +270,6 @@ class Exercise(models.Model):
[self.user.email],
fail_silently=True)
- def __unicode__(self):
- '''
- Return a more human-readable representation
- '''
- return self.name
-
class ExerciseComment(models.Model):
'''
diff --git a/wger/exercises/templates/muscles/overview.html b/wger/exercises/templates/muscles/overview.html
index 9aa7738d8..7d51d6bc8 100644
--- a/wger/exercises/templates/muscles/overview.html
+++ b/wger/exercises/templates/muscles/overview.html
@@ -2,6 +2,7 @@
{% load url from future %}
{% load i18n %}
{% load staticfiles %}
+{% load cache %}
<!--
Title
@@ -62,6 +63,7 @@ $(document).ready(function() {
Main Content
-->
{% block content %}
+{% cache cache_timeout muscle-overview language.id %}
{% trans "Hover with the mouse over the muscles to show corresponding exercises." %}
<div class="ym-grid linearize-level-1">
@@ -163,6 +165,7 @@ to create a new SVG image with the contours of the muscle and place it in the
folder <em>images/muscles</em>.{% endblocktrans %}</p>
{% endif %}
+{% endcache %}
{% endblock %}
diff --git a/wger/exercises/templates/overview.html b/wger/exercises/templates/overview.html
index 21fba1c08..d017f3254 100644
--- a/wger/exercises/templates/overview.html
+++ b/wger/exercises/templates/overview.html
@@ -3,6 +3,7 @@
{% load i18n %}
{% load staticfiles %}
{% load manager_extras %}
+{% load cache %}
<!--
Title
@@ -56,6 +57,7 @@ $(document).ready(function() {
Main Content
-->
{% block content %}
+{% cache cache_timeout exercise-overview language.id %}
<div id="tabs">
<ul>
{% for category in categories %}
@@ -74,19 +76,6 @@ $(document).ready(function() {
<td>
<a href="{{ exercise.get_absolute_url }}">{{ exercise.name }}</a>
</td>
- <td style="text-align:right;">
- {% if perms.exercises %}
- <div class="editoptions">
- <a href="{% url 'exercise-edit' exercise.id %}"
- title="{% trans 'Edit' %}">
- <img src="{% static 'images/icons/edit.svg' %}"
- width="16"
- height="16"
- alt="{% trans 'Edit' %}">
- </a>
- </div>
- {% endif %}
- </td>
</tr>
{% empty %}
<tr>
@@ -102,7 +91,7 @@ $(document).ready(function() {
</div>
{% endfor %}
</div>
-
+{% endcache %}
{% endblock %}
diff --git a/wger/exercises/templates/view.html b/wger/exercises/templates/view.html
index 86c5a15fe..dec40f6f7 100644
--- a/wger/exercises/templates/view.html
+++ b/wger/exercises/templates/view.html
@@ -3,7 +3,7 @@
{% load i18n %}
{% load staticfiles %}
{% load manager_extras %}
-
+{% load cache %}
{% block header %}
<script src="{% static 'js/tinymce/tiny_mce.js' %}"></script>
@@ -74,10 +74,10 @@ included in the database.{% endblocktrans %}
{% endif %} {# end exercise is pending review #}
-
+{% cache cache_timeout exercise-detail-header exercise.id language.id %}
<p>{% trans "Category" %}: <strong>{{ exercise.category.name }}</strong></p>
-
<p>{{ exercise.description|safe }}</p>
+{% endcache %}
{% with comments=exercise.exercisecomment_set.all %}
{% if comments %}
@@ -112,7 +112,6 @@ included in the database.{% endblocktrans %}
{% endif %}
{% endwith %}
-
{% if perms.exercises %}
<p>
<a href="{% url 'exercisecomment-add' exercise.id %}"
@@ -126,7 +125,7 @@ included in the database.{% endblocktrans %}
</p>
{% endif %}
-
+{% cache cache_timeout exercise-detail-muscles exercise.id language.id %}
{% with muscles=exercise.muscles.all %}
{% with muscles_secondary=exercise.muscles_secondary.all %}
@@ -192,7 +191,7 @@ included in the database.{% endblocktrans %}
{% endif %}
{% endwith %}
{% endwith %} {# end musclelist #}
-
+{% endcache %}
{% if logs %}
<h3>{% trans "Weight log" %}</h3>
diff --git a/wger/exercises/views/exercises.py b/wger/exercises/views/exercises.py
index f83fe42e6..f27560f76 100644
--- a/wger/exercises/views/exercises.py
+++ b/wger/exercises/views/exercises.py
@@ -26,6 +26,7 @@ from django.http import HttpResponseForbidden
from django.forms import ModelForm
from django.forms import ModelChoiceField
from django.core import mail
+from django.core.cache import cache
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
@@ -51,6 +52,8 @@ from wger.utils.language import load_item_languages
from wger.config.models import LanguageConfig
+from wger.utils.cache import cache_mapper
+
logger = logging.getLogger('workout_manager.custom')
@@ -83,32 +86,42 @@ def view(request, id, slug=None):
template_data['comment_edit'] = False
# Load the exercise itself
- exercise = get_object_or_404(Exercise, pk=id)
+ exercise = cache.get(cache_mapper.get_exercise_key(int(id)))
+ if not exercise:
+ exercise = get_object_or_404(Exercise, pk=id)
+ cache.set(cache_mapper.get_exercise_key(exercise), exercise)
+
template_data['exercise'] = exercise
# Create the backgrounds that show what muscles the exercise works on
- backgrounds_back = []
- backgrounds_front = []
-
- for muscle in exercise.muscles.all():
- if muscle.is_front:
- backgrounds_front.append('images/muscles/main/muscle-%s.svg' % muscle.id)
- else:
- backgrounds_back.append('images/muscles/main/muscle-%s.svg' % muscle.id)
-
- for muscle in exercise.muscles_secondary.all():
- if muscle.is_front:
- backgrounds_front.append('images/muscles/secondary/muscle-%s.svg' % muscle.id)
- else:
- backgrounds_back.append('images/muscles/secondary/muscle-%s.svg' % muscle.id)
-
- # Append the "main" background, with the silhouette of the human body
- # This has to happen as the last step, so it is rendered behind the muscles.
- backgrounds_front.append('images/muscles/muscular_system_front.svg')
- backgrounds_back.append('images/muscles/muscular_system_back.svg')
-
- template_data['muscle_backgrounds_front'] = backgrounds_front
- template_data['muscle_backgrounds_back'] = backgrounds_back
+ backgrounds = cache.get(cache_mapper.get_exercise_muscle_bg_key(int(id)))
+ if not backgrounds:
+ backgrounds_back = []
+ backgrounds_front = []
+
+ for muscle in exercise.muscles.all():
+ if muscle.is_front:
+ backgrounds_front.append('images/muscles/main/muscle-%s.svg' % muscle.id)
+ else:
+ backgrounds_back.append('images/muscles/main/muscle-%s.svg' % muscle.id)
+
+ for muscle in exercise.muscles_secondary.all():
+ if muscle.is_front:
+ backgrounds_front.append('images/muscles/secondary/muscle-%s.svg' % muscle.id)
+ else:
+ backgrounds_back.append('images/muscles/secondary/muscle-%s.svg' % muscle.id)
+
+ # Append the "main" background, with the silhouette of the human body
+ # This has to happen as the last step, so it is rendered behind the muscles.
+ backgrounds_front.append('images/muscles/muscular_system_front.svg')
+ backgrounds_back.append('images/muscles/muscular_system_back.svg')
+ backgrounds = (backgrounds_front, backgrounds_back)
+
+ cache.set(cache_mapper.get_exercise_muscle_bg_key(int(id)),
+ (backgrounds_front, backgrounds_back))
+
+ template_data['muscle_backgrounds_front'] = backgrounds[0]
+ template_data['muscle_backgrounds_back'] = backgrounds[1]
# If the user is logged in, load the log and prepare the entries for
# rendering in the D3 chart
diff --git a/wger/main.py b/wger/main.py
index 3d5525d9e..662bf9bc0 100755
--- a/wger/main.py
+++ b/wger/main.py
@@ -67,6 +67,9 @@ RECAPTCHA_PRIVATE_KEY = '%(recaptcha_private_key)s'
# The site's URL (e.g. http://www.my-local-gym.com or http://localhost:8000)
# This is needed for Mozilla's BrowserID to work
SITE_URL = '%(siteurl)s'
+
+# This might be a good idea if you setup memcached
+#SESSION_ENGINE = "django.contrib.sessions.backends.cache"
"""
KEY_LENGTH = 30
diff --git a/wger/manager/templates/navigation.html b/wger/manager/templates/navigation.html
index 544e3e200..5b1a1aef0 100644
--- a/wger/manager/templates/navigation.html
+++ b/wger/manager/templates/navigation.html
@@ -1,4 +1,4 @@
-{% load i18n %}{% load url from future %}
+{% load i18n %}{% load url from future %}{% load cache %}
<nav id="nav">
<div class="ym-wrapper">
<div class="navbar navbar-inverse ">
@@ -42,11 +42,14 @@
<ul class="dropdown-menu">
<li><a href="{% url 'wger.exercises.views.exercises.overview' %}">{% trans "Exercises" %}</a></li>
<li><a href="{% url 'muscle-overview' %}">{% trans "Muscle overview" %}</a></li>
+ {% cache cache_timeout user-admin-exercises user.id %}
{% if perms.exercises %}
<li class="divider"></li>
<li class="nav-header">{% trans "Administration" %}</li>
<li><a href="{% url 'exercise-pending' %}">{% trans "Exercises pending review" %}</a></li>
{% endif %}
+ {% endcache %}
+
</ul>
</li>
@@ -78,12 +81,14 @@
<ul class="dropdown-menu">
<li><a href="{% url 'wger.nutrition.views.plan.overview' %}" rel="nofollow">{% trans "Nutrition plans" %}</a></li>
<li><a href="{% url 'ingredient-list' %}">{% trans "Ingredient overview" %}</a></li>
+ {% cache cache_timeout user-admin-ingredients user.id %}
{% if perms.exercises %}
<li class="divider"></li>
<li class="nav-header">{% trans "Administration" %}</li>
<li><a href="{% url 'weight-unit-list' %}">{% trans "Ingredient weight units" %}</a></li>
<li><a href="{% url 'ingredient-pending' %}">{% trans "Ingredients pending review" %}</a></li>
{% endif %}
+ {% endcache %}
</ul>
</li>
diff --git a/wger/nutrition/models.py b/wger/nutrition/models.py
index 190c1c9c5..abb1215f2 100644
--- a/wger/nutrition/models.py
+++ b/wger/nutrition/models.py
@@ -16,7 +16,6 @@
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
import logging
import decimal
-import datetime
from django.db import models
@@ -25,12 +24,14 @@ from django.core.validators import MaxValueValidator
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.core import mail
+from django.core.cache import cache
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext
from wger.exercises.models import Language
from wger.utils.constants import EMAIL_FROM
+from wger.utils.cache import cache_mapper
MEALITEM_WEIGHT_GRAM = '1'
MEALITEM_WEIGHT_UNIT = '2'
@@ -212,6 +213,10 @@ class Ingredient(models.Model):
verbose_name=_('Sodium'),
help_text=_('In g per 100g of product'))
+ #
+ # Django methods
+ #
+
def get_absolute_url(self):
'''
Returns the canonical URL to view this object
@@ -245,6 +250,39 @@ class Ingredient(models.Model):
raise ValidationError(_('Total energy is not the approximate sum of the energy '
'provided by protein, carbohydrates and fat.'))
+ def save(self, *args, **kwargs):
+ '''
+ Reset the cache
+ '''
+
+ super(Ingredient, self).save(*args, **kwargs)
+ cache.delete(cache_mapper.get_ingredient_key(self.id))
+
+ def __unicode__(self):
+ '''
+ Return a more human-readable representation
+ '''
+ return u"{0}".format(self.name)
+
+ def __eq__(self, other):
+ '''
+ Compare ingredients based on their values, not like django on their PKs
+ '''
+
+ logger.debug('Overwritten behaviour: comparing ingredients on values, not PK.')
+ equal = True
+ if isinstance(other, self.__class__):
+ for i in self._meta.fields:
+ if (hasattr(self, i.name) and hasattr(other, i.name) and
+ (getattr(self, i.name, None) != getattr(other, i.name, None))):
+ equal = False
+ else:
+ equal = False
+ return equal
+
+ #
+ # Own methods
+ #
def compare_with_database(self):
'''
Compares the current ingredient with the version saved in the database.
@@ -290,28 +328,6 @@ class Ingredient(models.Model):
'''
return False
- def __unicode__(self):
- '''
- Return a more human-readable representation
- '''
- return u"{0}".format(self.name)
-
- def __eq__(self, other):
- '''
- Compare ingredients based on their values, not like django on their PKs
- '''
-
- logger.debug('Overwritten behaviour: comparing ingredients on values, not PK.')
- equal = True
- if isinstance(other, self.__class__):
- for i in self._meta.fields:
- if (hasattr(self, i.name) and hasattr(other, i.name) and
- (getattr(self, i.name, None) != getattr(other, i.name, None))):
- equal = False
- else:
- equal = False
- return equal
-
class WeightUnit(models.Model):
'''
diff --git a/wger/nutrition/templates/ingredient/overview.html b/wger/nutrition/templates/ingredient/overview.html
index 05bf67317..af355c0b6 100644
--- a/wger/nutrition/templates/ingredient/overview.html
+++ b/wger/nutrition/templates/ingredient/overview.html
@@ -3,7 +3,7 @@
{% load i18n %}
{% load staticfiles %}
{% load manager_extras %}
-
+{% load cache %}
{% block header %}
<script>
@@ -30,6 +30,7 @@ $(document).ready(function() {
{% block content %}
+{% cache cache_timeout ingredient-overview page_obj.number language.id %}
{% if ingredients_list %}
<ul>
{% for ingredient in ingredients_list %}
@@ -50,7 +51,7 @@ $(document).ready(function() {
<div style="padding-top:3em;"></div>
{% pagination paginator page_obj %}
-
+{% endcache %}
{% endblock %}
{% block sidebar %}
diff --git a/wger/nutrition/templates/ingredient/view.html b/wger/nutrition/templates/ingredient/view.html
index 2c6f0c0f3..dc88116da 100644
--- a/wger/nutrition/templates/ingredient/view.html
+++ b/wger/nutrition/templates/ingredient/view.html
@@ -3,6 +3,7 @@
{% load i18n %}
{% load staticfiles %}
{% load manager_extras %}
+{% load cache %}
{% block title %}{{ingredient.name}}{% endblock %}
@@ -217,6 +218,7 @@ the search.{% endblocktrans %}
</tbody>
</table>
</div>
+
{% endblock %}
diff --git a/wger/nutrition/views/ingredient.py b/wger/nutrition/views/ingredient.py
index 33994350e..a8a82e70c 100644
--- a/wger/nutrition/views/ingredient.py
+++ b/wger/nutrition/views/ingredient.py
@@ -26,6 +26,7 @@ from django.core import mail
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
+from django.core.cache import cache
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.decorators import login_required
from django.contrib import messages
@@ -50,6 +51,7 @@ from wger.utils.language import load_language
from wger.utils.language import load_ingredient_languages
from wger.config.models import LanguageConfig
from wger.utils.language import load_item_languages
+from wger.utils.cache import cache_mapper
logger = logging.getLogger('workout_manager.custom')
@@ -83,7 +85,10 @@ class IngredientListView(ListView):
def view(request, id, slug=None):
template_data = {}
- ingredient = get_object_or_404(Ingredient, pk=id)
+ ingredient = cache.get(cache_mapper.get_ingredient_key(int(id)))
+ if not ingredient:
+ ingredient = get_object_or_404(Ingredient, pk=id)
+ cache.set(cache_mapper.get_ingredient_key(ingredient), ingredient)
template_data['ingredient'] = ingredient
template_data['form'] = UnitChooserForm(data={'ingredient_id': ingredient.id,
'amount': 100,
diff --git a/wger/settings_global.py b/wger/settings_global.py
index 90127f9e3..8f183102a 100644
--- a/wger/settings_global.py
+++ b/wger/settings_global.py
@@ -267,3 +267,12 @@ LOGGING = {
TEST_RUNNER = 'discover_runner.DiscoverRunner'
TEST_DISCOVER_TOP_LEVEL = os.path.dirname(os.path.dirname(__file__))
+
+# Set local memory caching by default
+CACHES = {
+ 'default': {
+ 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
+ 'LOCATION': 'wger-cache',
+ 'TIMEOUT': 43200
+ }
+}
diff --git a/wger/utils/cache.py b/wger/utils/cache.py
new file mode 100644
index 000000000..414b89ac0
--- /dev/null
+++ b/wger/utils/cache.py
@@ -0,0 +1,84 @@
+# This file is part of Workout Manager.
+#
+# Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+
+
+import hashlib
+from django.core.cache import cache
+from django.utils.encoding import force_bytes
+
+
+def delete_template_fragment_cache(fragment_name='', *args):
+
+ key = u':'.join([str(arg) for arg in args])
+ key_name = hashlib.md5(force_bytes(key)).hexdigest()
+ cache.delete('template.cache.{0}.{1}'.format(fragment_name, key_name))
+
+
+class CacheKeyMapper(object):
+ '''
+ Simple class for mapping the cache keys of different objects
+ '''
+
+ # Keys used by the cache
+ LANGUAGE_CACHE_KEY = 'language-{0}'
+ EXERCISE_CACHE_KEY = 'exercise-{0}'
+ EXERCISE_CACHE_KEY_MUSCLE_BG = 'exercise-muscle-bg-{0}'
+ INGREDIENT_CACHE_KEY = 'ingredient-{0}'
+
+ def get_exercise_key(self, param):
+ '''
+ Return the exercise cache key
+ '''
+ if type(param) == int:
+ pk = param
+ else:
+ pk = param.pk
+
+ return self.EXERCISE_CACHE_KEY.format(pk)
+
+ def get_exercise_muscle_bg_key(self, param):
+ '''
+ Return the exercise muscle background cache key
+ '''
+ if type(param) == int:
+ pk = param
+ else:
+ pk = param.pk
+
+ return self.EXERCISE_CACHE_KEY_MUSCLE_BG.format(pk)
+
+ def get_language_key(self, param):
+ '''
+ Return the language cache key
+ '''
+ if type(param) in (str, unicode):
+ pk = param
+ else:
+ pk = param.short_name
+
+ return self.LANGUAGE_CACHE_KEY.format(pk)
+
+ def get_ingredient_key(self, param):
+ '''
+ Return the ingredient cache key
+ '''
+ if type(param) == int:
+ pk = param
+ else:
+ pk = param.pk
+
+ return self.INGREDIENT_CACHE_KEY.format(pk)
+
+
+cache_mapper = CacheKeyMapper()
diff --git a/wger/utils/context_processor.py b/wger/utils/context_processor.py
index a1f6972fd..30aa22789 100644
--- a/wger/utils/context_processor.py
+++ b/wger/utils/context_processor.py
@@ -13,6 +13,7 @@
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
+from django.conf import settings
from wger import get_version
from wger.utils import constants
@@ -45,6 +46,9 @@ def processor(request):
# Don't show messages on AJAX requests (they are deleted if shown)
'no_messages': request.META.get('HTTP_X_WGER_NO_MESSAGES', False),
+
+ # Default cache time for template fragment caching
+ 'cache_timeout': settings.CACHES['default']['TIMEOUT']
}
# Pseudo-intelligent navigation here
diff --git a/wger/utils/language.py b/wger/utils/language.py
index 01a1bf0b4..bb72fa64d 100644
--- a/wger/utils/language.py
+++ b/wger/utils/language.py
@@ -12,19 +12,13 @@
#
# You should have received a copy of the GNU Affero General Public License
-from os.path import join as path_join
-
-from django.conf import settings
from django.utils import translation
from django.core.exceptions import ObjectDoesNotExist
-
-from reportlab.lib.styles import ParagraphStyle
-from reportlab.lib.styles import StyleSheet1
-from reportlab.pdfbase.ttfonts import TTFont
-from reportlab.pdfbase import pdfmetrics
+from django.core.cache import cache
from wger.exercises.models import Language
from wger.config.models import LanguageConfig
+from wger.utils.cache import cache_mapper
# ************************
@@ -42,13 +36,17 @@ def load_language():
# Read the first part of a composite language, e.g. 'de-at'
used_language = translation.get_language().split('-')[0]
+ language = cache.get(cache_mapper.get_language_key(used_language))
+ if language:
+ return language
+
try:
language = Language.objects.get(short_name=used_language)
-
- # No luck, load english as our fall-back language
except ObjectDoesNotExist:
+ # No luck, load english as our fall-back language
language = Language.objects.get(short_name="en")
+ cache.set(cache_mapper.get_language_key(language), language)
return language
@@ -57,9 +55,6 @@ def load_item_languages(item):
Returns the languages for a data type (exercises, ingredients)
'''
- #SHOW_ITEM_EXERCISES = '1'
- #SHOW_ITEM_INGREDIENTS = '2'
-
# Load the configurations we are interested in and return the languages
LanguageConfig.SHOW_ITEM_LIST
language = load_language()
diff --git a/wger/utils/middleware.py b/wger/utils/middleware.py
index 07f8aa7c2..05d42a16a 100644
--- a/wger/utils/middleware.py
+++ b/wger/utils/middleware.py
@@ -23,6 +23,7 @@ import logging
import uuid
import re
+from django.core.cache import cache
from django.contrib import auth
from django.contrib.auth import authenticate
from django.utils.functional import SimpleLazyObject
@@ -31,6 +32,7 @@ from django.contrib.auth import login as django_login
from wger.manager.demo import create_temporary_user
+
logger = logging.getLogger('workout_manager.custom')
@@ -56,8 +58,13 @@ def check_current_request(request):
def get_user(request):
if not hasattr(request, '_cached_user'):
- user = auth.get_user(request)
+
+ CACHE_KEY = 'user-session-{0}'
create_user = check_current_request(request)
+ user = cache.get(CACHE_KEY.format(request.session.session_key))
+ if not user:
+ user = auth.get_user(request)
+ cache.set(CACHE_KEY.format(request.session.session_key), user)
# Set the flag in the session
if not request.session.get('has_demo_data'):
@@ -65,8 +72,10 @@ def get_user(request):
# Django didn't find a user, so create one now
if create_user and not user.is_authenticated():
+
logger.debug('creating a new guest user now')
user = create_temporary_user()
+ cache.set(CACHE_KEY.format(request.session.session_key), user)
django_login(request, user)
request._cached_user = user