Commit 281d22fd by David Ormsbee

Merge pull request #168 from edx/ormsbee/cache_sub

Simple caching of get_submission() requests.
parents c4f71442 cf27ac66
......@@ -5,6 +5,7 @@ Public interface for the submissions app.
import copy
import logging
from django.core.cache import cache
from django.db import DatabaseError
from django.utils.encoding import force_unicode
......@@ -180,9 +181,15 @@ def get_submission(submission_uuid):
"submission_uuid ({!r}) must be a string type".format(submission_uuid)
)
cache_key = "submissions.submission.{}".format(submission_uuid)
cached_submission_data = cache.get(cache_key)
if cached_submission_data:
return cached_submission_data
try:
submission = Submission.objects.get(uuid=submission_uuid)
return SubmissionSerializer(submission).data
submission_data = SubmissionSerializer(submission).data
cache.set(cache_key, submission_data)
except Submission.DoesNotExist:
raise SubmissionNotFoundError(
u"No submission matching uuid {}".format(submission_uuid)
......@@ -193,6 +200,8 @@ def get_submission(submission_uuid):
logger.exception(err_msg)
raise SubmissionInternalError(err_msg)
return submission_data
def get_submission_and_student(uuid):
"""
......
......@@ -76,7 +76,7 @@ class TestSubmissionsApi(TestCase):
# Test not found
with self.assertRaises(api.SubmissionNotFoundError):
api.get_submission("not a real uuid")
api.get_submission("notarealuuid")
with self.assertRaises(api.SubmissionNotFoundError):
api.get_submission("0" * 50) # This is bigger than our field size
......@@ -187,6 +187,21 @@ class TestSubmissionsApi(TestCase):
item_id=student_item["item_id"]
)
def test_caching(self):
sub = api.create_submission(STUDENT_ITEM, "Hello World!")
# The first request to get the submission hits the database...
with self.assertNumQueries(1):
db_sub = api.get_submission(sub["uuid"])
# The next one hits the cache only...
with self.assertNumQueries(0):
cached_sub = api.get_submission(sub["uuid"])
# The data that gets passed back matches the original in both cases
self.assertEqual(sub, db_sub)
self.assertEqual(sub, cached_sub)
"""
Testing Scores
"""
......
......@@ -171,3 +171,10 @@ LOGGING = {
WORKBENCH = {
'reset_state_on_restart': False,
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'default_loc_mem',
},
}
......@@ -29,3 +29,4 @@ LETTUCE_SERVER_PORT = 8005
# Install test-specific Django apps
INSTALLED_APPS += ('django_nose', 'lettuce.django',)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment