File: cache.md

package info (click to toggle)
python-beanie 2.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,480 kB
  • sloc: python: 14,427; makefile: 7; sh: 6
file content (42 lines) | stat: -rw-r--r-- 993 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Cache
All query results could be locally cached.

This feature must be explicitly turned on in the `Settings` inner class.

```python
class Sample(Document):
    num: int
    name: str

    class Settings:
        use_cache = True
```

Beanie uses LRU cache with expiration time. 
You can set `capacity` (the maximum number of the cached queries) and expiration time in the `Settings` inner class.

```python
class Sample(Document):
    num: int
    name: str

    class Settings:
        use_cache = True
        cache_expiration_time = datetime.timedelta(seconds=10)
        cache_capacity = 5
```

Any query will be cached for this document class.

```python
# on the first call it will go to the database
samples = await Sample.find(num>10).to_list()

# on the second - it will use cache instead
samples = await Sample.find(num>10).to_list()

await asyncio.sleep(15)

# if the expiration time was reached it will go to the database again
samples = await Sample.find(num>10).to_list()
```