本文整理汇总了Python中tornado.web.StaticFileHandler方法的典型用法代码示例。如果您正苦于以下问题:Python web.StaticFileHandler方法的具体用法?Python web.StaticFileHandler怎么用?Python web.StaticFileHandler使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.web
的用法示例。
在下文中一共展示了web.StaticFileHandler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tornadoserver
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
def tornadoserver():
setup_logging('tornadoserver')
app = create_app(parse_options())
fsh_folder = app.blueprints['flask_statics_helper'].static_folder
log_messages(app, OPTIONS['--port'], fsh_folder)
# Setup the application.
container = wsgi.WSGIContainer(app)
application = web.Application([
(r'/static/flask_statics_helper/(.*)', web.StaticFileHandler, dict(path=fsh_folder)),
(r'/(favicon\.ico)', web.StaticFileHandler, dict(path=app.static_folder)),
(r'/static/(.*)', web.StaticFileHandler, dict(path=app.static_folder)),
(r'.*', web.FallbackHandler, dict(fallback=container))
]) # From http://maxburstein.com/blog/django-static-files-heroku/
http_server = httpserver.HTTPServer(application)
http_server.bind(OPTIONS['--port'])
# Start the server.
http_server.start(0) # Forks multiple sub-processes
ioloop.IOLoop.instance().start()
示例2: swagger_handlers
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
def swagger_handlers():
"""Returns the swagger UI handlers
Returns:
[(route, handler)] -- list of Tornado URLSpec
"""
prefix = settings.default_settings.get('swagger_prefix', '/swagger')
if prefix[-1] != '/':
prefix += '/'
return [
URLSpec(prefix + r'spec.html$', SwaggerUIHandler,
settings.default_settings, name=settings.URL_SWAGGER_API_DOCS),
URLSpec(prefix + r'spec$', SwaggerApiHandler,
name=settings.URL_SWAGGER_API_SPEC),
(prefix + r'(.*\.(css|png|gif|js))', StaticFileHandler,
{'path': settings.default_settings.get('static_path')}),
]
示例3: _get_handler
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
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
示例4: _static_server
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
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...')
示例5: run
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
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'
示例6: get_static_routes
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
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
示例7: static_url
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
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)
示例8: execute
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
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
示例9: get_absolute_path
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
def get_absolute_path(cls, root, path):
"""返回 ``path`` 相对于 ``root`` 的绝对路径.
``root`` 是这个 `StaticFileHandler` 配置的路径(在大多数情
况下是 `Application` 的 ``static_path`` 设置).
这个类方法可能在子类中被复写. 默认情况下它返回一个文件系统
路径, 但其他字符串可以被使用, 只要它们是独特的并且被
子类复写的 `get_content` 理解.
.. versionadded:: 3.1
"""
abspath = os.path.abspath(os.path.join(root, path))
return abspath
示例10: static_url
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
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)
示例11: execute
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
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
示例12: get_absolute_path
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
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
示例13: __init__
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
def __init__(self, route):
"""
Bast Server Class. Runs on Tornado HTTP Server (http://www.tornadoweb.org/en/stable/)
Constructor for the Bast Server. Takes an instance of the route as parameter.
The Web handler with routes are handled here.
Config files are also loaded from the config/config.ini folder.
Appropriate configurations are loaded from the config file into the os environment for use
:param route:
"""
super(Bast, self).__init__()
init()
load_env()
self.config()
self.host = os.getenv("HOST", "127.0.0.1")
self.port = os.getenv("PORT", 2000)
self.debug = os.getenv("DEBUG", True)
self.handler = route.all().url
self.handler.append((r'/css/(.*)', StaticFileHandler, {"path": self.css_folder}))
self.handler.append((r'/script/(.*)', StaticFileHandler, {"path": self.script_folder}))
self.handler.append((r'/images/(.*)', StaticFileHandler, {"path": self.image_folder}))
# append the URL for static files to exception
self.handler.append((r'/exp/(.*)', StaticFileHandler,
{'path': os.path.join(os.path.dirname(os.path.realpath(__file__)), "exception")}))
示例14: get
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
def get(self, path):
return web.StaticFileHandler.get(self, path)
#-----------------------------------------------------------------------------
# File handler
#-----------------------------------------------------------------------------
# to minimize subclass changes:
示例15: static_url
# 需要导入模块: from tornado import web [as 别名]
# 或者: from tornado.web import StaticFileHandler [as 别名]
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)