Saravanan666/pypi-org huggingface dataset:
Package: django-cached-fields
django-cached-fieldsCached fields for DjangoUsageDefining a basic Cached FieldThe first argument of the CachedField constructor can be the name of a method on the class.This method only works with field triggers as signal triggers will require aCachedFieldSignalHandler.classInvoice(models.Model):name=models.TextField(null=False)quantity=models.IntegerField()amount=models.IntegerField(null=False)defcalc_total(self):self.total=self.quantity*self.amounttotal=CachedIntegerField('calc_total',field_triggers=['amount',],timeout=timedelta(seconds=5),)If you would like your cached field's callback to be triggered by a signal, you will need to create a signal handler.classInvoiceSignalHandler(CachedFieldSignalHandler):defcalc_total(instance):instance.total=instance.quantity*instance.amount@for_class('Customer')defcutomer_total(customer):returninvoice.quantity*invoice.amount@for_class('Supplier')defsupplier_total(supplier):invoice=supplier.invoice.last()returninvoice.quantity*invoice.amountIf you would like to offload task processing to Celery, django-cached-fields can handle that for you automatically.settings.pyCACHED_FIELDS_CELERY_ENABLED=TrueCACHED_FIELDS_CELERY={"queue":"default"}If you'd like to offload a recalculation to a specific queue, you can do this.classInvoiceSignalHandler(CachedFieldSignalHandler):defcalc_total(instance):instance.total=instance.quantity*instance.amount@for_class('Customer',queue="low_priority")defcutomer_total(customer):invoices=customer.invoices.all()foriininvoices:i.cache_toolkit.update_cache('total',i.quantity*i.amount)i.save()@for_class('Supplier')defsupplier_total(supplier):invoice=supplier.invoice.last()invoice.total=invoice.quantity*invoice.amountForce Recalculationym=YourModel.objects.create(name="fart",amount=6)ym.cache_toolchain.refresh_field('total')Get last time the cache was updatedFor when you need to run queries
```python
In [2]: print(ym.total_last_update)
Out[2]: datetime.datetime(2019,10,30,4,30,54)In [3]: YourModel.objcts.filter(total_last_update__date__gte=date(2019,10,1)).exists()
Out[3]: True
Package: django-cached-hitcount
Django-Cached-HitCount===============Basic app that allows you to track the number of hits/views for a particularobject.All hits are stored in memcache until persisted to database.As the hits are stored in cache there are no DB queries/inserts/updates on each request.Adding hits is done via an ajax call so that app can still be used on cached views.You can persist the hits to DB using celery and the `persist_hits` periodic task or use the `persist_hits` management command.python manage.py persist_hitshitcount_example app shows how to use app, by using `get_hit_count_javascript_template` and `get_hit_count` template tags.Available settings are:* HITCOUNT_CACHE -The CACHES setting dict key to use for caching hits (default is `cached_hitcount`)* HITCOUNT_CACHE_TIMEOUT - How long in seconds should the hits be cached for before persisted  (default is `600`)* HITCOUNT_IP_CACHE_TIMEOUT - How long in seconds should the black list ip addresses be cached for  (default is `86400` seconds = 1 day)* HITCOUNT_PERSIST_SCHEDULE - How often should the hits be persisted  (default is `15` minutes)* HITCOUNT_IP_CACHE - key name to use for caching the blacklist ip addresses  (default is `hitcount__blacklistip`)* HITCOUNT_EXCLUDE_IP_ADDRESS - Whether or not you want to exclude some ip addresses  (default is True)* HITCOUNT_EXCLUDE_BOTS - Whether or not you exclude bots (default is True)* HITCOUNT_LOCK_KEY - key name to use for locking when persisting hits to DB* HITCOUNT_CSRF_EXEMPT - Whether or not ajax view is CSRF exempt by default. Useful if the pages you are using hitcount on are cached. (default is False)* HITCOUNT_SERVER_CALLBACKS - Dict with with value as tuple of module and method to call on server. (default is {})* HITCOUNT_CLIENT_CALLBACKS - List of Javascript functions to call when response is received. Response is passed to these functions. (default is [])Also a gargoyle switch `cached_hitcount` to switch on/off all hit counting (default is True)This app was very much inspired by <http://damontimm.com/code/django-hitcount/>Installation:-------------Simplest way to formally install is to run:./setup.py installOr, you could do a PIP installation:pip install -e git://github.com/philroche/django-cached-hitcount.git#egg=django-cached-hitcountOr using PyPipip install django-cached-hitcountCopyright:-------------This package is © 2014 Philip Roche, released under the terms of the GNU GPL v3 (or at your option a later version).
Package: django-cached-httpbl
django-cached-httpbldjango-cached-httpblis a cached httpBL service support for Django 1.7+Requirementsdjango>=1.7
django-appconf>=0.6
django-ipware>=1.1.3InstallationDownload and installdjango-cached-httpblusingoneof the following methods:PIPYou can install the latest stable package running this command:$ pip install django-cached-httpblAlso you can install the development version running this command:$ pip install -e git+http://github.com/dlancer/django-cached-httpbl.git#egg=django-cached-httpblSetuptoolsYou can install the latest stable package running:$ easy_install django-cached-httpblUsageYou may find detailed documentation in the “docs” directory.
Package: django-cachedpaginator
django-cachedpaginator============# AboutA paginator that caches pages and result count. Very handy when you need to paginate an expensive queryThis application was inspired by https://djangosnippets.org/snippets/1173/## Changelog* 0.0.4: Adds support for jinja. You should call the paginate function instad of using it as a tagBuild Status============[![Build Status](https://travis-ci.org/arsham/django-cachedpaginator.svg?branch=master)](https://travis-ci.org/arsham/django-cachedpaginator)## Usage### ViewIn your view:```pythonfrom django_cachedpaginator import Paginator, PageNotAnInteger, EmptyPagedef my_view(request):cache_key = 'user_your_own_key'cache_timeout = 600 # 10 minutescount_timeout = 3600page = request.GET.get('page')object_list = ExpensiveModel.objects.all()paginator = Paginator(object_list, 20, cache_key, cache_timeout, count_timeout)try:object_list = object_list.page(page)except PageNotAnInteger:object_list = object_list.page(1)except EmptyPage:object_list = object_list.page(image_list.num_pages)```Or in you CBV view:```pythonfrom django_cachedpaginator import CachedPaginatorViewMixinclass MyView(CachedPaginatorViewMixin, ListView):....paginate_by = 7cache_timeout = 60cache_key = "my_view"```And it will automatically caches the pagination.## TemplatesIMPORTANT: Make sure you add 'django_cachedpaginator' to your INSTALLLED_APPS settings, otherwide django cannot load the tagAll you need to do is to load the tags and pass your object_list to paginator tag like so:In django templates:```twig{% load cached_paginator %}...{% paginate object_list %}```In jinja2 templates:```twig...{{ paginate(object_list) }}```If you want to override the template that is used to render the paginator, you have a couple of options:* Either create a file in your template folder (the one you've set in your settings file) by this name: django_cachedpaginator/paginator_template.html* or set this variable in your settings file: PAGINATOR_TEMPLATE = 'path/to/your/template'# SettingsYou can set any of these in your settings file if you needed to:PAGINATOR_TOTAL_PAGESdefault: 10PAGINATOR_TEMPLATEdefault: 'django_cachedpaginator/paginator_template.html'PAGINATOR_ID_PREFIXdefault: 'paginator_page'purpose: element's id prefix in your outputPAGINATOR_FIRST_CLASSdefault: 'first'purpose: element's class in your outputPAGINATOR_FIRST_VERBOSEdefault: 'First'purpose: String to show.PAGINATOR_PREVIOUS_CLASSdefault: 'previous'PAGINATOR_PREVIOUS_VERBOSEdefault: 'Previous'PAGINATOR_NEXT_CLASSdefault: 'next'PAGINATOR_NEXT_VERBOSEdefault: 'Next'PAGINATOR_LAST_CLASSdefault: 'last'PAGINATOR_LAST_VERBOSEdefault: 'Last'PAGINATOR_PAGE_PARAMETERdefault: 'page'purpose: name of the parameter in your query string# Notescache_timeout nad count_timeout are measured in seconds and are optional. Defaults are 300 and 600.There is no need to add the page in cache_key because Paginator takes care of it. Actually here is a list of variables added to key:* cache_key* per_page* page_number* cache_timeout* count_timeoutTherefore when you change any of these, your previous cache expires.
Package: django-cached-s3-storage
This package contains a CachedS3BotoStorage to be used with django-compressor and S3.Code copied fromhttps://github.com/jezdez/django_compressor/issues/100.Example settings:DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
STATICFILES_STORAGE = 'cached_s3_storage.CachedS3BotoStorage'
COMPRESS_STORAGE = STATICFILES_STORAGE

AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']
AWS_PRELOAD_METADATA = True
AWS_IS_GZIPPED = True
AWS_QUERYSTRING_AUTH = False

from django.utils.http import http_date
from time import time
max_age = 31536000
AWS_HEADERS = {
        'x-amz-acl': 'public-read',
        'Expires': http_date(time() + max_age),
        'Cache-Control': 'public, max-age=' + str(max_age)
}
Package: django-cache-expression-language
Django Cache Expression Language (DCEL)IntroductionDCEL is an extension of Django Framework for caching. It provides a more flexible decorator that use an expression language to define the cache key.Getting StartedCache MethodUse@Cacheddecorator to declare a cached method. This will check the cache before executing the actual method. If the defined key is already cached, it'll immediately return the cached return value. Else, it will execute the actual method, and update the cache using the defined key and return value.class StudentService:
    def __init__(self):
        self.students = []

    @Cached(key='{id}', duration=timedelta(minutes=5))
    def read(self, id: UUID) -> Optional[dict]:
        return first(
            filter(
                lambda s: s['id'] == id, self.students
            ),
            None
        )Use@CacheUpdatedecorator to declare a cache update method. This will update the cache using the defined key and return value after executing the actual method.class StudentService:
    def __init__(self):
        self.students = []

    @CacheUpdate(key='{id}', duration=timedelta(minutes=5))
    def update(self, id: UUID, name: str) -> dict:
        student = self.read(id)
        student['name'] = name
        return studentUse@CacheInvalidatedecorator to declare a cache invalidate method. This will invalidate cache using the defined key after method executing the actual method.class StudentService:
    def __init__(self):
        self.students = []

    @CacheInvalidate(key='{id}')
    def delete(self, id: UUID) -> dict:
        student = self.read(id)
        self.students.remove(student)
        return studentCache KeyCache key is derived from method argument. The syntax is similar to pythonf-string, with some limitation. You can define key using primitive, object, dictionary, list, tuple data type variable. Variable should be enclosed in curly braces ({}), and string index should be enclosed in quotation mark (""or'').class UtilService:

    @staticmethod
    @Cached(key='sum: {a} {b}')
    def sum(a: int, b: int) -> int:
        return a + b

    @staticmethod
    @Cached(key='join name: {a["name"]} {b["name"]}')
    def join_name(a: dict, b: dict) -> str:
        return ''.join((a['name'], b['name']))

    @staticmethod
    @Cached(key='is lowest: {values[0]} {values[-1]}')
    def is_lowest(values: Union[list, tuple]) -> bool:
        return values[0] <= values[-1]

    @staticmethod
    @Cached(key='duration: {started_at.day} {finished_at.day}')
    def duration(started_at: datetime, finished_at: datetime) -> timedelta:
        return finished_at - started_atNested variable, for examplejoin_name: {a[b["name"]]}is not supported.
