本文整理匯總了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)