i built a server (in python) thats is simultion http cache, but i have problem like: the first time i send a get request from the browser to the server the server sends the file and second time its sends 304 not modified because the file didnt changed, and then the third time when i request the same file the server is not responding.
the server:
import socket import os from datetime import datetime from email.utils import formatdate, parsedate_to_datetime class HTTPServer: def __init__(self, host='0.0.0.0', port=8080, folder='files'): self.host = host self.port = port self.folder = folder def get_file_response(self, filename, if_modified_since=None): filepath = os.path.join(self.folder, f"{filename}.txt") if not os.path.exists(filepath): return b"HTTP/1.1 404 Not FoundrnrnFile not found." last_modified = os.path.getmtime(filepath) #gemtime gets the last time a file has changed last_modified_http = formatdate(last_modified, usegmt=True) if if_modified_since: try: client_time = parsedate_to_datetime(if_modified_since).timestamp() print("🕒 client_time:", int(client_time)) print("🕒 file last_modified:", int(last_modified)) # Compare with small tolerance to avoid sub-second mismatch if abs(client_time - last_modified) < 1: print("🔁 Sending 304 Not Modified") return b"HTTP/1.1 304 Not ModifiedrnConnection: closernrn" except Exception as e: print("⚠️ Failed to parse If-Modified-Since:", e) with open(filepath, 'r') as f: content = f.read() response = ( "HTTP/1.1 200 OKrn" f"Last-Modified: {last_modified_http}rn" "Content-Type: text/plainrn" f"Content-Length: {len(content)}rn" "Cache-Control: public, max-age=3600rn" "Connection: closern" # 👈 This line is key "rn" f"{content}" ) return response.encode() def start(self): print(f"📡 Server listening on {self.host}:{self.port}") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((self.host, self.port)) s.listen(5) while True: conn, addr = s.accept() print(f"n📥 Connection from {addr}") try: conn.settimeout(5) data = conn.recv(1024) if not data: print("❌ Empty request. Skipping.") conn.close() continue request = data.decode() print("🔎 Raw Request:n", request) lines = request.split("rn") if not lines or len(lines[0].split()) < 3: raise ValueError("Invalid HTTP request line") method, path, _ = lines[0].split() filename = path.strip("/") if_modified_since = None for line in lines[1:]: if line.lower().startswith("if-modified-since:"): if_modified_since = line.split(":", 1)[1].strip() response = self.get_file_response(filename, if_modified_since) conn.sendall(response) except socket.timeout: print("⌛ Timeout: No data received.") except Exception as e: print("⚠️ Error:", e) conn.sendall(b"HTTP/1.1 400 Bad Requestrnrn") finally: try: conn.shutdown(socket.SHUT_RDWR) except: pass conn.close() finally: s.close() if __name__ == "__main__": server = HTTPServer() server.start()
submitted by /u/Suitable-Brush3868
[link] [comments]