Beispiel #1
0
    def init(self,
             server_dir: str,
             use_http_server: bool = False,
             config: Dict = None,
             **kwargs) -> None:
        self.root_dir = join_to_abs_path(server_dir)
        self.config_path = join_to_abs_path(server_dir,
                                            Hostray_Web_Config_File)

        if config:
            self.config = config
            self.config_path = None
        else:
            with open(self.config_path, 'r') as f:
                import yaml
                from .config_validator import HostrayWebConfigValidator
                validator = HostrayWebConfigValidator(
                    yaml.load(f, Loader=yaml.SafeLoader))
                self.config = validator.parameter

        self._make_app()

        if use_http_server or 'ssl' in self.config:
            from tornado.web import HTTPServer

            if 'ssl' in self.config:
                if not os.path.isfile(join_path(self.config['ssl']['crt'])):
                    raise HostrayWebException(
                        LocalCode_File_Not_Found,
                        join_path(self.config['ssl']['crt']))
                if not os.path.isfile(join_path(self.config['ssl']['key'])):
                    raise HostrayWebException(
                        LocalCode_File_Not_Found,
                        join_path(self.config['ssl']['key']))

                import ssl
                ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
                ssl_ctx.load_cert_chain(join_path(self.config['ssl']['crt']),
                                        join_path(self.config['ssl']['key']))
                if 'ca' in self.config['ssl']:
                    if not os.path.isfile(join_path(self.config['ssl']['ca'])):
                        raise HostrayWebException(
                            LocalCode_File_Not_Found,
                            join_path(self.config['ssl']['ca']))
                    ssl_ctx.load_verify_locations(
                        join_path(self.config['ssl']['ca']))

                self.server = HTTPServer(self.app, ssl_options=ssl_ctx)
            else:
                self.server = HTTPServer(self.app)

            self.server.listen(self.config['port'])
        else:
            self.app.listen(self.config['port'])
Beispiel #2
0
def main():
    # 接卸命令行 参数
    tornado.options.parse_command_line()
    if settings.get('debug') != True:
        options.log_file_prefix = config.log_file_prefix
        options.logging = config.log_level
    """服务器启动文件"""
    app = Application(urls, **settings)
    http_server = HTTPServer(app)
    http_server.listen(options['port'])
    IOLoop.current().start()
Beispiel #3
0
def run_server(app: Application, port: int):  # pragma: no cover
    sockets = bind_sockets(port, "localhost")
    server = HTTPServer(app)
    server.add_sockets(sockets)

    _, socket_port = sockets[0].getsockname()
    local_url = f"http://localhost:{socket_port}"
    log.info(f"Installer page ready on {local_url}")

    if not DEBUG:
        log.info("Should open automatically in browser...")
        recover_ld_library_env_path()
        webbrowser.open_new(local_url)

    tornado.ioloop.IOLoop.current().start()
Beispiel #4
0
                CostEstimationAPIHandler,
                name="api-cost-detail"),
            url(r"/api/configurations",
                ConfigurationListAPIHandler,
                name="api-configuration-list"),
            url(
                r"/api/configuration/(.*)",
                ConfigurationItemAPIHandler,
                name="api-configuration-detail",
            ),
        ],
        debug=DEBUG,
        static_path=os.path.join(RESOURCE_FOLDER_PATH, "static"),
        template_path=os.path.join(RESOURCE_FOLDER_PATH, "templates"),
    )

    sockets = bind_sockets((sum(ord(c)
                                for c in "RAIDEN_WIZARD") + 1000) % 2**16 - 1)
    server = HTTPServer(app)
    server.add_sockets(sockets)

    _, port = sockets[0].getsockname()
    local_url = f"http://localhost:{port}"
    log.info(f"Installer page ready on {local_url}")

    if not DEBUG:
        log.info("Should open automatically in browser...")
        webbrowser.open_new(local_url)

    tornado.ioloop.IOLoop.current().start()
Beispiel #5
0
    def post(self, *args, **kwargs):
        pass


#创建application对象:进行若干个对服务器的设置
#eg:路由列表、模板路径、静态资源...


class PythonHandler(RequestHandler):
    def get(self, *args, **kwargs):
        self.write("hello python")

    def post(self, *args, **kwargs):
        pass


app = Application([('/', IndexHandler),
                   ('/java', JavaHandler, {
                       'greeting': 'xxx',
                       'info': '家洼'
                   }), ('/Python', PythonHandler)])
#创建服务器
server = HTTPServer(app)
#监听端口(端口号10000以上)
server.listen(options.port)
#打印获得的数据库参数
print('数据库参数:', options.db)
#启动服务器
IOLoop.current().start()
Beispiel #6
0
import os
import ssl

from tornado.web import Application, RequestHandler, HTTPServer
from tornado.ioloop import IOLoop

ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain("server.pem", "server.key")


