Skip to content

Commit

Permalink
Update proxycache.py
Browse files Browse the repository at this point in the history
  • Loading branch information
moraroy authored Dec 10, 2024
1 parent 2d75e13 commit 838c763
Showing 1 changed file with 35 additions and 12 deletions.
47 changes: 35 additions & 12 deletions proxycache/proxycache.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from steamgrid.enums import PlatformType
from datetime import datetime, timedelta
import logging
import time

# Initialize logging
logging.basicConfig(level=logging.INFO)
Expand Down Expand Up @@ -38,15 +39,28 @@
@limits(calls=RATE_LIMIT, period=RATE_LIMIT_PERIOD)
def limited_request(url, headers):
try:
response = session.get(url, headers=headers)
response.raise_for_status()
# Set a timeout to prevent long hanging connections
response = session.get(url, headers=headers, timeout=10) # Timeout set to 10 seconds
response.raise_for_status() # Will raise HTTPError for bad responses (4xx, 5xx)
return response
except RateLimitException as e:
logger.error(f"Rate limit exceeded: {e}")
raise
except requests.exceptions.Timeout as e:
logger.error(f"Request timed out: {e}")
raise
except requests.exceptions.ConnectionError as e:
logger.error(f"Connection error: {e}")
raise
except requests.exceptions.RequestException as e:
# Handles all other request errors
logger.error(f"Request error: {e}")
raise
except requests.exceptions.RemoteDisconnected as e:
logger.error(f"Remote disconnected: {e}")
# Optionally retry after a short delay, or log the issue and return None
time.sleep(2) # Retry after 2 seconds or use exponential backoff
return limited_request(url, headers) # Retry the request

def sanitize_game_name(game_name):
# Remove special characters like ™ and ®
Expand Down Expand Up @@ -86,6 +100,18 @@ def do_GET(self):

self.handle_artwork(game_id, art_type, dimensions)

def do_HEAD(self):
self.do_GET() # Use the same handling logic as GET requests
self.send_response(200) # OK status
self.end_headers() # Only send headers, no content (body)
logger.info(f"HEAD request handled for: {self.path}")

def do_OPTIONS(self):
self.send_response(200) # OK status
self.send_header('Allow', 'GET, POST, HEAD, OPTIONS') # Allow the methods you support
self.end_headers()
logger.info(f"OPTIONS request handled for: {self.path}")

def handle_search(self, game_name):
logger.info(f"Searching for game ID for: {game_name}")

Expand Down Expand Up @@ -183,22 +209,19 @@ def handle_artwork(self, game_id, art_type, dimensions):
logger.error(f"Error making API call: {e}")
self.send_response(500)
self.end_headers()
self.wfile.write(b'Error making API call')
self.wfile.write(b'Error fetching artwork')
return

if 'data' not in data:
self.send_response(500)
self.end_headers()
self.wfile.write(b'Invalid response from API')
return

# Send the response
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(data).encode())

def is_cache_valid(self, cache_entry):
cache_expiry = timedelta(hours=168) # Set cache expiry time
return datetime.now() - cache_entry['timestamp'] < cache_expiry
def is_cache_valid(self, cached_item):
expiration_time = timedelta(hours=1)
return datetime.now() - cached_item['timestamp'] < expiration_time


def run(server_class=HTTPServer, handler_class=ProxyCacheHandler):
port = int(os.environ.get('PORT', 8000)) # Use the environment variable PORT or default to 8000
Expand Down

0 comments on commit 838c763

Please sign in to comment.