Package: django-cache-fallback
Info:This is the README file for Django Cache Fallback.Author:Jakub StawowyPURPOSEAllows you to set fallback cache backend (multiple cache backend).
The data is not shared between cache backends.
Example: Memcached is not available, backend switch to fallback. Site may slow down (cache have to be set)
but will not rise an error (watch your logs)INSTALLATIONpipinstalldjango-cache-fallbackINSTALLED_APPS=(...'cache_fallback',)USAGEUsage example PyLibMCCache + LocMemCacheCACHES={'default':{'BACKEND':'cache_fallback.FallbackCache',},'main_cache':{'BACKEND':'django.core.cache.backends.memcached.MemcachedCache','LOCATION':'/tmp/memcached.sock','TIMEOUT':500,},'fallback_cache':{'BACKEND':'django.core.cache.backends.locmem.LocMemCache','LOCATION':'unique'}}
Package: django-cache-fn
Cache FnUse django cache to cache thefunction(*arg, **kw)with timeout.Quick startInstall::pip install django-cache-fnStart to use it in codefrom cache_fn.decorators import cache_fn

   @cache_fn(prefix='myprefix', timeout=3600)
   def foo(k1, k2):
      return "%s %s"%(k1, k2)Usagedef cache_fn(timeout=1, prefix=None, cache_ttl=MEMCACHE_MAX_EXPIRATION):
    """
    Retrieve data from cache if cacheable and no-stale,
    otherise refresh synchronously and cache it.
    * timeout: The stale timeout which would be handled in the decorator.
    * prefix: The prefix of cache key.
    * cache_ttl: The TTL(time to live) of key in memcache.
    NOTE: For HttpResponse, we just cache the response whose status code is 200.
    """
