def wsgi_factory(): # pragma: no cover morepath.autoscan() if os.getenv("RUN_ENV") == "production": ProductionApp.commit() app = ProductionApp() elif os.getenv("RUN_ENV") == "test": TestApp.commit() app = TestApp() else: App.commit() app = App() index = FileApp("build/index.html") static = DirectoryApp("build", index_page=None) setup_db(app) @webob.dec.wsgify def morepath_with_static_absorb(request): popped = request.path_info_pop() if popped == "api": return request.get_response(app) elif popped == "static": return request.get_response(static) else: return request.get_response(index) return morepath_with_static_absorb
def __call__(self, request): # first segment should be publisher signature publisher_signature = request.path_info_peek() # pass through to underlying WSGI app if publisher_signature != self.bower.publisher_signature: return self.handler(request) request.path_info_pop() # next segment is BowerComponents name bower_components_name = request.path_info_pop() if bower_components_name is None: return webob.exc.HTTPNotFound() # next segment is component name component_name = request.path_info_pop() if component_name is None: return webob.exc.HTTPNotFound() # next segment is component version component_version = request.path_info_pop() if component_version is None: return webob.exc.HTTPNotFound() # the rest of the path goes into component file_path = request.path_info.lstrip('/') if file_path.strip() == '': return webob.exc.HTTPNotFound() filename = self.bower.get_filename(bower_components_name, component_name, component_version, file_path) if filename is None: return webob.exc.HTTPNotFound() file_app = FileApp(filename) response = request.get_response(file_app) if response.status_code == 200: response.cache_control.max_age = FOREVER response.expires = time.time() + FOREVER # XXX do we really want to rely on mimetype guessing? return response
def __call__(self, req): """WSGI application callable. Returns either a file download, directory listing or DAP response. """ path = os.path.abspath( os.path.join(self.path, *req.path_info.split("/"))) if not path.startswith(self.path): return HTTPForbidden() if path.endswith('catalog.xml'): return self.index(os.path.dirname(path), req, catalog=True) elif os.path.exists(path): if os.path.isdir(path): # Return the folder view return self.index(path, req) else: # Return a file download return FileApp(path) # strip DAP extension (.das, .dds, .html, .ascii) and see if the file exists base, ext = os.path.splitext(path) if os.path.isfile(base): req.environ["pydap.jinja2.environment"] = self.env app = ServerSideFunctions(get_handler(base, self.handlers)) return req.get_response(app) else: return HTTPNotFound(comment=path)
def wrapper(environ, start_response): request = Request(environ) if request.path.startswith(settings.MEDIA_URL): filename = request.path[len(settings.MEDIA_URL):] path = os.path.realpath(os.path.join(document_root, filename)) if path.startswith(document_root): return FileApp(path)(environ, start_response) return app(environ, start_response)
def get_resource_response(self, response, route): """Serve a resource.""" try: path = app.userapp.settings.RESOURCE_DIR + '/' + route.path if not os.path.exists(path) or not os.path.isfile(path): raise IOError return FileApp(path) except IOError: logging.warning('IOError while trying to access resource.') abort(404)
def static_files(self, env, data): path_info = unquote(env.request.path) if path_info.startswith(self.url): if path_info.endswith('/'): raise HTTPNotFound file_path = self.translate_path(path_info[len(self.url):]) if file_path and path.exists(file_path) and path.isfile(file_path): return FileApp(file_path) else: logger.info('Client requested non existent static data "%s"', file_path) return Response(status=404) return None
def show(self, request, resource, **kwargs): ''' Handles GET /files/{resource} ''' log.debug('%s\nResource: %s\n' % (request, resource)) try: urlvars = request.urlvars if urlvars.get('format') is not None: resource += '.%s' % urlvars.get('format') file_path = self.expand(resource) filename = self.repository.get_file(file_path).name return FileApp(filename, content_type=CONTENT_TYPE_OTHER) except FileObjectNotFound: log.error('File %s not found' % resource) return self.http_not_found()
def server(): graphql = graphql_wsgi(StarWarsSchema) static = DirectoryApp('build', index_page=None) index = FileApp('index.html') graphiql = FileApp('graphiql.html') @wsgify def mount_graphql(request): if request.path_info_peek() == '': return request.get_response(index) if request.path_info_peek() == 'graphiql': return request.get_response(graphiql) popped = request.path_info_pop() if popped == 'graphql': return request.get_response(graphql) elif popped == 'static': return request.get_response(static) raise HTTPNotFound() server = make_server('127.0.0.1', 5000, mount_graphql) print "Python GraphQL server running on http://127.0.0.1:5000/graphql" print "React with Relay UI available on http://127.0.0.1:5000" server.serve_forever()
def download_glextract(self, *args, **kwargs): ext = kwargs.get('ext', None) if ext == 'pdf': filename, filepath = self.export_glextract_pdf() response.headers["Content-Type"] = 'application/pdf' if ext == 'xls': filename, filepath = self.export_glextract_xls() response.headers["Content-Type"] = 'application/vnd.ms-excel' response.headers[ "Content-Disposition"] = 'attachment; filename="' + filename + '"' filecontent = FileApp(filepath) return use_wsgi_app(filecontent)
def download_template(self, *args, **kwargs): import_type_id = str_to_int(kwargs.get('import_type_id', None)) if not import_type_id: return '' member = TYPEUTIL.get_id_of_name('batch_import_type', 'member') family = TYPEUTIL.get_id_of_name('batch_import_type', 'family') purchase = TYPEUTIL.get_id_of_name('batch_import_type', 'purchase') if import_type_id == member: filename = 'Member Import Template.xlsx' elif import_type_id == purchase: filename = 'Policy Import Template.xlsx' elif import_type_id == family: filename = 'Family Import Template.xlsx' else: filename = None filepath = os.path.join(EXCEL_DIRNAME, str(filename)) if not os.path.exists(filepath): return '' response.headers["Content-Type"] = 'application/vnd.ms-excel' response.headers["Content-Disposition"] = 'attachment; filename="'+filename+'"' filecontent = FileApp(filepath) return use_wsgi_app(filecontent)
def static(self, req, db, static_path): if not self.static_re.match(static_path): return Response(status=404, body='Bad path') content_type, filename = db.get_blob_data(static_path) if not filename: return Response(status=404, body='No such static file') kw = {} if 'filename' in req.GET: download = req.GET['filename'] download = download.split('/')[-1] download = download.split('\\')[-1] download = self.filename_re.sub('', filename) ## FIXME: maybe I should check the extension against the declared type? kw['headers'] = {'Content-Disposition': 'attachment; filename="%s"' % download} ## FIXME: text/html content introduces a security hole ## Really all static content needs to be on another origin return req.send(FileApp(filename, content_type=content_type, **kw))
def download(self, filename, downloadname, download=True): """ Returns a download stream. filename is location of file. downloadname is name to download with. download (default True): specify whether to download the file or display it inline (aka: content disposition: attachement or inline) """ disposition = 'attachment' if not download: disposition = 'inline' return FileApp(filename, headerlist=[[ 'Content-Disposition', f'{disposition}; filename="{downloadname}"' ]])
def run(): # pragma: no cover morepath.autoscan() index = FileApp('static/index.html') static = DirectoryApp('static') app = App() @webob.dec.wsgify def morepath_with_static_absorb(request): popped = request.path_info_pop() if popped == 'api': return request.get_response(app) elif popped == 'static': return request.get_response(static) else: return request.get_response(index) morepath.run(morepath_with_static_absorb)
def script_store(self, req): prefix = '/api/scripts' assert req.path_info.startswith(prefix) path_parts = req.path_info[len(prefix):].strip('/').split('/', 1) email = path_parts[0] name = path_parts[1] filename = self.get_script_filename(email, name) if req.method == 'PUT': if req.email != email: return exc.HTTPForbidden() if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) with open(filename, 'wb') as fp: fp.write(req.body) return Response('', content_type=None) elif req.method == 'GET': if not os.path.exists(filename): return exc.HTTPNotFound() return FileApp(filename) else: return exc.HTTPMethodNotAllow(allow='PUT,GET')
def __call__(self, request): publisher_signature = request.path_info_peek() if publisher_signature != self.environment.url: return self.handler(request) subpath = request.path_info.replace(publisher_signature, '').strip('/') subpath = unquote(subpath) if has_insecure_path_element(subpath): return webob.exc.HTTPNotFound() asset = os.path.join(self.environment.directory, subpath) asset = os.path.abspath(asset) # I'm not entirely at ease with loading a file from disk and returning # it over the web. So as an extra precaution I want to make sure # that only files *inside* the assets folder will be served. # # I doubt webob let's this happen, but if somebody is ever able to # create an url resulting in a path that points outside the assets # directory this check might help. if not is_subpath(self.environment.directory, asset): return webob.exc.HTTPNotFound() # This is possibly too paranoid if os.path.islink(asset): return webob.exc.HTTPNotFound() if not os.path.isfile(asset): return webob.exc.HTTPNotFound() response = request.get_response(FileApp(asset)) if response.status_code == 200: response.cache_control.max_age = FOREVER response.expires = time.time() + FOREVER return response
def static_view(request, path): """ View for serving static files""" return _ForceResponse(FileApp(join(directory, path))(request))
def wsgi_app(self, environ, start_response): filename = environ["PATH_INFO"] if filename == "/status": response_headers = [("Content-type", "text/html")] start_response("200 OK", response_headers) return [b"200 OK"] # Sometimes, even after the user has clicked 'exit' in the page, # a browser sends a request for e.g. an audio file. if self.is_shutting_down and filename != "/release_database": response_headers = [("Content-type", "text/html")] start_response("503 Service Unavailable", response_headers) return [b"Server stopped"] # Load database if needed. if not self.is_mnemosyne_loaded and filename != "/release_database": self.load_mnemosyne() self.release_database_after_timeout.ping() # All our request return to the root page, so if the path is '/', # return the html of the review widget. if filename == "/": # Process clicked buttons in the form. form = cgi.FieldStorage(fp=environ["wsgi.input"], environ=environ) if "show_answer" in form and not self.is_just_started: self.mnemosyne.review_widget().show_answer() page = self.mnemosyne.review_widget().to_html() elif "grade" in form and not self.is_just_started: grade = int(form["grade"].value) self.mnemosyne.review_widget().grade_answer(grade) page = self.mnemosyne.review_widget().to_html() elif "star" in form: self.mnemosyne.controller().star_current_card() page = self.mnemosyne.review_widget().to_html() elif "exit" in form: self.unload_mnemosyne() page = "Server stopped" self.wsgi_server.stop() self.stop_server_after_timeout = \ StopServerAfterTimeout(self.wsgi_server) self.stop_server_after_timeout.start() self.is_shutting_down = True else: page = self.mnemosyne.review_widget().to_html() if self.is_just_started: self.is_just_started = False # Serve the web page. response_headers = [("Content-type", "text/html")] start_response("200 OK", response_headers) return [page] elif filename == "/release_database": self.unload_mnemosyne() response_headers = [("Content-type", "text/html")] start_response("200 OK", response_headers) return [b"200 OK"] # We need to serve a media file. else: # Late import to speed up application startup. from webob import Request from webob.static import FileApp full_path = self.mnemosyne.database().media_dir() for word in filename.split("/"): full_path = os.path.join(full_path, word) request = Request(environ) if os.path.exists(full_path): etag = "%s-%s-%s" % (os.path.getmtime(full_path), os.path.getsize(full_path), hash(full_path)) else: etag = "none" app = FileApp(full_path, etag=etag) return app(request)(environ, start_response)
class Subber(object): def __init__(self, source_dir, dest_dir=None, index_page='index.html', clear=True): name = 'path-%s' % random.randint(1, 10000) if source_dir.startswith('package:'): _, name, path = source_dir.split(':', 2) mod = sys.modules[name] base_path = os.path.dirname(mod.__file__) source_dir = os.path.join(base_path, path) self.source_dir = source_dir if dest_dir is None: dest_dir = os.environ.get('TMP_DEST_DIR', '/tmp/subbers') dest_dir = os.path.join(dest_dir, name) self.dest_dir = dest_dir if not os.path.exists(dest_dir): os.makedirs(dest_dir) self.index_page = index_page if clear: self.clear() @wsgify def __call__(self, req): dest_path = self.get_dest_path(req) source_path = self.source_dir file_path = posixpath.normpath(req.path_info.lstrip('/')) dest_file_path = os.path.join(dest_path, file_path) source_file_path = os.path.join(source_path, file_path) if (not dest_file_path.startswith(dest_path) or not source_file_path.startswith(source_path)): return exc.HTTPForbidden() if os.path.isdir(source_file_path) and not req.path_info.endswith('/'): return Response(status=301, location=add_slash(req)) if req.path_info.endswith('/' + self.index_page): new_url = req.path_url.rsplit('/', 1)[0] + '/' return Response(status=301, location=new_url) if req.path_info.endswith('/'): source_file_path += os.path.sep + self.index_page dest_file_path += os.path.sep + self.index_page if not os.path.exists(source_file_path): ## FIXME: delete source_file_path? return exc.HTTPNotFound(comment='No file at %s' % source_file_path) if (not os.path.exists(dest_file_path) or os.path.getmtime(dest_file_path) < os.path.getmtime(source_file_path)): with open(source_file_path, 'rb') as fp: content = fp.read() subs = req.environ.get('subber.subs', {}) for name, (old_content, new_content, content_types, replace) in subs.iteritems(): content_type = mimetypes.guess_type(source_file_path)[0] if content_types and content_type not in content_types: continue if not isinstance(new_content, basestring): new_content = new_content(req) if replace: content = content.replace(old_content, new_content) else: content = content.replace(old_content, new_content + old_content) dest_dir = os.path.dirname(dest_file_path) if not os.path.exists(dest_dir): try: os.makedirs(dest_dir) except OSError, e: if e.errno == 17: # File already exists pass else: raise with open(dest_file_path, 'wb') as fp: fp.write(content) return FileApp(dest_file_path)
def wsgi_app(self, environ, start_response): filename = environ["PATH_INFO"].decode("utf-8") if filename == "/status": response_headers = [("Content-type", "text/html")] start_response("200 OK", response_headers) return ["200 OK"] # Sometimes, even after the user has clicked 'exit' in the page, # a browser sends a request for e.g. an audio file. if self.is_shutting_down and filename != "/release_database": response_headers = [("Content-type", "text/html")] start_response("503 Service Unavailable", response_headers) return ["Server stopped"] # Load database if needed. if not self.is_mnemosyne_loaded and filename != "/release_database": self.load_mnemosyne() self.release_database_after_timeout.ping() # All our request return to the root page, so if the path is '/', # return the html of the review widget. if filename == "/": # Process clicked buttons in the form. form = cgi.FieldStorage(fp=environ["wsgi.input"], environ=environ) if "show_answer" in form and not self.is_just_started: self.mnemosyne.review_widget().show_answer() page = self.mnemosyne.review_widget().to_html() elif "grade" in form and not self.is_just_started: grade = int(form["grade"].value) self.mnemosyne.review_widget().grade_answer(grade) page = self.mnemosyne.review_widget().to_html() elif "star" in form: self.mnemosyne.controller().star_current_card() page = self.mnemosyne.review_widget().to_html() elif "exit" in form: self.unload_mnemosyne() page = "Server stopped" self.wsgi_server.stop() self.stop_server_after_timeout = \ StopServerAfterTimeout(self.wsgi_server) self.stop_server_after_timeout.start() self.is_shutting_down = True else: page = self.mnemosyne.review_widget().to_html() if self.is_just_started: self.is_just_started = False # Serve the web page. response_headers = [("Content-type", "text/html")] start_response("200 OK", response_headers) return [page] elif filename == "/release_database": self.unload_mnemosyne() response_headers = [("Content-type", "text/html")] start_response("200 OK", response_headers) return ["200 OK"] # We need to serve a media file. else: full_path = self.mnemosyne.database().media_dir() for word in filename.split("/"): full_path = os.path.join(full_path, word) request = Request(environ) # Check if file exists, but work around Android not reporting # the correct filesystem encoding. try: exists = os.path.exists(full_path) except (UnicodeEncodeError, UnicodeDecodeError): _ENCODING = sys.getfilesystemencoding() or \ locale.getdefaultlocale()[1] or "utf-8" full_path = full_path.encode(_ENCODING) if os.path.exists(full_path): etag = "%s-%s-%s" % (os.path.getmtime(full_path), os.path.getsize(full_path), hash(full_path)) else: etag = "none" app = FileApp(full_path, etag=etag) return app(request)(environ, start_response)