Python tornado.web.StaticFileHandler() Examples
The following are 30
code examples of tornado.web.StaticFileHandler().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
tornado.web
, or try the search function
.
Example #1
Source File: serve.py From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
def _static_server(host, port, site_dir): # Importing here to separate the code paths from the --livereload # alternative. _init_asyncio_patch() from tornado import ioloop from tornado import web application = web.Application([ (r"/(.*)", _get_handler(site_dir, web.StaticFileHandler), { "path": site_dir, "default_filename": "index.html" }), ]) application.listen(port=port, address=host) log.info('Running at: http://%s:%s/', host, port) log.info('Hold ctrl+c to quit.') try: ioloop.IOLoop.instance().start() except KeyboardInterrupt: log.info('Stopping server...')
Example #2
Source File: server.py From panel with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_static_routes(static_dirs): """ Returns a list of tornado routes of StaticFileHandlers given a dictionary of slugs and file paths to serve. """ patterns = [] for slug, path in static_dirs.items(): if not slug.startswith('/'): slug = '/' + slug if slug == '/static': raise ValueError("Static file route may not use /static " "this is reserved for internal use.") path = os.path.abspath(path) if not os.path.isdir(path): raise ValueError("Cannot serve non-existent path %s" % path) patterns.append( (r"%s/(.*)" % slug, StaticFileHandler, {"path": path}) ) return patterns
Example #3
Source File: draft_editor.py From ATX with Apache License 2.0 | 6 votes |
def run(basedir, port=8000): global cm basedir = os.path.abspath(basedir) cm = CaseManager(basedir) application = tornado.web.Application([ (r'/', MainHandler), (r'/frames/(.*)', StaticFileHandler, {'path':os.path.join(basedir, 'frames')}), (r'/case(.*)', CaseHandler), (r'/run', CaseRunnerHandler), (r'/(.*)', StaticFileHandler, {'path':os.path.join(__dir__, 'site')}), ], autoreload=True, static_hash_cache=False) if port is None: port = get_valid_port() webbrowser.open('http://127.0.0.1:%s' % port, new=2) application.listen(port) print 'Listen on', port print 'WorkDir:', basedir print 'Press Ctrl+C to stop...' try: tornado.ioloop.IOLoop.instance().start() except: print 'Done'
Example #4
Source File: serve.py From mkdocs with BSD 2-Clause "Simplified" License | 6 votes |
def _static_server(host, port, site_dir): # Importing here to separate the code paths from the --livereload # alternative. _init_asyncio_patch() from tornado import ioloop from tornado import web application = web.Application([ (r"/(.*)", _get_handler(site_dir, web.StaticFileHandler), { "path": site_dir, "default_filename": "index.html" }), ]) application.listen(port=port, address=host) log.info('Running at: http://%s:%s/', host, port) log.info('Hold ctrl+c to quit.') try: ioloop.IOLoop.instance().start() except KeyboardInterrupt: log.info('Stopping server...')
Example #5
Source File: serve.py From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
def _get_handler(site_dir, StaticFileHandler): from tornado.template import Loader class WebHandler(StaticFileHandler): def write_error(self, status_code, **kwargs): if status_code in (404, 500): error_page = '{}.html'.format(status_code) if isfile(join(site_dir, error_page)): self.write(Loader(site_dir).load(error_page).generate()) else: super().write_error(status_code, **kwargs) return WebHandler
Example #6
Source File: serve.py From mkdocs with BSD 2-Clause "Simplified" License | 6 votes |
def _get_handler(site_dir, StaticFileHandler): from tornado.template import Loader class WebHandler(StaticFileHandler): def write_error(self, status_code, **kwargs): if status_code in (404, 500): error_page = '{}.html'.format(status_code) if isfile(join(site_dir, error_page)): self.write(Loader(site_dir).load(error_page).generate()) else: super().write_error(status_code, **kwargs) return WebHandler
Example #7
Source File: serve.py From mkdocs with BSD 2-Clause "Simplified" License | 5 votes |
def _livereload(host, port, config, builder, site_dir): # We are importing here for anyone that has issues with livereload. Even if # this fails, the --no-livereload alternative should still work. _init_asyncio_patch() from livereload import Server import livereload.handlers class LiveReloadServer(Server): def get_web_handlers(self, script): handlers = super().get_web_handlers(script) # replace livereload handler return [(handlers[0][0], _get_handler(site_dir, livereload.handlers.StaticFileHandler), handlers[0][2],)] server = LiveReloadServer() # Watch the documentation files, the config file and the theme files. server.watch(config['docs_dir'], builder) server.watch(config['config_file_path'], builder) for d in config['theme'].dirs: server.watch(d, builder) # Run `serve` plugin events. server = config['plugins'].run_event('serve', server, config=config, builder=builder) server.serve(root=site_dir, host=host, port=port, restart_delay=0)
Example #8
Source File: jupytab.py From Jupytab with MIT License | 5 votes |
def create_server_app(listen_port, security_token, notebooks, ssl): notebook_store = CaseInsensitiveDict() for key, value in notebooks.items(): notebook_store[key] = KernelExecutor(**value) for key, value in notebook_store.items(): value.start() protocol = "https" if ssl else "http" if security_token: token_digest = hashlib.sha224(security_token.encode('utf-8')).hexdigest() print(f"""Your token is {token_digest} Please open : {protocol}://{socket.gethostname()}:{listen_port}""" f"/?security_token={token_digest}") else: token_digest = None print(f"""You have no defined token. Please note your process is not secured ! Please open : {protocol}://{socket.gethostname()}:{listen_port}""") server_app = Application([ (r"/evaluate", EvaluateHandler, {'notebook_store': notebook_store, 'security_token': token_digest}), (r"/" + api_kernel, APIHandler, {'notebook_store': notebook_store, 'security_token': token_digest}), (r"/" + restart_kernel + "/(.*)", RestartHandler, {'notebook_store': notebook_store, 'security_token': token_digest}), (r"/" + access_kernel + "/(.*)", ReverseProxyHandler, {'notebook_store': notebook_store, 'security_token': token_digest}), (r"/(.*)", StaticFileHandler, {'path': root, "default_filename": "index.html"}), ]) return server_app
Example #9
Source File: main.py From rxpy-example with MIT License | 5 votes |
def main(): AsyncIOMainLoop().install() port = os.environ.get("PORT", 8080) app = Application([ url(r"/", MainHandler), (r'/ws', WSHandler), (r'/static/(.*)', StaticFileHandler, {'path': "."}) ]) print("Starting server at port: %s" % port) app.listen(port) asyncio.get_event_loop().run_forever()
Example #10
Source File: handlers.py From elyra with Apache License 2.0 | 5 votes |
def get(self): return web.StaticFileHandler.get(self, self.get_resource_metadata()[0])
Example #11
Source File: handlers.py From elyra with Apache License 2.0 | 5 votes |
def initialize(self): web.StaticFileHandler.initialize(self, path=os.path.dirname(__file__))
Example #12
Source File: main.py From enaml-web with MIT License | 5 votes |
def main(): enaml_app = WebApplication() app = Application([ (r"/", MainHandler), (r"/static/(.*)", StaticFileHandler, {"path": "static"}), ]) app.listen(8888) print("Listening on 8888") IOLoop.current().start()
Example #13
Source File: core.py From swagger-ui-py with Apache License 2.0 | 5 votes |
def _tornado_handler(self): from tornado.web import RequestHandler, StaticFileHandler interface = self class DocHandler(RequestHandler): def get(self, *args, **kwargs): return self.write(interface.doc_html) class EditorHandler(RequestHandler): def get(self, *args, **kwargs): return self.write(interface.editor_html) class ConfigHandler(RequestHandler): def get(self, *args, **kwargs): return self.write(interface.get_config(self.request.host)) handlers = [ (self._uri(), DocHandler), (self._uri('/'), DocHandler), (self._uri('/swagger.json'), ConfigHandler), (self._uri('/(.+)'), StaticFileHandler, {'path': self.static_dir}), ] if self._editor: handlers.insert(1, (self._uri('/editor'), EditorHandler)) self._app.add_handlers('.*', handlers)
Example #14
Source File: formgrader.py From nbgrader with BSD 3-Clause "New" or "Revised" License | 5 votes |
def init_handlers(self, webapp): h = [] h.extend(handlers.default_handlers) h.extend(apihandlers.default_handlers) h.extend([ (r"/formgrader/static/(.*)", web.StaticFileHandler, {'path': handlers.static_path}), (r"/formgrader/.*", handlers.Template404) ]) def rewrite(x): pat = ujoin(webapp.settings['base_url'], x[0].lstrip('/')) return (pat,) + x[1:] webapp.add_handlers(".*$", [rewrite(x) for x in h])
Example #15
Source File: web.py From pySINDy with MIT License | 5 votes |
def get_absolute_path(cls, root, path): """Returns the absolute location of ``path`` relative to ``root``. ``root`` is the path configured for this `StaticFileHandler` (in most cases the ``static_path`` `Application` setting). This class method may be overridden in subclasses. By default it returns a filesystem path, but other strings may be used as long as they are unique and understood by the subclass's overridden `get_content`. .. versionadded:: 3.1 """ abspath = os.path.abspath(os.path.join(root, path)) return abspath
Example #16
Source File: web.py From EventGhost with GNU General Public License v2.0 | 5 votes |
def static_url(self, path, include_host=None, **kwargs): """Returns a static URL for the given relative static file path. This method requires you set the ``static_path`` setting in your application (which specifies the root directory of your static files). This method returns a versioned url (by default appending ``?v=<signature>``), which allows the static files to be cached indefinitely. This can be disabled by passing ``include_version=False`` (in the default implementation; other static file implementations are not required to support this, but they may support other options). By default this method returns URLs relative to the current host, but if ``include_host`` is true the URL returned will be absolute. If this handler has an ``include_host`` attribute, that value will be used as the default for all `static_url` calls that do not pass ``include_host`` as a keyword argument. """ self.require_setting("static_path", "static_url") get_url = self.settings.get("static_handler_class", StaticFileHandler).make_static_url if include_host is None: include_host = getattr(self, "include_host", False) if include_host: base = self.request.protocol + "://" + self.request.host else: base = "" return base + get_url(self.settings, path, **kwargs)
Example #17
Source File: web.py From pySINDy with MIT License | 5 votes |
def execute(self): # If template cache is disabled (usually in the debug mode), # re-compile templates and reload static files on every # request so you don't need to restart to see changes if not self.application.settings.get("compiled_template_cache", True): with RequestHandler._template_loader_lock: for loader in RequestHandler._template_loaders.values(): loader.reset() if not self.application.settings.get('static_hash_cache', True): StaticFileHandler.reset() self.handler = self.handler_class(self.application, self.request, **self.handler_kwargs) transforms = [t(self.request) for t in self.application.transforms] if self.stream_request_body: self.handler._prepared_future = Future() # Note that if an exception escapes handler._execute it will be # trapped in the Future it returns (which we are ignoring here, # leaving it to be logged when the Future is GC'd). # However, that shouldn't happen because _execute has a blanket # except handler, and we cannot easily access the IOLoop here to # call add_future (because of the requirement to remain compatible # with WSGI) self.handler._execute(transforms, *self.path_args, **self.path_kwargs) # If we are streaming the request body, then execute() is finished # when the handler has prepared to receive the body. If not, # it doesn't matter when execute() finishes (so we return None) return self.handler._prepared_future
Example #18
Source File: web.py From honeything with GNU General Public License v3.0 | 5 votes |
def __init__(self, handlers=None, default_host="", transforms=None, wsgi=False, **settings): if transforms is None: self.transforms = [] if settings.get("gzip"): self.transforms.append(GZipContentEncoding) self.transforms.append(ChunkedTransferEncoding) else: self.transforms = transforms self.handlers = [] self.named_handlers = {} self.default_host = default_host self.settings = settings self.ui_modules = {'linkify': _linkify, 'xsrf_form_html': _xsrf_form_html, 'Template': TemplateModule, } self.ui_methods = {} self._wsgi = wsgi self._load_ui_modules(settings.get("ui_modules", {})) self._load_ui_methods(settings.get("ui_methods", {})) if self.settings.get("static_path"): path = self.settings["static_path"] handlers = list(handlers or []) static_url_prefix = settings.get("static_url_prefix", "/static/") static_handler_class = settings.get("static_handler_class", StaticFileHandler) static_handler_args = settings.get("static_handler_args", {}) static_handler_args['path'] = path for pattern in [re.escape(static_url_prefix) + r"(.*)", r"/(favicon\.ico)", r"/(robots\.txt)"]: handlers.insert(0, (pattern, static_handler_class, static_handler_args)) if handlers: self.add_handlers(".*$", handlers) # Automatically reload modified modules if self.settings.get("debug") and not wsgi: from tornado import autoreload autoreload.start()
Example #19
Source File: web.py From honeything with GNU General Public License v3.0 | 5 votes |
def __init__(self, handlers=None, default_host="", transforms=None, wsgi=False, **settings): if transforms is None: self.transforms = [] if settings.get("gzip"): self.transforms.append(GZipContentEncoding) self.transforms.append(ChunkedTransferEncoding) else: self.transforms = transforms self.handlers = [] self.named_handlers = {} self.default_host = default_host self.settings = settings self.ui_modules = {} self.ui_methods = {} self._wsgi = wsgi self._load_ui_modules(settings.get("ui_modules", {})) self._load_ui_methods(settings.get("ui_methods", {})) if self.settings.get("static_path"): path = self.settings["static_path"] handlers = list(handlers or []) static_url_prefix = settings.get("static_url_prefix", "/static/") handlers = [ (re.escape(static_url_prefix) + r"(.*)", StaticFileHandler, dict(path=path)), (r"/(favicon\.ico)", StaticFileHandler, dict(path=path)), (r"/(robots\.txt)", StaticFileHandler, dict(path=path)), ] + handlers if handlers: self.add_handlers(".*$", handlers) # Automatically reload modified modules if self.settings.get("debug") and not wsgi: import autoreload autoreload.start()
Example #20
Source File: web.py From pySINDy with MIT License | 5 votes |
def static_url(self, path, include_host=None, **kwargs): """Returns a static URL for the given relative static file path. This method requires you set the ``static_path`` setting in your application (which specifies the root directory of your static files). This method returns a versioned url (by default appending ``?v=<signature>``), which allows the static files to be cached indefinitely. This can be disabled by passing ``include_version=False`` (in the default implementation; other static file implementations are not required to support this, but they may support other options). By default this method returns URLs relative to the current host, but if ``include_host`` is true the URL returned will be absolute. If this handler has an ``include_host`` attribute, that value will be used as the default for all `static_url` calls that do not pass ``include_host`` as a keyword argument. """ self.require_setting("static_path", "static_url") get_url = self.settings.get("static_handler_class", StaticFileHandler).make_static_url if include_host is None: include_host = getattr(self, "include_host", False) if include_host: base = self.request.protocol + "://" + self.request.host else: base = "" return base + get_url(self.settings, path, **kwargs)
Example #21
Source File: gallery.py From tljh-voila-gallery with BSD 3-Clause "New" or "Revised" License | 5 votes |
def make_app(): service_prefix = os.environ['JUPYTERHUB_SERVICE_PREFIX'] app_settings = { 'static_path': os.path.join(os.path.dirname(__file__), 'static'), 'static_url_prefix': f'{service_prefix}/static/' } return web.Application([ (rf'{service_prefix}?', GalleryHandler), (rf'{service_prefix}static/(.*)', web.StaticFileHandler, { 'path': app_settings['static_path'] }) ], **app_settings)
Example #22
Source File: web.py From honeything with GNU General Public License v3.0 | 5 votes |
def static_url(self, path, include_host=None): """Returns a static URL for the given relative static file path. This method requires you set the 'static_path' setting in your application (which specifies the root directory of your static files). We append ?v=<signature> to the returned URL, which makes our static file handler set an infinite expiration header on the returned content. The signature is based on the content of the file. By default this method returns URLs relative to the current host, but if ``include_host`` is true the URL returned will be absolute. If this handler has an ``include_host`` attribute, that value will be used as the default for all `static_url` calls that do not pass ``include_host`` as a keyword argument. """ self.require_setting("static_path", "static_url") static_handler_class = self.settings.get( "static_handler_class", StaticFileHandler) if include_host is None: include_host = getattr(self, "include_host", False) if include_host: base = self.request.protocol + "://" + self.request.host else: base = "" return base + static_handler_class.make_static_url(self.settings, path)
Example #23
Source File: web.py From tornado-zh with MIT License | 5 votes |
def static_url(self, path, include_host=None, **kwargs): """为给定的相对路径的静态文件返回一个静态URL. 这个方法需要你在你的应用中设置 ``static_path`` (既你 静态文件的根目录). 这个方法返回一个带有版本的url (默认情况下会添加 ``?v=<signature>``), 这会允许静态文件被无限期缓存. 这可以被 禁用通过传递 ``include_version=False`` (默认已经实现; 其他静态文件的实现不需要支持这一点, 但它们可能支持其他选项). 默认情况下这个方法返回当前host的相对URL, 但是如果 ``include_host`` 为true则返回的将是绝对路径的URL. 如果这个处理函数有一个 ``include_host`` 属性, 该值将被所有的 `static_url` 调用默认使用, 而不需要传递 ``include_host`` 作为一个关键字参数. """ self.require_setting("static_path", "static_url") get_url = self.settings.get("static_handler_class", StaticFileHandler).make_static_url if include_host is None: include_host = getattr(self, "include_host", False) if include_host: base = self.request.protocol + "://" + self.request.host else: base = "" return base + get_url(self.settings, path, **kwargs)
Example #24
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def get_absolute_path(cls, root: str, path: str) -> str: """Returns the absolute location of ``path`` relative to ``root``. ``root`` is the path configured for this `StaticFileHandler` (in most cases the ``static_path`` `Application` setting). This class method may be overridden in subclasses. By default it returns a filesystem path, but other strings may be used as long as they are unique and understood by the subclass's overridden `get_content`. .. versionadded:: 3.1 """ abspath = os.path.abspath(os.path.join(root, path)) return abspath
Example #25
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def execute(self) -> Optional[Awaitable[None]]: # If template cache is disabled (usually in the debug mode), # re-compile templates and reload static files on every # request so you don't need to restart to see changes if not self.application.settings.get("compiled_template_cache", True): with RequestHandler._template_loader_lock: for loader in RequestHandler._template_loaders.values(): loader.reset() if not self.application.settings.get("static_hash_cache", True): StaticFileHandler.reset() self.handler = self.handler_class( self.application, self.request, **self.handler_kwargs ) transforms = [t(self.request) for t in self.application.transforms] if self.stream_request_body: self.handler._prepared_future = Future() # Note that if an exception escapes handler._execute it will be # trapped in the Future it returns (which we are ignoring here, # leaving it to be logged when the Future is GC'd). # However, that shouldn't happen because _execute has a blanket # except handler, and we cannot easily access the IOLoop here to # call add_future (because of the requirement to remain compatible # with WSGI) fut = gen.convert_yielded( self.handler._execute(transforms, *self.path_args, **self.path_kwargs) ) fut.add_done_callback(lambda f: f.result()) # If we are streaming the request body, then execute() is finished # when the handler has prepared to receive the body. If not, # it doesn't matter when execute() finishes (so we return None) return self.handler._prepared_future
Example #26
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def static_url(self, path: str, include_host: bool = None, **kwargs: Any) -> str: """Returns a static URL for the given relative static file path. This method requires you set the ``static_path`` setting in your application (which specifies the root directory of your static files). This method returns a versioned url (by default appending ``?v=<signature>``), which allows the static files to be cached indefinitely. This can be disabled by passing ``include_version=False`` (in the default implementation; other static file implementations are not required to support this, but they may support other options). By default this method returns URLs relative to the current host, but if ``include_host`` is true the URL returned will be absolute. If this handler has an ``include_host`` attribute, that value will be used as the default for all `static_url` calls that do not pass ``include_host`` as a keyword argument. """ self.require_setting("static_path", "static_url") get_url = self.settings.get( "static_handler_class", StaticFileHandler ).make_static_url if include_host is None: include_host = getattr(self, "include_host", False) if include_host: base = self.request.protocol + "://" + self.request.host else: base = "" return base + get_url(self.settings, path, **kwargs)
Example #27
Source File: web.py From EventGhost with GNU General Public License v2.0 | 5 votes |
def execute(self): # If template cache is disabled (usually in the debug mode), # re-compile templates and reload static files on every # request so you don't need to restart to see changes if not self.application.settings.get("compiled_template_cache", True): with RequestHandler._template_loader_lock: for loader in RequestHandler._template_loaders.values(): loader.reset() if not self.application.settings.get('static_hash_cache', True): StaticFileHandler.reset() self.handler = self.handler_class(self.application, self.request, **self.handler_kwargs) transforms = [t(self.request) for t in self.application.transforms] if self.stream_request_body: self.handler._prepared_future = Future() # Note that if an exception escapes handler._execute it will be # trapped in the Future it returns (which we are ignoring here, # leaving it to be logged when the Future is GC'd). # However, that shouldn't happen because _execute has a blanket # except handler, and we cannot easily access the IOLoop here to # call add_future (because of the requirement to remain compatible # with WSGI) self.handler._execute(transforms, *self.path_args, **self.path_kwargs) # If we are streaming the request body, then execute() is finished # when the handler has prepared to receive the body. If not, # it doesn't matter when execute() finishes (so we return None) return self.handler._prepared_future
Example #28
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def get_absolute_path(cls, root: str, path: str) -> str: """Returns the absolute location of ``path`` relative to ``root``. ``root`` is the path configured for this `StaticFileHandler` (in most cases the ``static_path`` `Application` setting). This class method may be overridden in subclasses. By default it returns a filesystem path, but other strings may be used as long as they are unique and understood by the subclass's overridden `get_content`. .. versionadded:: 3.1 """ abspath = os.path.abspath(os.path.join(root, path)) return abspath
Example #29
Source File: web.py From teleport with Apache License 2.0 | 5 votes |
def execute(self) -> Optional[Awaitable[None]]: # If template cache is disabled (usually in the debug mode), # re-compile templates and reload static files on every # request so you don't need to restart to see changes if not self.application.settings.get("compiled_template_cache", True): with RequestHandler._template_loader_lock: for loader in RequestHandler._template_loaders.values(): loader.reset() if not self.application.settings.get("static_hash_cache", True): StaticFileHandler.reset() self.handler = self.handler_class( self.application, self.request, **self.handler_kwargs ) transforms = [t(self.request) for t in self.application.transforms] if self.stream_request_body: self.handler._prepared_future = Future() # Note that if an exception escapes handler._execute it will be # trapped in the Future it returns (which we are ignoring here, # leaving it to be logged when the Future is GC'd). # However, that shouldn't happen because _execute has a blanket # except handler, and we cannot easily access the IOLoop here to # call add_future (because of the requirement to remain compatible # with WSGI) fut = gen.convert_yielded( self.handler._execute(transforms, *self.path_args, **self.path_kwargs) ) fut.add_done_callback(lambda f: f.result()) # If we are streaming the request body, then execute() is finished # when the handler has prepared to receive the body. If not, # it doesn't matter when execute() finishes (so we return None) return self.handler._prepared_future
Example #30
Source File: web.py From EventGhost with GNU General Public License v2.0 | 5 votes |
def get_absolute_path(cls, root, path): """Returns the absolute location of ``path`` relative to ``root``. ``root`` is the path configured for this `StaticFileHandler` (in most cases the ``static_path`` `Application` setting). This class method may be overridden in subclasses. By default it returns a filesystem path, but other strings may be used as long as they are unique and understood by the subclass's overridden `get_content`. .. versionadded:: 3.1 """ abspath = os.path.abspath(os.path.join(root, path)) return abspath