@@ -15,6 +15,13 @@ def decorator(f):
1515 return f
1616 return decorator
1717
18+ handler_method = {}
19+ def handler (method = None ):
20+ def decorator (f ):
21+ handler_method [method ] = f
22+ return f
23+ return decorator
24+
1825class extended_BaseHTTPServer (BaseHTTPServer .BaseHTTPRequestHandler ):
1926 def log_message (self , format , * args ):
2027 return ""
@@ -38,35 +45,38 @@ def do_GET(s):
3845 def do_routing (s , o , arguments , action ):
3946 if o .path in register_route [action ]:
4047 retour = register_route [action ][o .path ](** arguments )
41-
42- if type (retour ) is dict :
43- s .send_response (retour .get ("code" ,200 ))
44- for header in retour :
45- if header not in ["code" ,"content" ]:
46- s .send_header (header , retour [header ])
47- s .end_headers ()
48- s .wfile .write (retour ['content' ])
49-
50- else :
51- s .send_response (200 )
52- s .send_header ("Content-type" , "text/html" )
53- s .end_headers ()
54- s .wfile .write (retour )
48+ build_response (s , retour , 200 )
5549 else :
5650 # Fichier static ?
5751 try :
5852 with open (os .path .join ("." + o .path )) as f :
5953 fname ,ext = os .path .splitext (o .path )
60- s . send_response ( 200 )
61- s . send_header ( 'Content-type' , types_map [ ext ])
62- s . end_headers ()
63- s . wfile . write ( f .read ())
54+ ctype = "text/plain"
55+ if ext in types_map :
56+ ctype = types_map [ ext ]
57+ build_response ( s , { 'Content-type' : ctype , "content" : f .read ()}, 200 )
6458 except Exception as e :
65- s .send_response (404 )
66- s .send_header ("Content-type" , "text/html" )
67- s .end_headers ()
6859 # Url introuvale et fichier static introuvable ==> 404
69- s .wfile .write ("TODO 404 STUFF" )
60+ if "404" not in handler_method :
61+ build_response (s , "404 - Not Found" , 404 )
62+ else :
63+ retour = handler_method ['404' ]()
64+ build_response (s , retour , 404 )
65+
66+
67+ def build_response (output , retour , code = 200 ):
68+ if type (retour ) is dict :
69+ output .send_response (retour .get ("code" ,code ))
70+ for header in retour :
71+ if header not in ["code" ,"content" ]:
72+ output .send_header (header , retour [header ])
73+ output .end_headers ()
74+ output .wfile .write (retour ['content' ])
75+ else :
76+ output .send_response (code )
77+ output .send_header ("Content-type" , "text/html" )
78+ output .end_headers ()
79+ output .wfile .write (retour )
7080
7181
7282def redirect (location = "" ):
0 commit comments