import asyncio import json import os import traceback import mimetypes import urllib.parse from collections import OrderedDict class HTTPRequest: def __init__(self): self.method = '' self.path = '' self.query_params = {} self.path_params = {} self.headers = {} self.body = b'' self.form = {} self.files = {} self.content_type = '' self.content_length = 0 self.remote_addr = '' @classmethod async def parse(cls, reader): request = cls() request_line = await reader.readline() if not request_line: return None line_decoded = request_line.decode('utf-8', errors='replace').strip() parts = line_decoded.split(' ') if len(parts) < 2: return None request.method = parts[0].upper() full_path = parts[1] if '?' in full_path: request.path, query_string = full_path.split('?', 1) request.query_params = dict(urllib.parse.parse_qsl(query_string)) else: request.path = full_path while True: header_line = await reader.readline() if header_line in (b'\r\n', b'\n', b''): break line = header_line.decode('utf-8', errors='replace').strip() if ':' in line: key, value = line.split(':', 1) request.headers[key.strip().lower()] = value.strip() request.content_length = int(request.headers.get('content-length', 0)) request.content_type = request.headers.get('content-type', '') if request.content_length > 0: request.body = await reader.readexactly(request.content_length) content_type_lower = request.content_type.lower() if 'application/x-www-form-urlencoded' in content_type_lower: request.form = dict(urllib.parse.parse_qsl( request.body.decode('utf-8', errors='replace'))) elif 'application/json' in content_type_lower: try: body_str = request.body.decode('utf-8') if body_str.strip(): request.form = json.loads(body_str) except (json.JSONDecodeError, UnicodeDecodeError): request.form = {} elif 'multipart/form-data' in content_type_lower: request._parse_multipart() return request def _parse_multipart(self): boundary = None for part in self.content_type.split(';'): part = part.strip() if part.startswith('boundary='): boundary = part[9:].strip('"') break if not boundary: return boundary_bytes = boundary.encode('utf-8') delimiter = b'--' + boundary_bytes parts = self.body.split(delimiter) for part_data in parts: if part_data in (b'', b'\r\n', b'--\r\n', b'--'): continue header_end = part_data.find(b'\r\n\r\n') if header_end == -1: continue header_section = part_data[:header_end].decode('utf-8', errors='replace') content = part_data[header_end + 4:] if content.endswith(b'\r\n'): content = content[:-2] headers = {} for line in header_section.split('\r\n'): if ':' in line: k, v = line.split(':', 1) headers[k.strip().lower()] = v.strip() content_disposition = headers.get('content-disposition', '') name = '' filename = '' for disp_part in content_disposition.split(';'): disp_part = disp_part.strip() if disp_part.startswith('name='): name = disp_part[5:].strip('"') elif disp_part.startswith('filename='): filename = disp_part[9:].strip('"') if filename: self.files[name] = { 'filename': filename, 'content': content, 'content_type': headers.get('content-type', 'application/octet-stream') } else: self.form[name] = content.decode('utf-8', errors='replace') class HTTPResponse: def __init__(self, status=200, body=b'', headers=None, content_type='text/html; charset=utf-8'): self.status = status self.body = body if isinstance(body, bytes) else str(body).encode('utf-8') self.headers = OrderedDict() if headers: for k, v in headers.items(): self.headers[k] = v has_ct = any(k.lower() == 'content-type' for k in self.headers) if not has_ct: self.headers['Content-Type'] = content_type def _status_text(self): status_map = { 200: 'OK', 201: 'Created', 204: 'No Content', 301: 'Moved Permanently', 302: 'Found', 304: 'Not Modified', 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 408: 'Request Timeout', 409: 'Conflict', 413: 'Payload Too Large', 500: 'Internal Server Error', 502: 'Bad Gateway', 503: 'Service Unavailable' } return status_map.get(self.status, 'Unknown') def set_cookie(self, name, value, max_age=None, path='/', http_only=True, secure=False): cookie = '{}={}; Path={}'.format(name, value, path) if max_age is not None: cookie += '; Max-Age={}'.format(max_age) if http_only: cookie += '; HttpOnly' if secure: cookie += '; Secure' existing = self.headers.get('Set-Cookie') if existing is not None: if isinstance(existing, list): existing.append(cookie) else: self.headers['Set-Cookie'] = [existing, cookie] else: self.headers['Set-Cookie'] = cookie def delete_cookie(self, name, path='/'): self.set_cookie(name, '', max_age=0, path=path) def to_bytes(self): status_line = 'HTTP/1.1 {} {}\r\n'.format(self.status, self._status_text()) self.headers['Content-Length'] = str(len(self.body)) self.headers['Connection'] = 'close' header_str = '' for key, value in self.headers.items(): if isinstance(value, list): for v in value: header_str += '{}: {}\r\n'.format(key, v) else: header_str += '{}: {}\r\n'.format(key, value) return (status_line + header_str + '\r\n').encode('utf-8') + self.body @classmethod def json(cls, data, status=200): if isinstance(data, str): body = data else: body = json.dumps(data, ensure_ascii=False, default=str) return cls(status=status, body=body, content_type='application/json; charset=utf-8') @classmethod def redirect(cls, location, status=302): return cls(status=status, body='', headers={'Location': location}) @classmethod def error(cls, status=500, message='Internal Server Error'): body = '

{} {}

'.format(status, message) return cls(status=status, body=body) class LiteServer: def __init__(self, host='0.0.0.0', port=8000): self.host = host self.port = port self.router = None async def _handle_client(self, reader, writer): try: request = await HTTPRequest.parse(reader) if request is None: writer.close() return addr = writer.get_extra_info('peername') if addr: request.remote_addr = '{}:{}'.format(addr[0], addr[1]) if self.router: static_response = await self._try_serve_static(request.path) if static_response: response = static_response else: response = await self.router.dispatch(request.method, request.path, request) if response is None: response = HTTPResponse.error(404, 'Not Found') else: response = HTTPResponse.error(404, 'Not Found') writer.write(response.to_bytes()) await writer.drain() except asyncio.IncompleteReadError: pass except Exception as e: tb = traceback.format_exc() try: error_response = HTTPResponse.error(500, 'Internal Server Error') writer.write(error_response.to_bytes()) await writer.drain() except Exception: pass finally: try: writer.close() except Exception: pass async def _try_serve_static(self, path): if not self.router: return None for prefix, dir_path in self.router.static_dirs.items(): if path.startswith(prefix): relative_path = path[len(prefix):] if not relative_path or relative_path == '/': relative_path = '/index.html' full_path = os.path.normpath(os.path.join(dir_path, relative_path.lstrip('/'))) if not full_path.startswith(os.path.normpath(dir_path)): return HTTPResponse.error(403, 'Forbidden') if os.path.isfile(full_path): mime_type, _ = mimetypes.guess_type(full_path) if mime_type is None: mime_type = 'application/octet-stream' with open(full_path, 'rb') as f: content = f.read() return HTTPResponse(status=200, body=content, content_type=mime_type) return None async def start(self): server = await asyncio.start_server(self._handle_client, self.host, self.port) addr = server.sockets[0].getsockname() msg = 'LiteAdmin server running on http://{}:{}'.format(addr[0], addr[1]) print('=' * 50) print(msg) print('=' * 50) async with server: await server.serve_forever()