Caching
Masonite provides a powerful caching feature to keep any data cached that may be needless or expensive to fetch on every request.
Masonite caching allows you to save and fetch data, set expiration times and manage different cache stores.

Adding Cache Data

You can easily add cache data using theadd method. This will either fetch the data already in the cache, if it is not expired, or it will insert the new value.
1
def store(self, cache: Cache):
2
data = cache.add('age', '21')
Copied!
If age key exists in the cache AND it is not expired, then "21" will be added to the cache and returned. If the age key does not exist or is not expired then it will return whatever data is in the cache for that key.

Putting Cache Data

The add method will either return data already in the cache or put data into the cache. The put method will put data into the cache regardless of if it exists already. This is a good way to overwrite data in the cache:
1
cache.put('age', '21')
Copied!
You can specify the number of seconds that the cache should be valid for. Do not specify any time or specify None to keep the data forever.
1
cache.put('age', '21', seconds=300) # stored for 5 minutes
Copied!
You may also cache lists and dictionaries which will preserve the data types:
1
cache.put('user', {"name": "Joe"}, seconds=300) # stored for 5 minutes
2
cache.get("user")['name'] #== "Joe"
Copied!

Getting Cache Data

You can get cache data from the cache. If the data is expired then this will either return None or the default you specify:
1
cache.get('age', '40')
Copied!
This will either fetch the correct age data from the cache or return the default value of 40.

Checking Existence

You can also see if a value exists in the cache (and it is not expired):
1
cache.has('age')
Copied!

Forgetting a Cache Item

If you want to forget an item in the cache you can:
1
cache.forget('age')
Copied!
This will remove this item from the cache.

Increment / Decrement

You can increment and decrement a value if it is an integer:
1
cache.get('age') #== 21
2
cache.increment('age') #== 22
3
cache.decrement('age') #== 21
Copied!

Remembering

Remembering is a great way to save something to a cache using a callable:
1
from app.models import User
2
3
remember("total_users", lambda cache: (
4
cache.put("total_users", User.all().count(), 300)
5
))
Copied!

Flushing the Cache

To delete everything in the cache you can simply flush it:
1
cache.flush()
Copied!
Last modified 18d ago