4
4
5
5
from . import server , abstract
6
6
from .http import HTTP , Stream
7
+ from .router import Router
7
8
8
9
AbstractApp = abstract .AbstractApp
9
10
h2_server = server .h2_server
10
11
11
12
12
13
class App (AbstractApp ):
13
- def __init__ (self , port = 5000 , root = './public' , static_file_handle = 'auto' , root_route = 'index.html' ):
14
+ def __init__ (self , port = 5000 , root = './public' ,
15
+ auto_serve_static_file = True ,
16
+ default_file = 'index.html' , router = Router ):
17
+ """
18
+ :param port: TCP port
19
+ :param root: root directory to serve
20
+ :param serve_static_file: automatically serve static files without manually register routes
21
+ :param default_file: default static file to serve
22
+ :param router: the router class to use
23
+ """
14
24
self .port = port
15
25
self .root = os .path .abspath (root )
16
- self .routes = {'GET' : {}, 'POST' : {}}
17
26
18
27
# todo: implement static_file_handle and root_route
19
- self .static_file_handle = static_file_handle
20
- self .root_route = root_route
28
+ self .default_file = default_file
29
+
30
+ if auto_serve_static_file :
31
+ async def default_get (http , stream , parameters ):
32
+ print ('default_get' )
33
+ route = stream .headers [':path' ].lstrip ('/' )
34
+ full_path = os .path .join (self .root , route )
35
+ if os .path .exists (full_path ):
36
+ await http .send_file (stream , full_path )
37
+ else :
38
+ await http .send_error (stream , 404 )
39
+
40
+ self ._router = router (default_get )
41
+ else :
42
+ self ._router = router (None )
21
43
22
44
def up (self ):
23
45
kernel = Kernel ()
@@ -27,27 +49,12 @@ def up(self):
27
49
app = self ),
28
50
shutdown = True )
29
51
30
- def register_route (self , method : str , route : str , handler ):
31
- assert method in ['GET' , 'POST' ]
32
- self .routes [method ][route ] = handler
33
-
34
52
def get (self , route : str , handler ):
35
- self .register_route ('GET' , route , handler )
53
+ self ._router . register ('GET' , route , handler )
36
54
37
55
def post (self , route : str , handler ):
38
- self .register_route ('POST' , route , handler )
56
+ self ._router . register ('POST' , route , handler )
39
57
40
58
# async
41
59
async def handle_route (self , http : HTTP , stream : Stream ):
42
- print ('app.App.handle_route' )
43
-
44
- route = stream .headers [':path' ].lstrip ('/' )
45
- if route in self .routes ['GET' ] or route in self .routes ['POST' ]:
46
- await self .routes [stream .headers [':method' ]][route ](http , stream )
47
- else :
48
- # if route is not registered, assume it is requesting files
49
- full_path = os .path .join (self .root , route )
50
- if os .path .exists (full_path ):
51
- await http .send_file (stream , full_path )
52
- else :
53
- await http .send_error (stream , 404 )
60
+ await self ._router .handle_route (http , stream )
0 commit comments