Package: django-cache-helper
django-cache-helperOverviewdjango-cache-helper is a simple tool for making caching functions, methods, and class methods a little bit easier.
It is largely based off of django-cache-utils, however, since cache-utils did not support caching model methods by instance and carried other features I didn't need, django-cache-helper was created.In order to cache and invalidate a function/method/class_method/static_method:SupportPython3.7, 3.8, 3.9, 3.10How to Cache# Caching a function@cached(60*60)# 60 Minutesdeffoo(bar):returnbarclassIncrementer:@cached_instance_method(60*60)definstance_increment_by(self,num):returnnum@classmethod@cached_class_method(60*60)defclass_increment_by(cls,num):returnnum@staticmethod@cached(60*60)defget_datetime():returndatetime.utcnow()How to invalidate a cachefoo(1)foo.invalidate(1)Incrementer.instance_increment_by(1)Incrementer.instance_increment_by.invalidate(1)Incrementer.class_increment_by(1)Incrementer.class_increment_by.invalidate(1)Incrementer.get_datetime()Incrementer.get_datetime.invalidate()Contributors ✨Thanks goes to these wonderful people.Kevin FoxTom JakewayAra AnjargolianHyuckin David LimJames
Package: django-cachekiller
django-cachekillerdjango-cachekilleris a small add-on for Django that adds thecdnstatictemplate tag which adds a 'cache busting' dynamic query string appended to the
file paths. This tag functions identically to the standard{% static ... %}template tag. This is designed to work with CDNs that cache by complete URI
including the query string so when you push a change the CDNs are automatically
refreshed without having to wait for TTLs to expire. Internally we use this withdjango-distill, a static site generator for Django to work with static sites
with heavy caching on images behind CloudFlare, cachefly and other CDNs:https://github.com/meeb/django-distillUnder the hood, this module just chains the request to the existingstatictag
to be widely compatible.InstallationInstall from pip:$pipinstalldjango-cachekillerAdddjango_cachekillerto yourINSTALLED_APPSin yoursettings.py:INSTALLED_APPS=[# ... other apps here ...'django_cachekiller',]That's it.UsageLoad the new module at the top of your templates:{% load cdnstaticfiles %}Then use the new tag in the template exactly as you would use thestatictag:{% cdnstatic 'some/image.jpg' %}This renders as (assumingsettings.STATIC_URLis set to/static/):/static/some/image.jpg?tag=[random tag][random tag]is either the truncated mercurial or git commit reference if it
is available, otherwise it will be the current date inYYYYMMDDHHMMSSformat.
If there are existing query string parameters then thetagis intelligently
appended. Thecdnstatictag will not break the existing URL.Additionally, if you need to just access the[random tag]for some other use
without the automatic URL rewriting you can use the following:<ahref="/someurl.html?tag={% cdntag %}">link</a>This can be used in conjunction with other URL wrapping tags for combatability
where chaining tags is difficult, for example:<linkrel="stylesheet"href="{% sass_src 'file.scss' %}?tag={% cdntag %}">ContributingAll properly formatted and sensible pull requests, issues and comments are
welcome.
Package: django-cache-lock
django-cache-lockA simple lock extension for django's cache to prevent concurrent editing.InstallationInstall django-cache-lock by using pippip install django-cache-lockQuick StartYou can work with django-cache-lock by using with-statement or decorator.from django_lock import lock

with lock("global"):
    pass

@lock("global")
def foo():
    passA shortcut to lock model instancefrom django.db import models
from django_lock import model_lock

class Foo(models.Model):
    bar = models.CharField(max_length=8)

    @lock_model
    def lock_pk(self):
        pass

    @lock_model("bar", blocking=False)
    def lock_bar(self):
        pass

    def nolock(self):
        pass

foo = Foo()
with lock_model(foo, blocking=False):
    nolock()ConfigurationskeydefaultdescDJANGOLOCK_PREFIX"lock:"lock's key prefix stored in cacheDJANGOLOCK_SLEEP0.1default interval time to acquire a lock if a lock is holded by othersDJANGOLOCK_RELEASEONDELTruerelease lock when__del__is called if TrueAdvanced usageFor more usages, please read thecode.Supported backendsdjango.core.cache.backends.dbdjango.core.cache.backends.filedjango.core.cache.backends.locmemdjango.core.cache.backends.memcacheddjango-redisdjango-redis-cacheATTENTIONSlocmem backendDO NOT USE locmem backend in a product environment.memcached backendMemcached does not support milliseconds expire time, and its' expire time is not very exact. So memcached lock's timeout time is not as exact as other backends.redis backendWe didn't test distributed redis lock.TODOS:use memcached's cas to release lockreacquire and extend lockdatabase backend cache support
Package: django-cache-machine
Cache Machine provides automatic caching and invalidation for Django models
through the ORM.For full docs, seehttps://cache-machine.readthedocs.org/en/latest/.RequirementsCache Machine currently works with:Django 2.2, 3.0, 3.1, 3.2, and 4.0Python 3.6, 3.7, 3.8, 3.9, and 3.10The last version to support Python 2.7 and Django 1.11 isdjango-cache-machine==1.1.0.InstallationGet it frompypi:pip install django-cache-machineRunning TestsGet it fromgithub:git clone git://github.com/django-cache-machine/django-cache-machine.git
cd django-cache-machine
pip install -r dev-requirements.txt
python run_tests.py
Package: django-cache-machine-2.0
Cache Machine provides automatic caching and invalidation for Django models
through the ORM.For full docs, seehttps://cache-machine.readthedocs.org/en/latest/.RequirementsCache Machine works with Django 1.8-2.0 and Python 2.7, 3.4, 3.5 and 3.6.InstallationGet it frompypi:pip install django-cache-machineRunning TestsGet it fromgithub:git clone git://github.com/django-cache-machine/django-cache-machine.git
cd django-cache-machine
pip install -r requirements/py3.txt  # or py2.txt for Python 2
python run_tests.py
Package: django-cache-magic
Django-Cache-Magic================Cache magic addresses two common scenarios for caching and cache invalidationfor django models: *instance caching* and *related objects caching*.Instance caching: Storing instances of objects in your cache layeras well as your database.Related objects caching: Storing a collection of objects related to anotherobject referenced by relational constraints (ForeignKey, ManyToMany, etc.)Installing----------pip install -e "git+https://github.com/ntucker/django-cache-magic#egg=cachemagic"Usage-----To start autocaching model instances, add a CacheController to your model:from django.db import modelsfrom cachemagic import CacheControllerclass myModel(models.Model):f1 = models.IntegerField()f2 = models.TextField()cache = CacheController()myModel.cache.get(pk=27)When using cachemagic, you should avoid django operations that update multiplerows at once, since these operations typically don't emit the signals thatcachemagic relies on for cache invalidation. This includes methods like[`Queryset.update`](https://docs.djangoproject.com/en/1.3/ref/models/querysets/#update),[`Queryset.delete`](https://docs.djangoproject.com/en/1.3/ref/models/querysets/#delete),and[`RelatedManager.clear`](https://docs.djangoproject.com/en/1.3/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear)Find the complete documentation at [django-cache-magic.readthedocs.org](http://django-cache-magic.readthedocs.org/).Thanks------Big thanks to [Travis Fischer](https://github.com/travisfischer) for draftinga lot of documentation and tests!
Package: django-cache-management
This is a Django application that adds management commands for
managing your caches.It has been tested with these combinations:Python 3.6, 3.7, 3.8, 3.9 and Django 2.2, 3.0, 3.1.This code is currently used in production.It provides these commands:listcaches: lists the caches configured in your Django project.pingcache: verifies that one or more caches are accessible
(“pings” them).clearcache: clears one or more caches.### Changelog5.0.0:Fix setup.py to avoid packaging the folders that pertain only to
development.Drop support for Django 1.1. It reached EOL.Drop support for Python 3.5. We’re two weeks away from its EOL.Formally test on Python 3.6 and 3.8.Formally test on Django 3.0 and 3.1. (It was already compatible but now tox
run tests on these versions.)4.0.1:Don’t use or requiresixanymore. It was an oversight that it stayed in
after we dropped support for Python 2.7.4.0.0:Formally support Django 2.2. (This package already worked fine on it.)Drop support for Django 2.0. It reached EOL.Drop support for Python 2.7 and 3.4.3.0.0:Drop support for Django versions prior to 1.11. This is a breaking change
and so require a new major number.Formally support 1.11, 2.0 and 2.1. (This package already worked fine on
them.)2.0.0:Formally follow the semver spec for version numbers. Previous
version numbers were bumped haphazardly.Drop support for Django 1.7.Fix problems with running on Django 1.10. Version 1.0.1 was
supposed to support Django 1.10 but I discovered, much to my
displeasure, thattoxsilently disregarded the disconnect
between its test specification (“please install Django 1.10.x”)
and a mistake insetup.py(“I want a Django version lower than
1.10”). The net result was that the tests that were supposed to be
done with 1.10 were done with a lower version…sigh.listcachesnow supports the case where the configuration
settings for caches contain unserializable values.1.0.1:Added formal support for Django 1.9, 1.10. The previous version
was already running fine on them, but the dependencies and the
test setup have been tweaked for these versions of Django.Drop support for Django 1.6.