class HelloHandler(RequestHandler):
    def get(self):
        self.write({'message': 'hello world'})


def make_app():
    urls = [("/", HelloHandler)]
    return Application(urls)


if __name__ == '__main__':
    app = make_app()
    http = HTTPServer(app, ssl_options=ssl_ctx)
    http.listen(3000)
    IOLoop.instance().start()
Beispiel #7
0
class HostrayServer():
    def start(self):
        from tornado.ioloop import IOLoop, PeriodicCallback
        PeriodicCallback(self.app.do_exit, 1000).start()
        IOLoop.current().start()

    def stop(self):
        if self.app:
            self.app.exit()

    def start_periodic_callback(self,
                                awaitable_func: Awaitable,
                                *args,
                                interval: int = 1000,
                                **kwargs) -> None:
        from tornado.ioloop import PeriodicCallback
        from inspect import iscoroutinefunction
        if iscoroutinefunction(awaitable_func):
            PeriodicCallback(
                lambda: self.__periodic_callback_decorator(
                    awaitable_func, *args, **kwargs), interval).start()

    async def __periodic_callback_decorator(self, func, *args, **kwargs):
        if not self.app.exiting:
            await func(*args, **kwargs)

    def init(self,
             server_dir: str,
             use_http_server: bool = False,
             config: Dict = None,
             **kwargs) -> None:
        self.root_dir = join_to_abs_path(server_dir)
        self.config_path = join_to_abs_path(server_dir,
                                            Hostray_Web_Config_File)

        if config:
            self.config = config
            self.config_path = None
        else:
            with open(self.config_path, 'r') as f:
                import yaml
                from .config_validator import HostrayWebConfigValidator
                validator = HostrayWebConfigValidator(
                    yaml.load(f, Loader=yaml.SafeLoader))
                self.config = validator.parameter

        self._make_app()

        if use_http_server or 'ssl' in self.config:
            from tornado.web import HTTPServer

            if 'ssl' in self.config:
                if not os.path.isfile(join_path(self.config['ssl']['crt'])):
                    raise HostrayWebException(
                        LocalCode_File_Not_Found,
                        join_path(self.config['ssl']['crt']))
                if not os.path.isfile(join_path(self.config['ssl']['key'])):
                    raise HostrayWebException(
                        LocalCode_File_Not_Found,
                        join_path(self.config['ssl']['key']))

                import ssl
                ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
                ssl_ctx.load_cert_chain(join_path(self.config['ssl']['crt']),
                                        join_path(self.config['ssl']['key']))
                if 'ca' in self.config['ssl']:
                    if not os.path.isfile(join_path(self.config['ssl']['ca'])):
                        raise HostrayWebException(
                            LocalCode_File_Not_Found,
                            join_path(self.config['ssl']['ca']))
                    ssl_ctx.load_verify_locations(
                        join_path(self.config['ssl']['ca']))

                self.server = HTTPServer(self.app, ssl_options=ssl_ctx)
            else:
                self.server = HTTPServer(self.app)

            self.server.listen(self.config['port'])
        else:
            self.app.listen(self.config['port'])

    def _make_app(self):
        settings = {
            'root_dir': self.root_dir,
            'config_path': self.config_path,
            **self.config
        }

        controllers, settings = get_controllers(settings, self.root_dir)
        self.app = self._make_app_instance(controllers, settings)
        self.app.init()

    def _make_app_instance(self, controllers, settings):
        return HostrayApplication(controllers, **settings)
Beispiel #8
0
def get_app():
    import uuid
    settings = {
        "cookie_secret": "__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__"
    }
    return Application([(r"/auth", Auth), (r"/log/(.*)", FileReader),
                        (r"/servers/(.*)", ServerList)], **settings)


# Press the green button in the gutter to run the script.
if __name__ == '__main__':

    config = get_config()
    from tornado.web import HTTPServer
    import platform

    from tornado.ioloop import IOLoop
    server = HTTPServer(get_app())
    server.bind(config['SERVER_PORT'])
    server.start()
    if platform.system() == "Windows":
        IOLoop.current().start()
    else:
        import uvloop
        from tornado.platform.asyncio import AsyncIOMainLoop
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
        AsyncIOMainLoop().install()
        asyncio.get_event_loop().run_forever()

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
Beispiel #9
0
#tornado基本功能演示

#ALT+ENTER
import tornado
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
from tornado.web import HTTPServer


#路由的判断 :用来响应用户请求
class IndexHandler(RequestHandler):
    def get(self, *args, **kwargs):
        self.write("hello aid1710")

    def post(self, *args, **kwargs):
        pass


#创建application对象:进行若干个对服务器的设置
#eg:路由列表、模板路径、静态资源...
app = Application([('/', IndexHandler)])
#创建服务器
server = HTTPServer(app)
#监听端口(端口号10000以上)
server.listen(8888)
#启动服务器
IOLoop.current().start()