Advertisement
roman_gemini

Simple router

Jan 26th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. class Route:
  2.     def __init__(self, route, action):
  3.         self.route = route
  4.         self.action = action
  5.  
  6.  
  7. class Router:
  8.     def __init__(self):
  9.         self.routes = []
  10.         self.otherwise
  11.  
  12.     def when(self, route, action):
  13.         route_object = Route(route, action)
  14.         self.routes.append(route_object)
  15.  
  16.     def otherwise(self, action):
  17.         self.otherwise = action
  18.  
  19.     def findAndCall(self, route):
  20.         for r in self.routes:
  21.             if r.route == route:
  22.                 r.action(route)
  23.                 return
  24.         if self.otherwise:
  25.             self.otherwise(route)
  26.    
  27.  
  28. def home_page(request):
  29.     print("Welcome Home!")
  30.  
  31. def other_page(request):
  32.     print("Other Page!")
  33.  
  34. def no_page(request):
  35.     print("Page " + request + " not found!")
  36.  
  37.  
  38. router = Router()
  39.  
  40. router.when("/", home_page)
  41. router.when("/other", other_page)
  42. router.otherwise(no_page)
  43.  
  44. while True:
  45.     route = input("http://mysite.com")
  46.     router.findAndCall(route)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement