For quite a while I wanted to figure out the decorator path in frameworks such as Flask and Django and because they are opensource projects the source code is readily available for study, modification, editing, etc. Utilizing the technique or something similar, the other day I figured out a simple way to do such the routing. Here is the following code.
#!/usr/bin/python3
import os
import sys
sys.stdout.reconfigure(encoding='utf-8', errors='ignore')
sys.stdin.reconfigure(errors='ignore')
class App:
ROUTE_MAP = {}
def routes(self, path):
def save_path(func): # This is the decorator function. It takes another function 'func' as input.
self.ROUTE_MAP[path] = func # Mapping URL path '{path}' to function '{func.__name__}
return func
return save_path
def request_serve(self, request_uri): # A simple function when a page is requested it fetches the func
# Looks up the request_uri in the ROUTE_MAP
# and calls the associated function.
if request_uri in self.ROUTE_MAP:
content = self.ROUTE_MAP[request_uri]() # Call the decorated function (which is the wrapper)
return f"""Content-Type:text/html;charset=utf-8;\n\n{content}"""
else:
return "HTTP/1.1 404 Not Found\n\nPage not found"
app = App()
@app.routes('/')
def index():
return "Homepage Content"
@app.routes('/hey/there')
def home_page_view():
return f"""
<html>
<head>
</head>
<body>
Hey there page
</body>
</html>
"""
def str1(str2):
if isinstance(str2, str):
str2 = str2[:-1] if (str2.endswith('/') and len(str2) > 1) else str2
idx = str2.find('?')
if idx != -1:
str2 = str2[:idx]
str2 = str2[:-1] if (str2.endswith('/') and len(str2) > 1) else str2
return str2
else:
return str2
else:
return ''
# Output during startup:
# Mapping URL path '/' to function 'index' and its Homepage Content text
# '/hey/there' to function 'home_page_view'
html = app.request_serve(str1(os.environ['REQUEST_URI']))
print(html)
Happy Coding!