Skip to content

Commit

Permalink
Web.py: fix
Browse files Browse the repository at this point in the history
  • Loading branch information
micahondiwa committed Jan 7, 2024
1 parent 7bece12 commit 3f6617e
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions 0x02-redis_basic/web.py
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

0 comments on commit 3f6617e

Please sign in to comment.