Untitled

mail@pastecode.io avatar
unknown
plain_text
7 days ago
2.5 kB
19
Indexable
Never
import http.server
import socketserver
import json
from urllib.parse import urlparse, parse_qs

# Mock database
mock_db = {
    "users": [
        {"id": 1, "name": "Alice", "email": "alice@example.com"},
        {"id": 2, "name": "Bob", "email": "bob@example.com"},
        {"id": 3, "name": "Charlie", "email": "charlie@example.com"}
    ],
    "products": [
        {"id": 1, "name": "Laptop", "price": 999.99},
        {"id": 2, "name": "Smartphone", "price": 499.99},
        {"id": 3, "name": "Headphones", "price": 99.99}
    ]
}

class MyHandler(http.server.SimpleHTTPRequestHandler):
    def _set_headers(self, status_code=200):
        self.send_response(status_code)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def _read_content(self):
        content_length = int(self.headers['Content-Length'])
        return self.rfile.read(content_length)

    def do_GET(self):
        parsed_path = urlparse(self.path)
        path = parsed_path.path
        query = parse_qs(parsed_path.query)

        if path == '/users':
            data = mock_db['users']
            if 'id' in query:
                user_id = int(query['id'][0])
                data = next((user for user in data if user['id'] == user_id), None)
                if data is None:
                    self._set_headers(404)
                    response = {"error": "User not found"}
                else:
                    response = data
            else:
                response = data
        elif path == '/products':
            data = mock_db['products']
            if 'id' in query:
                product_id = int(query['id'][0])
                data = next((product for product in data if product['id'] == product_id), None)
                if data is None:
                    self._set_headers(404)
                    response = {"error": "Product not found"}
                else:
                    response = data
            else:
                response = data
        else:
            self._set_headers(404)
            response = {"error": "Not found"}

        self._set_headers()
        self.wfile.write(json.dumps(response).encode())



    def do_DELETE(self):
        self._set_headers()
        response = {"message": "This is a DELETE request response"}
        self.wfile.write(json.dumps(response).encode())

PORT = 8000

with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
    print(f"Serving at port {PORT}")
    httpd.serve_forever()
Leave a Comment