![]() |
A. very basic micro web framework. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html) +--- Thread: A. very basic micro web framework. (/thread-7129.html) |
A. very basic micro web framework. - RickyWilson - Dec-22-2017 I'm looking for some insight on a prototype micro web framework I'm working on. #!/usr/bin/env python from http.server import BaseHTTPRequestHandler, HTTPServer import sys import socket DEFAULT_PORT = 8080 LOCALHOST = '127.0.0.1' DEFAULT_ENCODING = 'utf-16' ROUTES = None class Router(object): def __init__(self): self.routes = {} global ROUTES ROUTES = self def add(self, route, cb): self.routes[route] = cb() def get(self, route): return self.routes.get(route) def exists(self, route): return route in self.routes def __call__(self, route): return self.get(route) def enable_router(): Router() class Route(object): def __init__(self, route): self.route = route def __call__(self, func): ROUTES.add(self.route, func) class RequestHandler(BaseHTTPRequestHandler): def send_msg(self, msg, encoding=DEFAULT_ENCODING): try: self.wfile.write(bytes(msg, encoding)) except socket.error: return def do_GET(self): print(self.headers) if not ROUTES.exists(self.path): self.send_header('content-type', 'text/html') self.send_response(404) self.end_headers() self.send_msg('<center><h1>404 ?</h1></center>') return self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.send_msg(ROUTES(self.path)) return def run(port=8080, server_addr=LOCALHOST): print('starting server...') server_address = (server_addr, port) httpd = HTTPServer(server_address, RequestHandler) print('running server...') httpd.serve_forever() if __name__ == '__main__': enable_router() @Route('/') def root(): return '<h1><center><b>It Works ?</b></center></h1>' run() CodeReview RE: A. very basic micro web framework. - nilamo - Dec-28-2017 I don't like the global keyword, or the enable_router() call. I think Route can handle both of those itself by having a class-level variable that refers to a single Router that they all refer to.
RE: A. very basic micro web framework. - SarbjitGrewal - Jan-08-2018 Hi nilamo, I agree with your statement that all variables can be picked by the single router that they refer all do. |