Created
November 8, 2019 02:53
-
-
Save Trshant/bf317e55069acd5746ed222ac8f878f6 to your computer and use it in GitHub Desktop.
a minimal webserver in python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer # python2 | |
from http.server import BaseHTTPRequestHandler, HTTPServer # python3 | |
class HandleRequests(BaseHTTPRequestHandler): | |
def _set_headers(self): | |
self.send_response(200) | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
def do_GET(self): | |
'''Reds get request body''' | |
self._set_headers() | |
stringToReturn = app.handleRoutes(self.path , "POST" ) | |
self.wfile.write( str.encode(stringToReturn) ) | |
def do_POST(self): | |
'''Reads post request body''' | |
self._set_headers() | |
stringToReturn = app.handleRoutes(self.path , "GET" ) | |
self.wfile.write( str.encode(stringToReturn) ) | |
class app: | |
@staticmethod | |
def run(host,port): | |
HTTPServer((host, port), HandleRequests).serve_forever() | |
routes = [] | |
routes_path = {} | |
@classmethod | |
def route( self, path): | |
self.routes.append(path) | |
def tags_decorator(func): | |
self.routes_path[path] = func | |
def func_wrapper(): | |
return func() | |
return func_wrapper | |
return tags_decorator | |
@classmethod | |
def handleRoutes( self, path, method ): | |
stringToReturn = "recieved "+method+"request : " | |
stringToReturn += self.routes_path[path]() | |
return stringToReturn | |
@app.route("/") | |
def get_text(): | |
return "Hello " | |
@app.route("/name/") | |
def get_text2(): | |
return "Hello 2" | |
host = '' | |
port = 80 | |
app.run(host, port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment