def test_index_page(self): os.mkdir(os.path.join(self.test_dir, "index-test")) create_file(bytes_("index"), self.test_dir, "index-test", "index.html") app = static.DirectoryApp(self.test_dir) resp = get_response(app, "/index-test") self.assertEqual(resp.status_code, 301) self.assertTrue(resp.location.endswith("/index-test/")) resp = get_response(app, "/index-test?test") self.assertTrue(resp.location.endswith("/index-test/?test")) resp = get_response(app, "/index-test/") self.assertEqual(resp.status_code, 200) self.assertEqual(resp.body, bytes_("index")) self.assertEqual(resp.content_type, "text/html") resp = get_response(app, "/index-test/index.html") self.assertEqual(resp.status_code, 200) self.assertEqual(resp.body, bytes_("index")) redir_app = static.DirectoryApp(self.test_dir, hide_index_with_redirect=True) resp = get_response(redir_app, "/index-test/index.html") self.assertEqual(resp.status_code, 301) self.assertTrue(resp.location.endswith("/index-test/")) resp = get_response(redir_app, "/index-test/index.html?test") self.assertTrue(resp.location.endswith("/index-test/?test")) page_app = static.DirectoryApp(self.test_dir, index_page="something-else.html") self.assertEqual( get_response(page_app, "/index-test/").status_code, 404)
def _static(self, req: Request): """Static path where images and other files live""" if req.path_info_peek() == "static": req.path_info_pop() logger.info("[static asset] %s", req.path_info) try: with resources.files("pyloot").joinpath("static") as path: return static.DirectoryApp(path) except AttributeError: with resources.path("pyloot", "static") as path: return static.DirectoryApp(path)
def test_file_app_arguments(self): app = static.DirectoryApp(self.test_dir, content_type="xxx/yyy") create_file("abcde", self.test_dir, "bar") resp = get_response(app, "/bar") self.assertEqual(200, resp.status_code) self.assertEqual("xxx/yyy", resp.content_type)
def test_file_app_arguments(self): app = static.DirectoryApp(self.test_dir, content_type='xxx/yyy') create_file('abcde', self.test_dir, 'bar') resp = get_response(app, '/bar') self.assertEqual(200, resp.status_code) self.assertEqual('xxx/yyy', resp.content_type)
def test_serve_file(self): app = static.DirectoryApp(self.test_dir) create_file("abcde", self.test_dir, "bar") self.assertEqual(404, get_response(app).status_code) self.assertEqual(404, get_response(app, "/foo").status_code) resp = get_response(app, "/bar") self.assertEqual(200, resp.status_code) self.assertEqual(bytes_("abcde"), resp.body)
def test_serve_file(self): app = static.DirectoryApp(self.test_dir) create_file('abcde', self.test_dir, 'bar') self.assertEqual(404, get_response(app).status_code) self.assertEqual(404, get_response(app, '/foo').status_code) resp = get_response(app, '/bar') self.assertEqual(200, resp.status_code) self.assertEqual(bytes_('abcde'), resp.body)
def test_dont_leak_parent_directory_file_existance(self): # We'll have: # /TEST_DIR/ # /TEST_DIR/foo/ <- serve this directory serve_path = os.path.join(self.test_dir, "foo") os.mkdir(serve_path) app = static.DirectoryApp(serve_path) # The file exists, but is outside the served dir. self.assertEqual(403, get_response(app, "/../bar2").status_code)
def __init__(self, module_name, path, grab=None, index_file='index.html'): mod = sys.modules[module_name] path = os.path.join(os.path.dirname(mod.__file__), path) self.static_app = static.DirectoryApp(path) if grab: if not grab.startswith('/'): grab = '/' + grab grab = grab.rstrip('/') self.grab = grab self.index_file = index_file
def test_dont_serve_file_in_parent_directory(self): # We'll have: # /TEST_DIR/ # /TEST_DIR/bar # /TEST_DIR/foo/ <- serve this directory create_file("abcde", self.test_dir, "bar") serve_path = os.path.join(self.test_dir, "foo") os.mkdir(serve_path) app = static.DirectoryApp(serve_path) # The file exists, but is outside the served dir. self.assertEqual(403, get_response(app, "/../bar").status_code)
def test_file_app_factory(self): def make_fileapp(*args, **kwargs): make_fileapp.called = True return Response() make_fileapp.called = False app = static.DirectoryApp(self.test_dir) app.make_fileapp = make_fileapp create_file('abcde', self.test_dir, 'bar') get_response(app, '/bar') self.assertTrue(make_fileapp.called)
def __init__(self, settings): map = {} if getattr(settings, 'MEDIA_URL', '').startswith('/'): for app_name in settings.INSTALLED_APPS: if app_name == 'django.contrib.admin': continue mod = __import__(app_name, globals(), locals(), ['']) dirname = os.path.dirname(os.path.abspath(mod.__file__)) medias = glob.glob(os.path.join(dirname, 'media*', '*')) for media in medias: dummy, name = os.path.split(media) if not dirname.startswith('.'): map[settings.MEDIA_URL + name] = \ static.DirectoryApp(media) map[settings.MEDIA_URL] = static.DirectoryApp(settings.MEDIA_ROOT) # staticfiles has_statics = False if hasattr(settings, "STATIC_URL"): if settings.STATIC_URL.startswith('/'): try: map[settings.STATIC_URL] = StaticFiles() except ImportError: pass else: has_statics = True # admin medias if not has_statics and hasattr(settings, "ADMIN_MEDIA_PREFIX"): if settings.ADMIN_MEDIA_PREFIX.startswith('/'): import django.contrib.admin dirname = os.path.dirname( os.path.abspath(django.contrib.admin.__file__)) map[settings.ADMIN_MEDIA_PREFIX] = static.DirectoryApp( os.path.join(dirname, 'media')) for l, k in sorted([(len(k), k) for k in map], reverse=True): self.append((k, map[k]))
def media(self, req): """Static path where images and other files live""" path = resource_filename('dozer', 'media') app = static.DirectoryApp(path) return app
def test_empty_directory(self): app = static.DirectoryApp(self.test_dir) self.assertEqual(404, get_response(app).status_code) self.assertEqual(404, get_response(app, "/foo").status_code)
def _process(self, req): """ a request URL is parsed as follow /object/resource?args object is the main python object GET /object is mapped to handle_get function(**kwargs) GET /object/resource is mapped to handle_get([resource,], **kwargs) GET /object/resource/resource2 is mapped to handle_get([resource,resource2], **kwargs) args are always passed on through **kwargs """ method = req.method object = req.path_info_pop() #do some static file serving logic first before trying functions on objects if object == None or object == "": #the root / is moved to static file serving res = exc.HTTPMovedPermanently(location="/static/") return res elif object == "static": # In here we are handling real files so be careful!!! if method == "GET": # simply serving static files #import os #print(os.getcwd()) res = static.DirectoryApp(self._httpdRoot) return res if method == "POST": # uploading new files filename = req.path_info_pop() filepath = os.path.join(os.path.join(self._httpdRoot, filename)) # if the file exists we raise an exception if filename == "": filename = req.params['file'] if os.path.exists(filepath): raise exc.HTTPForbidden("%s already exists" % filename) #print(dir(req)) #print(req.body) saveFile = open(os.path.join(self._httpdRoot, filename), 'wb') saveFile.write(req.body_file.read()) saveFile.close() return Response("ok") if method == "PUT": # This will overwrite your files # uploading files to update filename = req.path_info_pop() filepath = os.path.join(os.path.join(self._httpdRoot, filename)) # if the file exists we raise an exception if not os.path.exists(filepath): raise exc.HTTPNotFound("%s file not found" % filename) if filename == "": filename = req.params['file'] #print(dir(req)) #print(req.body) saveFile = open(os.path.join(self._httpdRoot, filename), 'wb') saveFile.write(req.body_file.read()) saveFile.close() return Response("ok") ################################################# # # After this we only handle JSON type content!!!! # ################################################# #Find the object obj = None try: obj = self._restObjects[object] except: #print(self._restObjects) #print(dir(self._restObjects)) raise exc.HTTPNotFound('No such resource: %s' % object) #Find the function func = None try: func = getattr(obj, 'handle_' + method) except: raise exc.HTTPNotFound('No %s method on resource: %s' % (method, object)) # Find resources: resources = [] # get first resource res = req.path_info_pop() while res: resources.append(res) # get next resource res = req.path_info_pop() #optional extra headers #FIXME: this shouldn't be hardcoded. The appie modules should take care of this #http://www.w3.org/TR/cors/#syntax extraHeaderList = [ ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS'), ('Access-Control-Max-Age', '86400'), ('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version' ) ] #Get args kwargs = req.GET if (method == 'POST'): #curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d #curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"test" : "help" }' http://localhost:8000/bge/IcoSphere if req.content_type == 'application/json': encoding = req.charset body = req.body.decode(encoding) data = loads(body) #print(data) #print(type(data)) kwargs = data else: kwargs = req.POST try: result = func(*resources, **kwargs) except: raise exc.HTTPInternalServerError( "Appie raised an exception while calling the method with %s %s" % (str(resources), str(kwargs))) resp = Response(content_type='application/json', charset='utf8', body=dumps(result)) resp.headerlist.extend(extraHeaderList) return resp
def handle_GET(self, req, *args, **kwargs): return static.DirectoryApp(self.root_dir)
print("Web_root = "+ web_root) print("Svn_root = "+ svn_root) # generate a simple http server # extra headers we want to inject in our responses extra_headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS', 'Access-Control-Max-Age': '86400', 'Access-Control-Allow-Headers': 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version' } # this the default file serving object serving files from the webroot # AppieFS = AppieSimpleFileServer("../../../../../../z25-ict/web/www.z25.org/src/html/", enable_del=True) AppieFS = AppieSimpleFileServer(web_root, enable_del=True) # create the Appie instance and pass it the default file server appie_inst = Appie(default=AppieFS) # add the extra header info to Appie appie_inst.inject_headers(extra_headers) # register simple Rest object serving file from the "static" url base # this serves the files for the z25 website appie_inst.register_rest_object("static", static.DirectoryApp(static_root)) # register the z25 collector projects = AppieZ25Projects(projects_root, static_root, svn_root) appie_inst.register_rest_object("json", projects) # start a webserver httpd = make_server('', 8000, appie_inst) print("Serving on port 8000...") # Serve until process is killed httpd.serve_forever()