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)
Bonus: I created a very early version of the flask feature to accept a variable as a url parameter.
For example, @app.routes(‘/post/<int:post_id>’)
Here is the code to accept variable integer in the url.
#!/usr/bin/python3
import os
import sys
sys.stdout.reconfigure(encoding='utf-8', errors='ignore')
sys.stdin.reconfigure(errors='ignore')
a = ''
a1 = ''
var_name = ''
num1 = ''
class App:
ROUTE_MAP = {}
def routes(self, path):
def save_path(func): # This is the decorator function. It takes another function 'func' as input.
global a
global a1
global var_name
global num1
a = f"""Mapping URL path '{path}' to function '{func.__name__}' """
a1 = path.split('/')
x = 0
for v in a1:
if v.startswith('<int:'):
var_name = v.replace('<int:','').replace('>', '')
else:
x += 1
a2 = os.environ['REQUEST_URI'].split('/')
num1 = a2[x]
globals()[var_name] = num1
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.
request_uri_a1 = request_uri.split('/')
request_uri_b1 = ''
if request_uri_a1[1] == a1[1]:
request_uri_b1 = f"""/{request_uri_a1[1]}"""
request_uri_b1 += f"""/{a1[2]}"""
if request_uri_b1 in self.ROUTE_MAP:
content = self.ROUTE_MAP[request_uri_b1]() # Call the decorated function (which is the wrapper)
return f"""Content-Type:text/html;charset=utf-8;\n\n{content}"""
elif 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 f"""HTTP/1.1 404 Not Found\n\nPage not found"""
# debugging, use these two lines
#else:
# return f"""HTTP/1.1 404 Not Found\n\nPage not found {a} ({a1}) {var_name} {num1} {post_id} {request_uri} {request_uri_a1} {request_uri_b1} """
app = App()
@app.routes('/')
def index():
return "Homepage Content"
@app.routes('/post/<int:post_id>')
def home_page_view():
return f"""
<html>
<head>
</head>
<body>
Hey there page
{post_id}
{a}
</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!