0
|
1 import os
|
|
2
|
|
3 from dispatcher import Dispatcher
|
|
4 from paste.httpexceptions import HTTPExceptionHandler
|
|
5 from paste.urlparser import StaticURLParser
|
|
6 from pkg_resources import resource_filename
|
|
7
|
|
8 class PassthroughFileserver(object):
|
|
9 """serve files if they exist"""
|
|
10
|
4
|
11 def __init__(self, app, *directories):
|
0
|
12 self.app = app
|
4
|
13 missing = [i for i in directories
|
|
14 if not os.path.exists(i) or not os.path.isdir(i)]
|
|
15 assert not missing, "Missing directories: %s" % missing
|
|
16 self.directories = [(directory, StaticURLParser(directory))
|
|
17 for directory in directories]
|
0
|
18
|
|
19 def __call__(self, environ, start_response):
|
|
20 path = environ['PATH_INFO'].strip('/')
|
4
|
21 for directory, fileserver in self.directories:
|
|
22 if path and os.path.exists(os.path.join(directory, path)):
|
|
23 return fileserver(environ, start_response)
|
0
|
24 return self.app(environ, start_response)
|
|
25
|
1
|
26 def factory(**app_conf):
|
0
|
27 """create a webob view and wrap it in middleware"""
|
4
|
28 directory = app_conf['directory']
|
1
|
29 app = Dispatcher(**app_conf)
|
3
|
30 return PassthroughFileserver(app, resource_filename(__name__, 'static'))
|
0
|
31
|
1
|
32 if __name__ == '__main__':
|
2
|
33 import shutil
|
1
|
34 import tempfile
|
|
35 from wsgiref import simple_server
|
2
|
36 tempdir = tempfile.mkdtemp()
|
|
37 try:
|
3
|
38 app = factory(directory=tempdir)
|
|
39 server = simple_server.make_server(host='0.0.0.0', port=8080, app=app)
|
|
40 server.serve_forever()
|
2
|
41 finally:
|
|
42 shutil.rmtree(tempdir)
|