Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
anx-ckreuzberger committed Dec 20, 2017
0 parents commit 6f35d13
Show file tree
Hide file tree
Showing 8 changed files with 240 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.pyc
*.pyo
dist/**
django_request_cache.egg-info/**
.idea/**
venv/
build/
.tox/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 Christian Kreuzberger

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
include LICENSE
include README.rst
66 changes: 66 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
====================
Django Request Cache
====================

Django Request Cache provides a cache for each request (within your Django Request/Response cycle).

Quick start
-----------

1. Download and install using `pip install`

.. code-block:: bash
pip install django-request-cache
2. Add ``UserForeignKeyMiddleware`` and ``RequestCacheMiddleware`` to your ``MIDDLEWARE`` settings like this:

.. code-block:: python
MIDDLEWARE = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
...
'django_userforeignkey.middleware.UserForeignKeyMiddleware',
'django_request_cache.middleware.RequestCacheMiddleware',
)
or if you are still using the an older Django version (e.g., Django 1.8) with ``MIDDLEWARE_CLASSES``:

.. code-block:: python
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
...
'django_userforeignkey.middleware.UserForeignKeyMiddleware',
'django_request_cache.middleware.RequestCacheMiddleware',
)
3. Use the per-request cache as a decorator

.. code-block:: python
from django_request_cache import cache_for_request
@cache_for_request
def do_some_complex_calculation(a, b, c):
print("Calculating... please wait")
return a * b * c
Try it out by executing do_some_complex_calculation multiple times within your request

Attribution
-----------

``RequestCache`` and ``RequestCacheMiddleware`` (see ``middleware.py``) are from a source code snippet on StackOverflow
https://stackoverflow.com/questions/3151469/per-request-cache-in-django/37015573#37015573
created by coredumperror https://stackoverflow.com/users/464318/coredumperror
Original Question was posted by https://stackoverflow.com/users/7679/chase-seibert
at https://stackoverflow.com/questions/3151469/per-request-cache-in-django
copied on 2017-Dec-20

58 changes: 58 additions & 0 deletions django_request_cache/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from django.core.cache.backends.base import BaseCache
from django.core.cache.backends.locmem import LocMemCache
from django.utils.synch import RWLock


def get_request_cache():
"""
Return the current requests cache
:return:
"""
from django_userforeignkey.request import get_current_request
return getattr(get_current_request(), "cache", None)


cache_args_kwargs_marker = object() # marker for separating args from kwargs (needs to be global)


def cache_calculate_key(*args, **kwargs):
"""
Calculate the cache key of a function call with args and kwargs
Taken from lru_cache
:param args:
:param kwargs:
:return: the calculated key for the function call
:rtype: basestring
"""
# combine args with kwargs, separated by the cache_args_kwargs_marker
key = args + (cache_args_kwargs_marker,) + tuple(sorted(kwargs.items()))
# return as a string
return str(key)


def cache_for_request(fn):
"""
Decorator that allows to cache a function call with parameters and its result only for the current request
The result is stored in the memory of the current process
As soon as the request is destroyed, the cache is destroyed
:param fn:
:return:
"""
def wrapper(*args, **kwargs):
cache = get_request_cache()

if not cache:
# no cache found -> directly execute function without caching
return fn(*args, **kwargs)

# cache found -> check if a result is already available for this function call
key = cache_calculate_key(fn.__name__, *args, **kwargs)
result = getattr(cache, key, None)

if not result:
# no result available -> execute function
result = fn(*args, **kwargs)
setattr(cache, key, result)

return result
return wrapper
36 changes: 36 additions & 0 deletions django_request_cache/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from django.core.cache.backends.base import BaseCache
from django.core.cache.backends.locmem import LocMemCache
from django.utils.synch import RWLock

# Attribution: RequestCache and RequestCacheMiddleware are from a source code snippet on StackOverflow
# https://stackoverflow.com/questions/3151469/per-request-cache-in-django/37015573#37015573
# created by coredumperror https://stackoverflow.com/users/464318/coredumperror
# Original Question was posted by https://stackoverflow.com/users/7679/chase-seibert
# at https://stackoverflow.com/questions/3151469/per-request-cache-in-django
# copied on 2017-Dec-20


class RequestCache(LocMemCache):
"""
RequestCache is a customized LocMemCache which stores its data cache as an instance attribute, rather than
a global. It's designed to live only as long as the request object that RequestCacheMiddleware attaches it to.
"""

def __init__(self):
# We explicitly do not call super() here, because while we want BaseCache.__init__() to run, we *don't*
# want LocMemCache.__init__() to run, because that would store our caches in its globals.
BaseCache.__init__(self, {})

self._cache = {}
self._expire_info = {}
self._lock = RWLock()


class RequestCacheMiddleware(object):
"""
For every request, a fresh cache instance is stored in ``request.cache``.
The cache instance lives only as long as request does.
"""

def process_request(self, request):
request.cache = RequestCache()
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[metadata]
description-file = README.rst
47 changes: 47 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import os

from setuptools import find_packages, setup

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
name='django-request-cache',
version='1.0',
packages=find_packages(),
include_package_data=True,
license='MIT',
description='A simple Django app that provides a per-request cache.',
long_description=README,
url='https://github.com/anx-ckreuzberger/django-request-cache',
author='Christian Kreuzberger',
author_email='[email protected]',
install_requires=[
"django>=1.8,<2.1",
"django_userforeignkey"
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)

0 comments on commit 6f35d13

Please sign in to comment.