本文整理汇总了Python中tornado.web.Application.add_handlers方法的典型用法代码示例。如果您正苦于以下问题:Python Application.add_handlers方法的具体用法?Python Application.add_handlers怎么用?Python Application.add_handlers使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.web.Application
的用法示例。
在下文中一共展示了Application.add_handlers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_app
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
def get_app(self):
app = Application()
def request_callable(request):
request.connection.write_headers(
ResponseStartLine("HTTP/1.1", 200, "OK"),
HTTPHeaders({"Content-Length": "2"}))
request.connection.write(b"OK")
request.connection.finish()
router = CustomRouter()
router.add_routes({
"/nested_handler": (app, _get_named_handler("nested_handler"))
})
app.add_handlers(".*", [
(HostMatches("www.example.com"), [
(PathMatches("/first_handler"),
"tornado.test.routing_test.SecondHandler", {}, "second_handler")
]),
Rule(PathMatches("/.*handler"), router),
Rule(PathMatches("/first_handler"), FirstHandler, name="first_handler"),
Rule(PathMatches("/request_callable"), request_callable),
("/connection_delegate", ConnectionDelegate())
])
return app
示例2: __call__
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
def __call__(self, application=None):
"""
This is used to mount the handlers in the
applet onto a new `tornado.web.Application` object or
an existing one thats passed in.
:arg tornado.web.Application application The application providing the
mount point for the handlers in the applet. A new application object is
created if this argument is `None`.
"""
if not application:
application = Application()
application.add_handlers(self.host_pattern, self.handlers)
return application
示例3: initWebServer
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
def initWebServer(options={}):
options.setdefault('port', 8081)
options.setdefault('host', '0.0.0.0')
options.setdefault('log_dir', None)
options.setdefault('username', '')
options.setdefault('password', '')
options.setdefault('web_root', '/')
assert isinstance(options['port'], int)
assert 'data_root' in options
# tornado setup
# Load the app
app = Application([],
debug=False,
gzip=True,
xheaders=sickbeard.HANDLE_REVERSE_PROXY,
cookie_secret='61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo='
)
# Main Handler
app.add_handlers(".*$", [
(r"%s" % options['web_root'], RedirectHandler, {'url': '%s/home/' % options['web_root']}),
(r'%s/(.*)(/?)' % options['web_root'], webserve.MainHandler)
])
# Static Path Handler
app.add_handlers(".*$", [
(r'%s/(favicon\.ico)' % options['web_root'], MultiStaticFileHandler,
{'paths': [os.path.join(options['data_root'], 'images/ico/favicon.ico')]}),
(r'%s/%s/(.*)(/?)' % (options['web_root'], 'images'), MultiStaticFileHandler,
{'paths': [os.path.join(options['data_root'], 'images')]}),
(r'%s/%s/(.*)(/?)' % (options['web_root'], 'css'), MultiStaticFileHandler,
{'paths': [os.path.join(options['data_root'], 'css')]}),
(r'%s/%s/(.*)(/?)' % (options['web_root'], 'js'), MultiStaticFileHandler,
{'paths': [os.path.join(options['data_root'], 'js')]})
])
global server
protocol = "http"
server = HTTPServer(app, no_keep_alive=True)
logger.log(u"Starting SickRage on " + protocol + "://" + str(options['host']) + ":" + str(
options['port']) + "/")
server.listen(options['port'], options['host'])
示例4: get_app
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
def get_app(self):
app = Application()
def request_callable(request):
request.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")
request.finish()
app.add_handlers(".*", [
(HostMatches("www.example.com"), [
(PathMatches("/first_handler"), "tornado.test.routing_test.SecondHandler", {}, "second_handler")
]),
Rule(PathMatches("/first_handler"), FirstHandler, name="first_handler"),
Rule(PathMatches("/request_callable"), request_callable),
("/connection_delegate", ConnectionDelegate())
])
return app
示例5: run
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
def run(self, port=5000, host='127.0.0.1', **kwargs):
if self.app.debug or kwargs.get('debug', False):
# Attach debugger to Flask routes
self.app.debug = True
self.app.wsgi_app = DebuggedApplication(self.app.wsgi_app, True)
# Attach debugger to Tornado routes
self.debug_app = DebuggedApplication(WSGIAdapter(self), True)
debug_container = WSGIContainer(self.debug_app)
# Socket handlers must bypass debugger
if hasattr(self, 'socket_handlers'):
socket_app = Application([
(r".*", FallbackHandler, dict(fallback=WSGIContainer(self.debug_app)))
])
socket_app.add_handlers(r".*", self.socket_handlers)
http_server = HTTPServer(socket_app)
else:
http_server = HTTPServer(debug_container)
autoreload.start()
else:
if hasattr(self, 'socket_handlers'):
self.add_handlers(r".*", self.socket_handlers)
http_server = HTTPServer(self)
http_server.listen(port, address=host)
IOLoop.current().start()
示例6: initWebServer
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
def initWebServer(options={}):
options.setdefault('port', 8081)
options.setdefault('host', '0.0.0.0')
options.setdefault('log_dir', None)
options.setdefault('username', '')
options.setdefault('password', '')
options.setdefault('web_root', '/')
assert isinstance(options['port'], int)
assert 'data_root' in options
def http_error_401_hander(status, message, traceback, version):
""" Custom handler for 401 error """
if status != "401 Unauthorized":
logger.log(u"Tornado caught an error: %s %s" % (status, message), logger.ERROR)
logger.log(traceback, logger.DEBUG)
return r'''<!DOCTYPE html>
<html>
<head>
<title>%s</title>
</head>
<body>
<br/>
<font color="#0000FF">Error %s: You need to provide a valid username and password.</font>
</body>
</html>
''' % ('Access denied', status)
def http_error_404_hander(status, message, traceback, version):
""" Custom handler for 404 error, redirect back to main page """
return r'''<!DOCTYPE html>
<html>
<head>
<title>404</title>
<script type="text/javascript" charset="utf-8">
<!--
location.href = "%s/home/"
//-->
</script>
</head>
<body>
<br/>
</body>
</html>
''' % options['web_root']
# tornado setup
enable_https = options['enable_https']
https_cert = options['https_cert']
https_key = options['https_key']
if enable_https:
# If either the HTTPS certificate or key do not exist, make some self-signed ones.
if not (https_cert and os.path.exists(https_cert)) or not (https_key and os.path.exists(https_key)):
if not create_https_certificates(https_cert, https_key):
logger.log(u"Unable to create CERT/KEY files, disabling HTTPS")
sickbeard.ENABLE_HTTPS = False
enable_https = False
if not (os.path.exists(https_cert) and os.path.exists(https_key)):
logger.log(u"Disabled HTTPS because of missing CERT and KEY files", logger.WARNING)
sickbeard.ENABLE_HTTPS = False
enable_https = False
# Load the app
app = Application([],
debug=True,
gzip=True,
autoreload=True,
xheaders=False,
cookie_secret='61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=',
login_url='/login'
)
# Index Handler
app.add_handlers(".*$", [
(r"/", RedirectHandler, {'url': '/home/'}),
(r'/login', webserve.LoginHandler),
(r'/api/(.*)(/?)', webapi.Api),
(r'%s(.*)(/?)' % options['web_root'], webserve.IndexHandler)
])
# Static Path Handler
app.add_handlers(".*$", [
('%s/%s/(.*)([^/]*)' % (options['web_root'], 'images'), MultiStaticFileHandler,
{'paths': [os.path.join(options['data_root'], 'images'),
os.path.join(sickbeard.CACHE_DIR, 'images'),
os.path.join(sickbeard.CACHE_DIR, 'images', 'thumbnails')]}),
('%s/%s/(.*)([^/]*)' % (options['web_root'], 'css'), MultiStaticFileHandler,
{'paths': [os.path.join(options['data_root'], 'css')]}),
('%s/%s/(.*)([^/]*)' % (options['web_root'], 'js'), MultiStaticFileHandler,
{'paths': [os.path.join(options['data_root'], 'js')]})
])
global server
if enable_https:
protocol = "https"
server = HTTPServer(app, no_keep_alive=True,
ssl_options={"certfile": https_cert, "keyfile": https_key})
#.........这里部分代码省略.........
示例7: WebServer
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
class WebServer(object):
def __init__(self):
super(WebServer, self).__init__()
self.name = "TORNADO"
self.daemon = True
self.started = False
self.video_root = None
self.api_root = None
self.app = None
self.server = None
def start(self):
self.started = True
# load languages
tornado.locale.load_gettext_translations(sickrage.LOCALE_DIR, 'messages')
# clear mako cache folder
mako_cache = os.path.join(sickrage.app.cache_dir, 'mako')
if os.path.isdir(mako_cache):
shutil.rmtree(mako_cache)
# video root
if sickrage.app.config.root_dirs:
root_dirs = sickrage.app.config.root_dirs.split('|')
self.video_root = root_dirs[int(root_dirs[0]) + 1]
# web root
if sickrage.app.config.web_root:
sickrage.app.config.web_root = sickrage.app.config.web_root = (
'/' + sickrage.app.config.web_root.lstrip('/').strip('/'))
# api root
self.api_root = r'%s/api/%s' % (sickrage.app.config.web_root, sickrage.app.config.api_key)
# tornado setup
if sickrage.app.config.enable_https:
# If either the HTTPS certificate or key do not exist, make some self-signed ones.
if not (
sickrage.app.config.https_cert and os.path.exists(
sickrage.app.config.https_cert)) or not (
sickrage.app.config.https_key and os.path.exists(sickrage.app.config.https_key)):
if not create_https_certificates(sickrage.app.config.https_cert,
sickrage.app.config.https_key):
sickrage.app.log.info("Unable to create CERT/KEY files, disabling HTTPS")
sickrage.app.config.enable_https = False
if not (os.path.exists(sickrage.app.config.https_cert) and os.path.exists(
sickrage.app.config.https_key)):
sickrage.app.log.warning("Disabled HTTPS because of missing CERT and KEY files")
sickrage.app.config.enable_https = False
# Load the app
self.app = Application(
debug=True,
autoreload=False,
gzip=sickrage.app.config.web_use_gzip,
cookie_secret=sickrage.app.config.web_cookie_secret,
login_url='%s/login/' % sickrage.app.config.web_root)
# Websocket handler
self.app.add_handlers(".*$", [
(r'%s/ws/ui' % sickrage.app.config.web_root, WebSocketUIHandler)
])
# Static File Handlers
self.app.add_handlers('.*$', [
# api
(r'%s/api/(\w{32})(/?.*)' % sickrage.app.config.web_root, ApiHandler),
# redirect to home
(r"(%s)" % sickrage.app.config.web_root, RedirectHandler,
{"url": "%s/home" % sickrage.app.config.web_root}),
# api builder
(r'%s/api/builder' % sickrage.app.config.web_root, RedirectHandler,
{"url": sickrage.app.config.web_root + '/apibuilder/'}),
# login
(r'%s/login(/?)' % sickrage.app.config.web_root, LoginHandler),
# logout
(r'%s/logout(/?)' % sickrage.app.config.web_root, LogoutHandler),
# calendar
(r'%s/calendar' % sickrage.app.config.web_root, CalendarHandler),
# favicon
(r'%s/(favicon\.ico)' % sickrage.app.config.web_root, StaticNoCacheFileHandler,
{"path": os.path.join(sickrage.app.config.gui_static_dir, 'images/favicon.ico')}),
# images
(r'%s/images/(.*)' % sickrage.app.config.web_root, StaticImageHandler,
{"path": os.path.join(sickrage.app.config.gui_static_dir, 'images')}),
# css
(r'%s/css/(.*)' % sickrage.app.config.web_root, StaticNoCacheFileHandler,
{"path": os.path.join(sickrage.app.config.gui_static_dir, 'css')}),
# scss
#.........这里部分代码省略.........
示例8: runCouchPotato
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
#.........这里部分代码省略.........
api_key = Env.setting("api_key")
if not api_key:
api_key = uuid4().hex
Env.setting("api_key", value=api_key)
api_base = r"%sapi/%s/" % (web_base, api_key)
Env.set("api_base", api_base)
# Basic config
host = Env.setting("host", default="0.0.0.0")
host6 = Env.setting("host6", default="::")
config = {
"use_reloader": reloader,
"port": tryInt(Env.setting("port", default=5050)),
"host": host if host and len(host) > 0 else "0.0.0.0",
"host6": host6 if host6 and len(host6) > 0 else "::",
"ssl_cert": Env.setting("ssl_cert", default=None),
"ssl_key": Env.setting("ssl_key", default=None),
}
# Load the app
application = Application(
[],
log_function=lambda x: None,
debug=config["use_reloader"],
gzip=True,
cookie_secret=api_key,
login_url="%slogin/" % web_base,
)
Env.set("app", application)
# Request handlers
application.add_handlers(
".*$",
[
(r"%snonblock/(.*)(/?)" % api_base, NonBlockHandler),
# API handlers
(r"%s(.*)(/?)" % api_base, ApiHandler), # Main API handler
(r"%sgetkey(/?)" % web_base, KeyHandler), # Get API key
(r"%s" % api_base, RedirectHandler, {"url": web_base + "docs/"}), # API docs
# Login handlers
(r"%slogin(/?)" % web_base, LoginHandler),
(r"%slogout(/?)" % web_base, LogoutHandler),
# Catch all webhandlers
(r"%s(.*)(/?)" % web_base, WebHandler),
(r"(.*)", WebHandler),
],
)
# Static paths
static_path = "%sstatic/" % web_base
for dir_name in ["fonts", "images", "scripts", "style"]:
application.add_handlers(
".*$",
[
(
"%s%s/(.*)" % (static_path, dir_name),
StaticFileHandler,
{"path": sp(os.path.join(base_path, "couchpotato", "static", dir_name))},
)
],
)
Env.set("static_path", static_path)
# Load configs & plugins
示例9: runCouchPotato
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
#.........这里部分代码省略.........
# Create app
from couchpotato import WebHandler
web_base = ('/' + Env.setting('url_base').lstrip('/') + '/') if Env.setting('url_base') else '/'
Env.set('web_base', web_base)
api_key = Env.setting('api_key')
api_base = r'%sapi/%s/' % (web_base, api_key)
Env.set('api_base', api_base)
# Basic config
host = Env.setting('host', default = '0.0.0.0')
# app.debug = development
config = {
'use_reloader': reloader,
'port': tryInt(Env.setting('port', default = 5050)),
'host': host if host and len(host) > 0 else '0.0.0.0',
'ssl_cert': Env.setting('ssl_cert', default = None),
'ssl_key': Env.setting('ssl_key', default = None),
}
# Load the app
application = Application([],
log_function = lambda x : None,
debug = config['use_reloader'],
gzip = True,
cookie_secret = api_key,
login_url = '%slogin/' % web_base,
)
Env.set('app', application)
# Request handlers
application.add_handlers(".*$", [
(r'%snonblock/(.*)(/?)' % api_base, NonBlockHandler),
# API handlers
(r'%s(.*)(/?)' % api_base, ApiHandler), # Main API handler
(r'%sgetkey(/?)' % web_base, KeyHandler), # Get API key
(r'%s' % api_base, RedirectHandler, {"url": web_base + 'docs/'}), # API docs
# Login handlers
(r'%slogin(/?)' % web_base, LoginHandler),
(r'%slogout(/?)' % web_base, LogoutHandler),
# Catch all webhandlers
(r'%s(.*)(/?)' % web_base, WebHandler),
(r'(.*)', WebHandler),
])
# Static paths
static_path = '%sstatic/' % web_base
for dir_name in ['fonts', 'images', 'scripts', 'style']:
application.add_handlers(".*$", [
('%s%s/(.*)' % (static_path, dir_name), StaticFileHandler, {'path': toUnicode(os.path.join(base_path, 'couchpotato', 'static', dir_name))})
])
Env.set('static_path', static_path)
# Load configs & plugins
loader = Env.get('loader')
loader.preload(root = toUnicode(base_path))
loader.run()
# Fill database with needed stuff
示例10: runCouchPotato
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
#.........这里部分代码省略.........
Env.set('web_base', web_base)
api_key = Env.setting('api_key')
if not api_key:
api_key = uuid4().hex
Env.setting('api_key', value = api_key)
api_base = r'%sapi/%s/' % (web_base, api_key)
Env.set('api_base', api_base)
# Basic config
host = Env.setting('host', default = '0.0.0.0')
# app.debug = development
config = {
'use_reloader': reloader,
'port': tryInt(Env.setting('port', default = 5050)),
'host': host if host and len(host) > 0 else '0.0.0.0',
'ssl_cert': Env.setting('ssl_cert', default = None),
'ssl_key': Env.setting('ssl_key', default = None),
}
# Load the app
application = Application(
[],
log_function = lambda x: None,
debug = config['use_reloader'],
gzip = True,
cookie_secret = api_key,
login_url = '%slogin/' % web_base,
)
Env.set('app', application)
# Request handlers
application.add_handlers(".*$", [
(r'%snonblock/(.*)(/?)' % api_base, NonBlockHandler),
# API handlers
(r'%s(.*)(/?)' % api_base, ApiHandler), # Main API handler
(r'%sgetkey(/?)' % web_base, KeyHandler), # Get API key
(r'%s' % api_base, RedirectHandler, {"url": web_base + 'docs/'}), # API docs
# Login handlers
(r'%slogin(/?)' % web_base, LoginHandler),
(r'%slogout(/?)' % web_base, LogoutHandler),
# Catch all webhandlers
(r'%s(.*)(/?)' % web_base, WebHandler),
(r'(.*)', WebHandler),
])
# Static paths
static_path = '%sstatic/' % web_base
for dir_name in ['fonts', 'images', 'scripts', 'style']:
application.add_handlers(".*$", [
('%s%s/(.*)' % (static_path, dir_name), StaticFileHandler, {'path': sp(os.path.join(base_path, 'couchpotato', 'static', dir_name))})
])
Env.set('static_path', static_path)
# Load configs & plugins
loader = Env.get('loader')
loader.preload(root = sp(base_path))
loader.run()
# Fill database with needed stuff
fireEvent('database.setup')
if not db_exists:
示例11: srWebServer
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
class srWebServer(object):
def __init__(self):
self.io_loop = IOLoop.instance()
self.running = True
self.restart = False
self.open_browser = False
self.port = sickrage.srConfig.WEB_PORT
self.host = sickrage.srConfig.WEB_HOST
# video root
if sickrage.srConfig.ROOT_DIRS:
root_dirs = sickrage.srConfig.ROOT_DIRS.split("|")
self.video_root = root_dirs[int(root_dirs[0]) + 1]
else:
self.video_root = None
# web root
if sickrage.srConfig.WEB_ROOT:
sickrage.srConfig.WEB_ROOT = sickrage.srConfig.WEB_ROOT = "/" + sickrage.srConfig.WEB_ROOT.lstrip(
"/"
).strip("/")
# api root
if not sickrage.srConfig.API_KEY:
sickrage.srConfig.API_KEY = generateApiKey()
self.api_root = r"%s/api/%s" % (sickrage.srConfig.WEB_ROOT, sickrage.srConfig.API_KEY)
# tornado setup
if sickrage.srConfig.ENABLE_HTTPS:
# If either the HTTPS certificate or key do not exist, make some self-signed ones.
if not (sickrage.srConfig.HTTPS_CERT and os.path.exists(sickrage.srConfig.HTTPS_CERT)) or not (
sickrage.srConfig.HTTPS_KEY and os.path.exists(sickrage.srConfig.HTTPS_KEY)
):
if not create_https_certificates(sickrage.srConfig.HTTPS_CERT, sickrage.srConfig.HTTPS_KEY):
sickrage.srLogger.info("Unable to create CERT/KEY files, disabling HTTPS")
sickrage.srConfig.ENABLE_HTTPS = False
if not (os.path.exists(sickrage.srConfig.HTTPS_CERT) and os.path.exists(sickrage.srConfig.HTTPS_KEY)):
sickrage.srLogger.warning("Disabled HTTPS because of missing CERT and KEY files")
sickrage.srConfig.ENABLE_HTTPS = False
# Load the app
self.app = Application(
[],
debug=sickrage.srConfig.DEBUG,
autoreload=False,
gzip=sickrage.srConfig.WEB_USE_GZIP,
xheaders=sickrage.srConfig.HANDLE_REVERSE_PROXY,
cookie_secret=sickrage.srConfig.WEB_COOKIE_SECRET,
login_url="%s/login/" % sickrage.srConfig.WEB_ROOT,
)
# Main Handlers
self.app.add_handlers(
".*$",
[
# webapi handler
(r"%s(/?.*)" % self.api_root, ApiHandler),
# webapi key retrieval
(r"%s/getkey(/?.*)" % sickrage.srConfig.WEB_ROOT, KeyHandler),
# webapi builder redirect
(
r"%s/api/builder" % sickrage.srConfig.WEB_ROOT,
RedirectHandler,
{"url": sickrage.srConfig.WEB_ROOT + "/apibuilder/"},
),
# webui login/logout handlers
(r"%s/login(/?)" % sickrage.srConfig.WEB_ROOT, LoginHandler),
(r"%s/logout(/?)" % sickrage.srConfig.WEB_ROOT, LogoutHandler),
# webui handlers
]
+ Route.get_routes(sickrage.srConfig.WEB_ROOT),
)
# Web calendar handler (Needed because option Unprotected calendar)
self.app.add_handlers(".*$", [(r"%s/calendar" % sickrage.srConfig.WEB_ROOT, CalendarHandler)])
# Static File Handlers
self.app.add_handlers(
".*$",
[
# favicon
(
r"%s/(favicon\.ico)" % sickrage.srConfig.WEB_ROOT,
StaticFileHandler,
{"path": os.path.join(sickrage.srConfig.GUI_DIR, "images/ico/favicon.ico")},
),
# images
(
r"%s.*?/images/(.*)" % sickrage.srConfig.WEB_ROOT,
StaticImageHandler,
{"path": os.path.join(sickrage.srConfig.GUI_DIR, "images")},
),
# css
(
r"%s/css/(.*)" % sickrage.srConfig.WEB_ROOT,
StaticFileHandler,
{"path": os.path.join(sickrage.srConfig.GUI_DIR, "css")},
),
#.........这里部分代码省略.........
示例12: AppWebServer
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
class AppWebServer(threading.Thread):
def __init__(self, options=None):
threading.Thread.__init__(self)
self.daemon = True
self.alive = True
self.name = 'TORNADO'
self.options = options or {}
self.options.setdefault('port', 8081)
self.options.setdefault('host', '0.0.0.0')
self.options.setdefault('log_dir', None)
self.options.setdefault('username', '')
self.options.setdefault('password', '')
self.options.setdefault('web_root', '/')
assert isinstance(self.options['port'], int)
assert 'data_root' in self.options
self.server = None
self.io_loop = None
# video root
if app.ROOT_DIRS:
root_dirs = app.ROOT_DIRS
self.video_root = root_dirs[int(root_dirs[0]) + 1]
else:
self.video_root = None
# web root
if self.options['web_root']:
app.WEB_ROOT = self.options['web_root'] = clean_url_path(self.options['web_root'])
# Configure root to selected theme.
app.WEB_ROOT = self.options['theme_path'] = clean_url_path(app.WEB_ROOT)
# Configure the directory to the theme's data root.
app.THEME_DATA_ROOT = self.options['theme_data_root'] = os.path.join(self.options['data_root'], app.THEME_NAME)
# api root
if not app.API_KEY:
app.API_KEY = generate_api_key()
self.options['api_root'] = r'{root}/api/(?:v1/)?{key}'.format(root=app.WEB_ROOT, key=app.API_KEY)
self.options['api_v2_root'] = r'{root}/api/v2'.format(root=app.WEB_ROOT)
# websocket root
self.options['web_socket'] = r'{root}/ws'.format(root=app.WEB_ROOT)
# tornado setup
self.enable_https = self.options['enable_https']
self.https_cert = self.options['https_cert']
self.https_key = self.options['https_key']
if self.enable_https:
# If either the HTTPS certificate or key do not exist, make some self-signed ones.
if not (self.https_cert and os.path.exists(self.https_cert)) or not (
self.https_key and os.path.exists(self.https_key)):
if not create_https_certificates(self.https_cert, self.https_key):
log.info('Unable to create CERT/KEY files, disabling HTTPS')
app.ENABLE_HTTPS = False
self.enable_https = False
if not (os.path.exists(self.https_cert) and os.path.exists(self.https_key)):
log.warning('Disabled HTTPS because of missing CERT and KEY files')
app.ENABLE_HTTPS = False
self.enable_https = False
# Load the app
self.app = Application(
[],
debug=True,
autoreload=False,
gzip=app.WEB_USE_GZIP,
xheaders=app.HANDLE_REVERSE_PROXY,
cookie_secret=app.WEB_COOKIE_SECRET,
login_url=r'{root}/login/'.format(root=self.options['theme_path']),
log_function=self.log_request,
)
self.app.add_handlers('.*$', get_apiv2_handlers(self.options['api_v2_root']))
# Websocket handler
self.app.add_handlers('.*$', [
(r'{base}/ui(/?.*)'.format(base=self.options['web_socket']), WebSocketUIHandler)
])
# Static File Handlers
self.app.add_handlers('.*$', [
# favicon
(r'{base}/favicon\.ico()'.format(base=self.options['theme_path']), StaticFileHandler,
{'path': os.path.join(self.options['theme_data_root'], 'assets', 'img', 'ico', 'favicon.ico')}),
# images
(r'{base}/images/(.*)'.format(base=self.options['theme_path']), StaticFileHandler,
{'path': os.path.join(self.options['theme_data_root'], 'assets', 'img')}),
# cached images
(r'{base}/cache/images/(.*)'.format(base=self.options['theme_path']), StaticFileHandler,
{'path': os.path.join(app.CACHE_DIR, 'images')}),
# css
(r'{base}/css/(.*)'.format(base=self.options['theme_path']), StaticFileHandler,
#.........这里部分代码省略.........
示例13: SRWebServer
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
class SRWebServer(object):
def __init__(self, **kwargs):
self.running = True
self.restart = False
self.io_loop = IOLoop.instance()
self.options = {}
self.options.setdefault('port', 8081)
self.options.setdefault('host', '0.0.0.0')
self.options.setdefault('log_dir', None)
self.options.setdefault('username', '')
self.options.setdefault('password', '')
self.options.setdefault('web_root', '/')
self.options.setdefault('stop_timeout', 3)
self.options.update(kwargs)
# video root
if sickrage.ROOT_DIRS:
root_dirs = sickrage.ROOT_DIRS.split('|')
self.video_root = root_dirs[int(root_dirs[0]) + 1]
else:
self.video_root = None
# web root
if self.options[b'web_root']:
sickrage.WEB_ROOT = self.options[b'web_root'] = ('/' + self.options[b'web_root'].lstrip('/').strip('/'))
# api root
if not sickrage.API_KEY:
sickrage.API_KEY = generateApiKey()
self.options[b'api_root'] = r'%s/api/%s' % (sickrage.WEB_ROOT, sickrage.API_KEY)
# tornado setup
self.enable_https = self.options[b'enable_https']
self.https_cert = self.options[b'https_cert']
self.https_key = self.options[b'https_key']
if self.enable_https:
# If either the HTTPS certificate or key do not exist, make some self-signed ones.
if not (self.https_cert and os.path.exists(self.https_cert)) or not (
self.https_key and os.path.exists(self.https_key)):
if not create_https_certificates(self.https_cert, self.https_key):
sickrage.LOGGER.info("Unable to create CERT/KEY files, disabling HTTPS")
sickrage.ENABLE_HTTPS = False
self.enable_https = False
if not (os.path.exists(self.https_cert) and os.path.exists(self.https_key)):
sickrage.LOGGER.warning("Disabled HTTPS because of missing CERT and KEY files")
sickrage.ENABLE_HTTPS = False
self.enable_https = False
# Load the app
self.app = Application([],
debug=sickrage.DEBUG,
autoreload=False,
gzip=sickrage.WEB_USE_GZIP,
xheaders=sickrage.HANDLE_REVERSE_PROXY,
cookie_secret=sickrage.WEB_COOKIE_SECRET,
login_url='%s/login/' % self.options[b'web_root'],
)
# Main Handlers
self.app.add_handlers('.*$', [
# webapi handler
(r'%s(/?.*)' % self.options[b'api_root'], ApiHandler),
# webapi key retrieval
(r'%s/getkey(/?.*)' % self.options[b'web_root'], KeyHandler),
# webapi builder redirect
(r'%s/api/builder' % self.options[b'web_root'], RedirectHandler,
{"url": self.options[b'web_root'] + '/apibuilder/'}),
# webui login/logout handlers
(r'%s/login(/?)' % self.options[b'web_root'], LoginHandler),
(r'%s/logout(/?)' % self.options[b'web_root'], LogoutHandler),
# webui handlers
] + route.get_routes(self.options[b'web_root']))
# Web calendar handler (Needed because option Unprotected calendar)
self.app.add_handlers('.*$', [
(r'%s/calendar' % self.options[b'web_root'], CalendarHandler),
])
# Static File Handlers
self.app.add_handlers(".*$", [
# favicon
(r'%s/(favicon\.ico)' % self.options[b'web_root'], StaticFileHandler,
{"path": os.path.join(self.options[b'gui_root'], 'images/ico/favicon.ico')}),
# images
(r'%s.*?/images/(.*)' % self.options[b'web_root'], StaticImageHandler,
{"path": os.path.join(self.options[b'gui_root'], 'images')}),
# css
(r'%s/css/(.*)' % self.options[b'web_root'], StaticFileHandler,
{"path": os.path.join(self.options[b'gui_root'], 'css')}),
# javascript
#.........这里部分代码省略.........
示例14: HTTPD
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
class HTTPD(object): # noqa
"""
HTTP Server implementation that attaches to an event loop and socket, and
is capable of handling mesos wire protocol messages.
"""
def __init__(self, sock, loop):
"""
Construct an HTTP server on a socket given an ioloop.
"""
self.loop = loop
self.sock = sock
self.app = Application(handlers=[(r'/.*$', Blackhole)])
self.server = HTTPServer(self.app, io_loop=self.loop)
self.server.add_sockets([sock])
self.sock.listen(1024)
def terminate(self):
log.info('Terminating HTTP server and all connections')
self.server.close_all_connections()
self.sock.close()
def mount_process(self, process):
"""
Mount a Process onto the http server to receive message callbacks.
"""
for route_path in process.route_paths:
route = '/%s%s' % (process.pid.id, route_path)
log.info('Mounting route %s' % route)
self.app.add_handlers('.*$', [(
re.escape(route),
RoutedRequestHandler,
dict(process=process, path=route_path)
)])
for message_name in process.message_names:
route = '/%s/%s' % (process.pid.id, message_name)
log.info('Mounting message handler %s' % route)
self.app.add_handlers('.*$', [(
re.escape(route),
WireProtocolMessageHandler,
dict(process=process, name=message_name)
)])
def unmount_process(self, process):
"""
Unmount a process from the http server to stop receiving message
callbacks.
"""
# There is no remove_handlers, but .handlers is public so why not. server.handlers is a list of
# 2-tuples of the form (host_pattern, [list of RequestHandler]) objects. We filter out all
# handlers matching our process from the RequestHandler list for each host pattern.
def nonmatching(handler):
return 'process' not in handler.kwargs or handler.kwargs['process'] != process
def filter_handlers(handlers):
host_pattern, handlers = handlers
return (host_pattern, list(filter(nonmatching, handlers)))
self.app.handlers = [filter_handlers(handlers) for handlers in self.app.handlers]
示例15: WebServer
# 需要导入模块: from tornado.web import Application [as 别名]
# 或者: from tornado.web.Application import add_handlers [as 别名]
class WebServer(threading.Thread):
def __init__(self, options=None):
threading.Thread.__init__(self)
self.daemon = True
self.alive = True
self.name = 'TORNADO'
self.io_loop = None
self.server = None
self.options = options or {}
self.options.setdefault('port', 8081)
self.options.setdefault('host', '0.0.0.0')
self.options.setdefault('log_dir', None)
self.options.setdefault('username', '')
self.options.setdefault('password', '')
self.options.setdefault('web_root', None)
assert isinstance(self.options['port'], int)
assert 'data_root' in self.options
# web root
self.options['web_root'] = ('/' + self.options['web_root'].lstrip('/')) if self.options['web_root'] else ''
# tornado setup
self.enable_https = self.options['enable_https']
self.https_cert = self.options['https_cert']
self.https_key = self.options['https_key']
if self.enable_https:
make_cert = False
update_cfg = False
for (attr, ext) in [('https_cert', '.crt'), ('https_key', '.key')]:
ssl_path = getattr(self, attr, None)
if ssl_path and not os.path.isfile(ssl_path):
if not ssl_path.endswith(ext):
setattr(self, attr, os.path.join(ssl_path, 'server%s' % ext))
setattr(sickbeard, attr.upper(), 'server%s' % ext)
make_cert = True
# If either the HTTPS certificate or key do not exist, make some self-signed ones.
if make_cert:
if not create_https_certificates(self.https_cert, self.https_key):
logger.log(u'Unable to create CERT/KEY files, disabling HTTPS')
update_cfg |= False is not sickbeard.ENABLE_HTTPS
sickbeard.ENABLE_HTTPS = False
self.enable_https = False
else:
update_cfg = True
if not (os.path.isfile(self.https_cert) and os.path.isfile(self.https_key)):
logger.log(u'Disabled HTTPS because of missing CERT and KEY files', logger.WARNING)
update_cfg |= False is not sickbeard.ENABLE_HTTPS
sickbeard.ENABLE_HTTPS = False
self.enable_https = False
if update_cfg:
sickbeard.save_config()
# Load the app
self.app = Application([],
debug=True,
serve_traceback=True,
autoreload=False,
compress_response=True,
cookie_secret=sickbeard.COOKIE_SECRET,
xsrf_cookies=True,
login_url='%s/login/' % self.options['web_root'])
re_host_pattern = re_valid_hostname()
# webui login/logout handlers
self.app.add_handlers(re_host_pattern, [
(r'%s/login(/?)' % self.options['web_root'], webserve.LoginHandler),
(r'%s/logout(/?)' % self.options['web_root'], webserve.LogoutHandler),
])
# Web calendar handler (Needed because option Unprotected calendar)
self.app.add_handlers(re_host_pattern, [
(r'%s/calendar' % self.options['web_root'], webserve.CalendarHandler),
])
# Static File Handlers
self.app.add_handlers(re_host_pattern, [
# favicon
(r'%s/(favicon\.ico)' % self.options['web_root'], webserve.BaseStaticFileHandler,
{'path': os.path.join(self.options['data_root'], 'images/ico/favicon.ico')}),
# images
(r'%s/images/(.*)' % self.options['web_root'], webserve.BaseStaticFileHandler,
{'path': os.path.join(self.options['data_root'], 'images')}),
# cached images
(r'%s/cache/images/(.*)' % self.options['web_root'], webserve.BaseStaticFileHandler,
{'path': os.path.join(sickbeard.CACHE_DIR, 'images')}),
# css
(r'%s/css/(.*)' % self.options['web_root'], webserve.BaseStaticFileHandler,
{'path': os.path.join(self.options['data_root'], 'css')}),
# javascript
(r'%s/js/(.*)' % self.options['web_root'], webserve.BaseStaticFileHandler,
#.........这里部分代码省略.........