File: url_patterns.py

package info (click to toggle)
python-requests-cache 1.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 6,024 kB
  • sloc: python: 7,029; makefile: 4
file content (53 lines) | stat: -rwxr-xr-x 1,583 bytes parent folder | download
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
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python
# fmt: off
"""
An example of {ref}`url-patterns`
"""
from datetime import timedelta

from requests_cache import DO_NOT_CACHE, NEVER_EXPIRE, CachedSession

default_expire_after = 60 * 60               # By default, cached responses expire in an hour
urls_expire_after = {
    'httpbin.org/image': timedelta(days=7),  # Requests for this base URL will expire in a week
    '*.fillmurray.com': NEVER_EXPIRE,        # Requests matching this pattern will never expire
    '*.placeholder.com/*': DO_NOT_CACHE,     # Requests matching this pattern will not be cached
}
urls = [
    'https://httpbin.org/get',               # Will expire in an hour
    'https://httpbin.org/image/jpeg',        # Will expire in a week
    'https://www.fillmurray.com/460/300',    # Will never expire
    'https://via.placeholder.com/350x150',   # Will not be cached
]


def send_requests():
    session = CachedSession(
        cache_name='example_cache',
        expire_after=default_expire_after,
        urls_expire_after=urls_expire_after,
    )
    return [session.get(url) for url in urls]


def _expires_str(response):
    if not response.from_cache:
        return 'N/A'
    elif response.expires is None:
        return 'Never'
    else:
        return response.expires.isoformat()


def main():
    send_requests()
    cached_responses = send_requests()
    for response in cached_responses:
        print(
            f'{response.url:40} From cache: {response.from_cache:}'
            f'\tExpires: {_expires_str(response)}'
        )


if __name__ == '__main__':
    main()