-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7bece12
commit 3f6617e
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
#!/usr/bin/env python3 | ||
"""A module with tools for request caching and tracking. | ||
""" | ||
import redis | ||
import requests | ||
from functools import wraps | ||
from typing import Callable | ||
|
||
|
||
redis_store = redis.Redis() | ||
"""The module-level Redis instance. | ||
""" | ||
|
||
|
||
def data_cacher(method: Callable) -> Callable: | ||
"""Caches the output of fetched data.""" | ||
|
||
@wraps(method) | ||
def invoker(url) -> str: | ||
"""The wrapper function for caching the output.""" | ||
redis_store.incr(f"count:{url}") | ||
result = redis_store.get(f"result:{url}") | ||
if result: | ||
return result.decode("utf-8") | ||
result = method(url) | ||
redis_store.set(f"count:{url}", 0) | ||
redis_store.setex(f"result:{url}", 10, result) | ||
return result | ||
|
||
return invoker | ||
|
||
|
||
@data_cacher | ||
def get_page(url: str) -> str: | ||
"""Returns the content of a URL after caching the request's response, | ||
and tracking the request. | ||
""" | ||
return requests.get(url).text |