• Stars
    star
    145
  • Rank 254,144 (Top 6 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created almost 12 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Django `cache_page` decorator on steroids.

django-fancy-cache

Copyright Peter Bengtsson, [email protected], 2013-2022

License: BSD

About django-fancy-cache

A Django cache_page decorator on steroids.

Unlike the stock django.views.decorators.cache.change_page this decorator makes it possible to set a key_prefix that is a callable. This callable is passed the request and if it returns None the page is not cached.

Also, you can set another callable called post_process_response (which is passed the response and the request) which can do some additional changes to the response before it's set in cache.

Lastly, you can set post_process_response_always=True so that the post_process_response callable is always called, even when the response is coming from the cache.

How to use it

In your Django views:

from fancy_cache import cache_page
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

@cache_page(60 * 60)
def myview(request):
    return render(request, 'page1.html')

def prefixer(request):
    if request.method != 'GET':
        return None
    if request.GET.get('no-cache'):
        return None
    return 'myprefix'

@cache_page(60 * 60, key_prefix=prefixer)
def myotherview(request):
    return render(request, 'page2.html')

def post_processor(response, request):
    response.content += '<!-- this was post processed -->'
    return response

@cache_page(
    60 * 60,
    key_prefix=prefixer,
    post_process_response=post_processor)
def yetanotherotherview(request):
    return render(request, 'page3.html')


class MyClassBasedView(TemplateView):
    template_name = 'page4.html'

    @method_decorator(cache_page(60*60))
    def get(self, request, *args, **kwargs):
        return super().get(request, *args, **kwargs)

Optional uses

If you want to you can have django-fancy-cache record every URL it caches. This can be useful for things like invalidation or curious statistical inspection.

You can either switch this on on the decorator itself. Like this:

from fancy_cache import cache_page

@cache_page(60 * 60, remember_all_urls=True)
def myview(request):
    return render(request, 'page1.html')

Or, more conveniently to apply it to all uses of the cache_page decorator you can set the default in your settings with:

FANCY_REMEMBER_ALL_URLS = True

Now, suppose you have the this option enabled. Now you can do things like this:

>>> from fancy_cache.memory import find_urls
>>> list(find_urls(['/some/searchpath', '/or/like/*/this.*']))
>>> # or, to get all:
>>> list(find_urls([]))

There is also another option to this and that is to purge (aka. invalidate) the remembered URLs. You simply all the purge=True option like this:

>>> from fancy_cache.memory import find_urls
>>> list(find_urls([], purge=True))

Note: Since find_urls() returns a generator, the purging won't happen unless you exhaust the generator. E.g. looping over it or turning it into a list.

If you are using Memcached, you must enable check-and-set to remember all urls by enabling the FANCY_USE_MEMCACHED_CHECK_AND_SET flag and enabling cas in your CACHES settings:

# in settings.py

FANCY_USE_MEMCACHED_CHECK_AND_SET = True

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',
        'LOCATION': '127.0.0.1:11211',
        # This OPTIONS setting enables Memcached check-and-set which is
        # required for remember_all_urls or FANCY_REMEMBER_ALL_URLS.
        'OPTIONS': {
            'behaviors': {
                'cas': True
            }
        }
    }
 }

The second way to inspect all recorded URLs is to use the fancy-cache management command. This is only available if you have added fancy_cache to your INSTALLED_APPS setting. Now you can do this:

$ ./manage.py fancy-cache --help
$ ./manage.py fancy-cache
$ ./manage.py fancy-cache /some/searchpath /or/like/*/this.*
$ ./manage.py fancy-cache /some/place/* --purge
$ # or to purge them all!
$ ./manage.py fancy-cache --purge

Note, it will only print out URLs that if found (and purged, if applicable).

The third way to inspect the recorded URLs is to add this to your root urls.py:

url(r'fancy-cache', include('fancy_cache.urls')),

Now, if you visit http://localhost:8000/fancy-cache you get a table listing every URL that django-fancy-cache has recorded.

Optional uses (for the exceptionally curious)

If you have enabled FANCY_REMEMBER_ALL_URLS you can also enable FANCY_REMEMBER_STATS_ALL_URLS in your settings. What this does is that it attempts to count the number of cache hits and cache misses you have for each URL.

This counting of hits and misses is configured to last "a long time". Possibly longer than you cache your view. So, over time you can expect to have more than one miss because your view cache expires and it starts over.

You can see the stats whenever you use any of the ways described in the section above. For example like this:

>>> from fancy_cache.memory import find_urls
>>> found = list(find_urls([]))[0]
>>> found[0]
'/some/page.html'
>>> found[2]
{'hits': 1235, 'misses': 12}

There is obviously a small additional performance cost of using the FANCY_REMEMBER_ALL_URLS and/or FANCY_REMEMBER_STATS_ALL_URLS in your project so only use it if you don't have any smarter way to invalidate, for debugging or if you really want make it possible to purge all cached responses when you run an upgrade of your site or something.

Running the test suite

The simplest way is to simply run:

$ pip install tox
$ tox

Or to run it without tox you can simply run:

$ export PYTHONPATH=`pwd`
$ export DJANGO_SETTINGS_MODULE=fancy_tests.tests.settings
$ django-admin.py test

Changelog

1.2.1
  • Bugfix: conflict between the DummyCache backend when FANCY_USE_MEMCACHED_CHECK_AND_SET is True
1.2.0
  • Restructure the remembered_urls cache dict to clean up stale entries
  • Update FancyCacheMiddleware to match latest Django CacheMiddlware (Also renames to FancyCacheMiddleware)
  • Apply Memcached check-and-set to the delete_keys function if settings.FANCY_USE_MEMCACHED_CHECK_AND_SET = True
  • Drop support for Python <3.6
  • Add support for Python 3.10 and Django 4.0
1.1.0
  • If you use Memcached you can set settings.FANCY_USE_MEMCACHED_CHECK_AND_SET = True so that you can use cache._cache.cas which only workd with Memcached
1.0.0
  • Drop support for Python <3.5 and Django <2.2.0
0.11.0
  • Fix for parse_qs correctly between Python 2 and Python 3
0.10.0
  • Fix for keeping blank strings in query strings. #39
0.9.0
  • Django 1.10 support
0.8.2
  • Remove deprecated way to define URL patterns and tests in python 3.5
0.8.1
  • Ability to specify different cache backends to be used #31
0.8.0
  • Started keeping a Changelog

More Repositories

1

premailer

Turns CSS blocks into style attributes
Python
1,041
star
2

mincss

Tool for finding out which CSS selectors you're NOT using.
Python
855
star
3

minimalcss

Extract the minimal CSS used in a set of URLs with puppeteer
JavaScript
351
star
4

autocompeter

A really fast AJAX autocomplete service and widget
Python
277
star
5

django-static

Template tags for better serving static files from templates in Django
Python
194
star
6

django-cache-memoize

Django utility for a memoization decorator that uses the Django cache framework.
Python
158
star
7

github-pr-triage

A dashboard of Github Pull Requests
JavaScript
149
star
8

tornado-utils

Utility scripts for a Tornado site
Python
135
star
9

tiler

App for allowing you to host some huge ass photos on the web.
JavaScript
127
star
10

django-mongokit

Bridging Django to MongoDB with the MongoKit ODM (Object Document Mapper)
Python
122
star
11

govspy

Go vs. Python
Python
112
star
12

django-sockjs-tornado

Makes it easy to run a SockJS server in Django through Tornado.
Python
102
star
13

hashin

Helping you write hashed entries for packages in your requirements.txt
Python
98
star
14

whatsdeployed

What's deployed from a Github repo on various server environments?
JavaScript
84
star
15

python-gorun

Using (py)inotify to run commands when files change
Python
66
star
16

toocool

too cool for me
JavaScript
62
star
17

worklog

Tornado app behind DoneCal
JavaScript
59
star
18

django-peterbecom

Code for my personal home page
CSS
54
star
19

django-html-validator

A tool to do validation of your HTML generated from your Django app.
Python
47
star
20

tornado_gists

Collaborative collection of Tornado related Github gists
Python
39
star
21

htmltree

Finding out which DOM nodes weigh the most
CSS
28
star
22

premailer.io

A website that uses premailer
JavaScript
25
star
23

docsql

docsQL - Getting an overview over your Markdown file in your Jamstack site
TypeScript
22
star
24

grymt

Preps a set of HTML files for deployment
Python
20
star
25

groce

A mobile web app to help families do grocery and meal planning.
TypeScript
19
star
26

buggy

A client-side wrapper on the bugzilla.mozilla.org REST API.
JavaScript
16
star
27

optisorl

Django backend plugin for sorl-thumbnail that optimizes thumbnails
Python
14
star
28

fastestdb

A collection of benchmarks for which database is the fastest for Tornado
JavaScript
13
star
29

workon

Personally opinionated Todo list in React
JavaScript
9
star
30

minimalcss-website

Single-page-app website for showcasing minimalcss
JavaScript
9
star
31

minimalcss-server

Node Express server to wrap calling minimalcss
JavaScript
8
star
32

django-fastest-redis

Trying different configurations for django-redis
Python
8
star
33

bgg

A love story with Bugzilla, git and Github
Python
8
star
34

django-jingo-offline-compressor

Using jingo and django_compressor but miss offline compression?
Python
8
star
35

next-peterbecom

New front-end for www.peterbe.com
CSS
7
star
36

github-action-tricks

Tips and tricks to make you a GitHub Actions power-user
Shell
7
star
37

django-spellcorrector

Spellcorrector app for Django
Python
6
star
38

json-schema-reducer

Extract from a JSON/dict ONLY whats in the JSON Schema
Python
6
star
39

youshouldwatch-next

A to-watch list of movies and TV shows
TypeScript
6
star
40

IssueTrackerProduct

A bug/issue tracker for Zope2
Python
5
star
41

django-spending

Bengtsson Household Spending app
Python
5
star
42

remix-peterbecom

Front-end for www.peterbe.com in Remix
TypeScript
5
star
43

sockshootout

Comparing WebSockets vs. jQuery AJAX using Tornado
JavaScript
5
star
44

jest-ts-and-http

Node/TypeScript project that uses `jest` to test a local server
TypeScript
5
star
45

slimmer

slimmer
Python
5
star
46

headsupper

Houston. We have commits coming in.
CSS
5
star
47

peepin

Project superseded by https://github.com/peterbe/hashin
Python
5
star
48

howsmywifi

Measure (repeatedly) your broadband speed using Fast.com in a headless browser.
JavaScript
5
star
49

fake-failbot

Mock server to use locally instead of a real FailBot server
JavaScript
5
star
50

django-fastest-cache

Experiment to see speed of using various caching backends
Python
5
star
51

chiveproxy

Experimental React PWA
JavaScript
4
star
52

cheerio-to-text

Turning a Cheerio objects into plain text
TypeScript
4
star
53

ghdocs-goer

A VS Code Extension for people who contribute to https://github.com/github/docs by editing Markdown files in VS Code.
TypeScript
4
star
54

redunter

Hunting down unused CSS since 2015
Python
4
star
55

gg

Git and GitHub for the productivity addicted
Python
4
star
56

python-reverse-geocode-test

Comparing Google Reverse Geocoding against GeoNames
3
star
57

python-donecal

Python interface for the donecal.com restful HTTP API
Python
3
star
58

sockshootout2019

XHR vs WebSockets 2019
JavaScript
3
star
59

hylite

A CLI for syntax highlighting code to HTML
TypeScript
3
star
60

minimalcss2

A Node library to extract the minimal (critical) CSS based on a string of HTML and a string of CSS.
TypeScript
3
star
61

uslicenseplates

US License Plate Spotter
JavaScript
3
star
62

fwc_mobile

Python
3
star
63

esrun-tsnode-esno

ts-node vs. esrun vs. esno vs. bun
TypeScript
3
star
64

rpsls

Rock Paper Scissors Lizard Spock
3
star
65

render-block-images-in-css

Experimenting with inlining CSS images with data URLs
JavaScript
3
star
66

slowpage

Experimenting with browsers' resource download behaviour
Python
3
star
67

SMTPSink

Very basic script for running a SMTP service to see sent emails
Python
2
star
68

mdn-yari-content

All the MDN documents as index.html and index.yaml.
2
star
69

tornado_gkc

GKC (tornado)
JavaScript
2
star
70

minimalcss-cli

JavaScript
2
star
71

activity

An experiment with logging project activities
JavaScript
2
star
72

react-buggy

Side-project in need of a better name
JavaScript
2
star
73

FriedZopeBase

Misc utility Zope2 Product with nifty base classess
JavaScript
2
star
74

kl

Crosstips.org
Python
2
star
75

programmatically-render-next-page

Programmatically render a Next page without a server in Node
TypeScript
2
star
76

podcasttime2

client-side for podcastti.me
JavaScript
2
star
77

dinnerd

Experiment to plan weekly dinners
JavaScript
2
star
78

express-vs-fastify-vs-polka

Comparing Express, Polka, and Fastify for serving static assets
JavaScript
2
star
79

ZSQL

A Zope2 Product for executing SQL in a file based Zope2 product
Python
2
star
80

mdn-nottranslated

Actually NOT Translated on MDN?
JavaScript
2
star
81

fake-hydro

Receive Hydro send events locally
JavaScript
2
star
82

langdetect

Wrapping whatlanggo as a CLI in Go
Go
2
star
83

battleshits

You will never shit in peace
JavaScript
2
star
84

github-slideshow

A robot powered training repository ๐Ÿค–
HTML
2
star
85

primer-autocomplete

A standalone implementation of @primer/react Autocomplete to build a typehead search feature
TypeScript
2
star
86

ws-sane-demo

A playground to play with WebSockets and Sane.
JavaScript
1
star
87

gityouracttogether

Learning how to pretend a commit never happened
1
star
88

zope_products

Old ZOPE products
Python
1
star
89

justmerge

Automatically merge/land GitHub Pull Requests that are ready
Python
1
star
90

http-request-relay

Make HTTP request via distributed AWS Lambda functions
Python
1
star
91

gitbusy

What are you gitting busy with?
JavaScript
1
star
92

django-thuawood

A website for my mom.
Python
1
star
93

elmo-docs

Documentation for the Mozilla Elmo project
Python
1
star
94

django-stephanie

A website for my friend Stephanie Kearley Mรผller
CSS
1
star
95

gaffwall

canvas + slippy map
JavaScript
1
star
96

spellthese

"Train your own spell corrector with TextBlob" blog post demo code
HTML
1
star
97

mondayosaseri

1
star
98

lang-analyze

A scrappy script to analyze the state of translated documents in MDN.
JavaScript
1
star
99

classy

An online Bayesian classifier for anybody via a REST API
JavaScript
1
star
100

aroundtheworld

JavaScript
1
star