

Requests-Cache는 Python Requests 라이브러리로 더 나은 성능을 얻을 수있는 쉬운 방법을 제공하는 지속적인 HTTP 캐시입니다.
완전한 프로젝트 문서는 requests-cache.readthedocs.io에서 찾을 수 있습니다.
requests 라이브러리를 계속 사용하십시오. requests.Session 에 대한 드롭 인 교체로 캐싱을 추가하거나 모든 requests 기능에 투명 캐싱을 추가하려면 전 세계적으로 설치하십시오.먼저 PIP로 설치하십시오.
pip install requests-cache그런 다음 requests_cache.cachedsession을 사용하여 요청을하십시오. 그것은 정상적인 요청처럼 동작하지만, 세션이지만 캐싱 동작이 있습니다.
예를 들어, 느린 또는 속도 제한 웹 사이트를 시뮬레이션하는 1 초의 지연을 추가하는 엔드 포인트를 호출합니다.
1 분이 걸립니다.
import requests
session = requests . Session ()
for i in range ( 60 ):
session . get ( 'https://httpbin.org/delay/1' )1 초가 걸립니다.
import requests_cache
session = requests_cache . CachedSession ( 'demo_cache' )
for i in range ( 60 ):
session . get ( 'https://httpbin.org/delay/1' ) 캐싱을 사용하면 응답이 한 번 가져 와서 demo_cache.sqlite 에 저장되며, 후속 요청은 캐시 된 응답을 거의 근접하게 반환합니다.
세션 객체를 관리하지 않거나 코드를 수정하지 않고 애플리케이션에서 신속하게 테스트하려면 Requests-Cache를 전역으로 설치할 수 있으며 모든 요청은 투명하게 캐싱됩니다.
import requests
import requests_cache
requests_cache . install_cache ( 'demo_cache' )
requests . get ( 'https://httpbin.org/delay/1' )기본적으로 요청 캐시는 캐시 된 응답을 무기한으로 유지합니다. 대부분의 경우 다음 두 가지 전략 중 하나를 사용하여 캐시 신선도와 성능의 균형을 맞추려고합니다.
응답을 유지하는 데 얼마나 오래 정의하십시오.
expire_after 매개 변수를 사용하여 모든 새로운 응답에 대한 고정 만료 시간을 설정하십시오.
from requests_cache import CachedSession
from datetime import timedelta
# Keep responses for 360 seconds
session = CachedSession ( 'demo_cache' , expire_after = 360 )
# Or use timedelta objects to specify other units of time
session = CachedSession ( 'demo_cache' , expire_after = timedelta ( hours = 1 ))더 많은 기능과 설정은 만료를 참조하십시오.
캐시 제어 헤더 사용 :
cache_control 매개 변수를 사용하여 Cache-Control 및 기타 표준 HTTP 헤더를 기반으로 자동 만료를 활성화하십시오.
from requests_cache import CachedSession
session = CachedSession ( 'demo_cache' , cache_control = True )자세한 내용은 캐시 헤더를 참조하십시오.
기본 설정은 대부분의 사용 사례에서 잘 작동하지만 필요할 때 캐싱 동작을 사용자 정의하는 방법에는 여러 가지가 있습니다. 다음은 사용 가능한 일부 옵션의 빠른 예입니다.
from datetime import timedelta
from requests_cache import CachedSession
session = CachedSession (
'demo_cache' ,
use_cache_dir = True , # Save files in the default user cache dir
cache_control = True , # Use Cache-Control response headers for expiration, if available
expire_after = timedelta ( days = 1 ), # Otherwise expire responses after one day
allowable_codes = [ 200 , 400 ], # Cache 400 responses as a solemn reminder of your failures
allowable_methods = [ 'GET' , 'POST' ], # Cache whatever HTTP methods you want
ignored_parameters = [ 'api_key' ], # Don't match this request param, and redact if from the cache
match_headers = [ 'Accept-Language' ], # Cache a different response per language
stale_if_error = True , # In case of request errors, use stale cache data if possible
)요청 캐시로 수행 할 수있는 일에 대한 자세한 내용은 다음을 참조하십시오.