Junior — Middle
How can a system for tracking and managing URLs be created within a custom framework?
sobes.tech AI
Answer from AI
To create a URL management and tracking system in your own Python framework, you can implement a simple router that maps URL paths to handlers (functions or methods). The main steps are:
- Create a data structure (e.g., a dictionary) where the key is the URL path or pattern, and the value is the handler function.
- When receiving an HTTP request, extract the path from the URL.
- Find the corresponding handler in the dictionary by the path.
- Call the handler and return the result.
Example of a simple router:
class Router:
def __init__(self):
self.routes = {}
def add_route(self, path, handler):
self.routes[path] = handler
def handle_request(self, path):
handler = self.routes.get(path)
if handler:
return handler()
else:
return "404 Not Found"
# Usage
router = Router()
@router.add_route
def home():
return "Home Page"
router.add_route("/about", lambda: "About Us")
print(router.handle_request("/about")) # Output: About Us
For more complex cases, you can add support for URL parameters, HTTP methods, middleware, etc.