Beispiel #1
0
def gevent_run(app, address, port, debugger=False, reloader=False):
    from gevent.wsgi import WSGIServer
    from werkzeug.debug import DebuggedApplication
    import gevent.monkey
    gevent.monkey.patch_all()

    run_app = app
    if debugger:
        run_app = DebuggedApplication(app)

    def run_server():
        import logging
        from gevent import version_info

        logger = logging.getLogger('pydirl')
        logger.info('Listening on http://{}:{}/'.format(address, port))
        server_params = dict()
        # starting from gevent version 1.1b1 we can pass custom logger to gevent
        if version_info[:2] >= (1, 1):
            server_params['log'] = logger
        http_server = WSGIServer((address, port), run_app, **server_params)
        http_server.serve_forever()

    if reloader:
        from werkzeug._reloader import run_with_reloader
        run_with_reloader(run_server)
    else:
        run_server()
Beispiel #2
0
def run():
    import argparse

    parser = argparse.ArgumentParser(description='Phovea Server')
    parser.add_argument('--use_reloader',
                        action='store_true',
                        help='whether to automatically reload the server')
    parser.add_argument('--env',
                        default=cc.get('env'),
                        help='environment mode (dev or prod)')

    # parse before to enable correct plugin discovery
    args = parser.parse_known_args()[0]
    if args.env.startswith('dev'):
        enable_dev_mode()
    else:
        enable_prod_mode()

    default_command = _resolve_commands(parser)
    if default_command is not None:
        set_default_subparser(parser, default_command)

    args = parser.parse_args()

    _set_runtime_infos(args)
    main = args.launcher(args)

    if args.use_reloader:
        _log.info('start using reloader...')
        from werkzeug._reloader import run_with_reloader
        run_with_reloader(main, extra_files=_config_files())
    else:
        _log.info('start...')
        main()
Beispiel #3
0
def gevent_run(app):
    from gevent.wsgi import WSGIServer
    import gevent.monkey
    from werkzeug.debug import DebuggedApplication
    gevent.monkey.patch_socket()
    run_app = app
    if app.config['DEBUG']:
        run_app = DebuggedApplication(app)

    def run_server():
        from gevent import version_info

        logger = app._logger
        port = int(app.config.get('PORT', 5000))
        address = app.config.get('ADDRESS', '')
        logger.info('Listening on http://{}:{}/'.format(address or '0.0.0.0', port))
        server_params = dict()
        #starting from gevent version 1.1b1 we can pass custom logger to gevent
        if version_info[:2] >= (1,1):
            server_params['log'] = logger
        http_server = WSGIServer((address, port), run_app, **server_params)
        http_server.serve_forever()

    if app.config['DEBUG']:
        from werkzeug._reloader import run_with_reloader
        run_with_reloader(run_server)
    else:
        run_server()
Beispiel #4
0
def gevent_run(app, address, port, debugger=False, reloader=False):
    from gevent.wsgi import WSGIServer
    from werkzeug.debug import DebuggedApplication
    import gevent.monkey
    gevent.monkey.patch_all()

    run_app = app
    if debugger:
        run_app = DebuggedApplication(app)

    def run_server():
        import logging
        from gevent import version_info

        logger = logging.getLogger('pydirl')
        logger.info('Listening on http://{}:{}/'.format(address, port))
        server_params = dict()
        # starting from gevent version 1.1b1 we can pass custom logger to gevent
        if version_info[:2] >= (1, 1):
            server_params['log'] = logger
        http_server = WSGIServer((address, port), run_app, **server_params)
        http_server.serve_forever()

    if reloader:
        from werkzeug._reloader import run_with_reloader
        run_with_reloader(run_server)
    else:
        run_server()
Beispiel #5
0
def run_simple(
    hostname,
    port,
    application,
    use_reloader=False,
    use_debugger=False,
    use_evalex=True,
    extra_files=None,
    reloader_interval=1,
    reloader_type="auto",
    threaded=False,
    processes=1,
    request_handler=None,
    static_files=None,
    passthrough_errors=False,
    ssl_context=None,
):
    if use_debugger:
        from werkzeug.debug import DebuggedApplication

        application = DebuggedApplication(application, use_evalex)
    if static_files:
        from werkzeug.wsgi import SharedDataMiddleware

        application = SharedDataMiddleware(application, static_files)

    def inner():
        # Override here
        make_server(
            hostname, port, application, threaded, processes, request_handler, passthrough_errors, ssl_context
        ).serve_forever()

    if os.environ.get("WERKZEUG_RUN_MAIN") != "true":
        display_hostname = hostname != "*" and hostname or "localhost"
        if ":" in display_hostname:
            display_hostname = "[%s]" % display_hostname
        quit_msg = "(Press CTRL+C to quit)"
        _log(
            "info",
            " * Running on %s://%s:%d/ %s",
            ssl_context is None and "http" or "https",
            display_hostname,
            port,
            quit_msg,
        )
    if use_reloader:
        # Create and destroy a socket so that any exceptions are raised before
        # we spawn a separate Python interpreter and lose this ability.
        address_family = select_ip_version(hostname, port)
        test_socket = socket.socket(address_family, socket.SOCK_STREAM)
        test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        test_socket.bind((hostname, port))
        test_socket.close()

        from werkzeug._reloader import run_with_reloader

        run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
    else:
        inner()
Beispiel #6
0
def serve(address="0.0.0.0", port=8000, config=configfile, source='default'):
    from werkzeug._reloader import run_with_reloader
    from werkzeug.serving import run_simple
    from threading import Thread

    def inner():
        cfg = load_config(config, source)
        Thread(target=lambda: watch(cfg), daemon=True).start()
        run_simple(address, port, cfg.application, use_debugger=True)

    run_with_reloader(inner)
Beispiel #7
0
def main():
    # Command-line entry point for setup.py install/develop
    command = get_command()
    shell = get_shell()
    files = get_files()

    run_with_reloader(
        lambda: subprocess.call(
            command,
            shell=True,
            executable=shell),
        extra_files=files)
Beispiel #8
0
def runserver(host, port, **kwargs):
    app = create_app(**kwargs)

    def serve():
        from paste.translogger import TransLogger
        wsgi = TransLogger(app.wsgi_app)
        waitress.serve(wsgi, host=host, port=port)

    if app.config.get('RELOADER'):
        from werkzeug._reloader import run_with_reloader
        run_with_reloader(serve)
    else:
        serve()
Beispiel #9
0
Datei: lfs.py Projekt: mgax/lfs
def runserver(host, port, **kwargs):
    app = create_app(**kwargs)

    def serve():
        from paste.translogger import TransLogger
        wsgi = TransLogger(app.wsgi_app)
        waitress.serve(wsgi, host=host, port=port)

    if app.config.get('RELOADER'):
        from werkzeug._reloader import run_with_reloader
        run_with_reloader(serve)
    else:
        serve()
Beispiel #10
0
def run(rpc_class, host='0.0.0.0', port=4242, autoreload=True):
    """
    Start a rpc server

    :param rpc_class: The rpc service module
    :param host: The host to bind to, for example ``'localhost'``
    :param port: The port for the server.  eg: ``4242``
    :param autoreload: should the server automatically restart the python process if modules were changed?
    """
    main_func = partial(run_server, rpc_class, host, port)
    if autoreload:
        run_with_reloader(main_func)
    else:
        main_func()
Beispiel #11
0
def run_simple(hostname,
               port,
               application,
               use_reloader=False,
               use_debugger=False,
               use_evalex=True,
               extra_files=None,
               reloader_interval=1,
               reloader_type='auto',
               threaded=False,
               processes=1,
               request_handler=None,
               static_files=None,
               passthrough_errors=False,
               ssl_context=None):
    if use_debugger:
        from werkzeug.debug import DebuggedApplication
        application = DebuggedApplication(application, use_evalex)
    if static_files:
        from werkzeug.wsgi import SharedDataMiddleware
        application = SharedDataMiddleware(application, static_files)

    def inner():
        # Override here
        make_server(hostname, port, application, threaded, processes,
                    request_handler, passthrough_errors,
                    ssl_context).serve_forever()

    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        display_hostname = hostname != '*' and hostname or 'localhost'
        if ':' in display_hostname:
            display_hostname = '[%s]' % display_hostname
        quit_msg = '(Press CTRL+C to quit)'
        _log('info', ' * Running on %s://%s:%d/ %s',
             ssl_context is None and 'http' or 'https', display_hostname, port,
             quit_msg)
    if use_reloader:
        # Create and destroy a socket so that any exceptions are raised before
        # we spawn a separate Python interpreter and lose this ability.
        address_family = select_ip_version(hostname, port)
        test_socket = socket.socket(address_family, socket.SOCK_STREAM)
        test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        test_socket.bind((hostname, port))
        test_socket.close()

        from werkzeug._reloader import run_with_reloader
        run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
    else:
        inner()
Beispiel #12
0
def main():
    parser = configargparse.ArgumentParser("mediaTUM start.py")

    parser.add_argument("-b", "--bind", default=None, help="hostname / IP to bind to, default: see config file")

    parser.add_argument("-p", "--http_port", default=None, help="HTTP port to use, default: see config file")

    parser.add_argument("-r", "--reload", action="store_true", default=False,
                        help="reload when code or config file changes, default false")

    parser.add_argument("-s", "--stackdump", action="store_true", default=True,
                        help="write stackdumps to temp dir {} on SIGQUIT, default true".format(SYSTEM_TMP_DIR))

    parser.add_argument("--force-test-db", action="store_true", default=False,
                        help="create / use database server with default database for testing (overrides configured db connection)")
    parser.add_argument("-l", "--loglevel", help="root loglevel, sensible values: DEBUG, INFO, WARN")
    parser.add_argument("-m", "--automigrate", action="store_true", default=False,
                        help="run automatic database schema upgrades on startup")
    parser.add_argument(
        "--redis-sessions",
        action="store_true",
        default=False,
        help="EXPERIMENTAL: save sessions to redis, making them persistent, requires redis-collections and a redis server on localhost!")

    args = parser.parse_args()
    print("start.py args:", args)

    def signal_handler_usr1(signum, stack):
        import utils.log
        utils.log.reopen_log(None, None)

    import signal
    signal.signal(signal.SIGUSR1, signal_handler_usr1)

    if args.stackdump:
        stackdump_setup()

    if args.reload:
        # don't use this in production!
        maybe_config_filepath = config.get_config_filepath()
        extra_files = [maybe_config_filepath] if maybe_config_filepath else []

        def main_wrapper():
            run(args.bind, args.http_port, args.redis_sessions, args.force_test_db, args.loglevel, args.automigrate)

        run_with_reloader(main_wrapper, extra_files)
    else:
        run(args.bind, args.http_port, args.redis_sessions, args.force_test_db, args.loglevel, args.automigrate)
Beispiel #13
0
def main():
    parser = configargparse.ArgumentParser("mediaTUM start.py")

    parser.add_argument("-b", "--bind", default=None, help="hostname / IP to bind to, default: see config file")

    parser.add_argument("-p", "--http_port", default=None, help="HTTP port to use, default: see config file")

    parser.add_argument("-r", "--reload", action="store_true", default=False,
                        help="reload when code or config file changes, default false")

    parser.add_argument("-s", "--stackdump", action="store_true", default=True,
                        help="write stackdumps to temp dir {} on SIGQUIT, default true".format(SYSTEM_TMP_DIR))

    parser.add_argument("--force-test-db", action="store_true", default=False,
                        help="create / use database server with default database for testing (overrides configured db connection)")
    parser.add_argument("-l", "--loglevel", help="root loglevel, sensible values: DEBUG, INFO, WARN")
    parser.add_argument("-m", "--automigrate", action="store_true", default=False,
                        help="run automatic database schema upgrades on startup")
    parser.add_argument(
        "--redis-sessions",
        action="store_true",
        default=False,
        help="EXPERIMENTAL: save sessions to redis, making them persistent, requires redis-collections and a redis server on localhost!")

    args = parser.parse_args()
    print("start.py args:", args)

    def signal_handler_usr1(signum, stack):
        import utils.log
        utils.log.reopen_log(None, None)

    import signal
    signal.signal(signal.SIGUSR1, signal_handler_usr1)

    if args.stackdump:
        stackdump_setup()

    if args.reload:
        # don't use this in production!
        maybe_config_filepath = config.get_config_filepath()
        extra_files = [maybe_config_filepath] if maybe_config_filepath else []

        def main_wrapper():
            run(args.bind, args.http_port, args.redis_sessions, args.force_test_db, args.loglevel, args.automigrate)

        run_with_reloader(main_wrapper, extra_files)
    else:
        run(args.bind, args.http_port, args.redis_sessions, args.force_test_db, args.loglevel, args.automigrate)
Beispiel #14
0
def runserver(host, port, **kwargs):
    """
    Runs the GitLFS Server (WIP)
    
    Arguments:
        host [str] -- the host for the server
        port [int] -- the port for the server
    """

    app = create_app(**kwargs)
    if app.config.get('HOST'):
        host = app.config.get('HOST')

    def serve():
        from paste.translogger import TransLogger
        wsgi = TransLogger(app.wsgi_app)
        waitress.serve(wsgi, host=host, port=port)

    if app.config.get('RELOADER'):
        from werkzeug._reloader import run_with_reloader
        run_with_reloader(serve)
    else:
        serve()
Beispiel #15
0
def cmd_run(host, port, debugger, use_reloader):
    """Run a development server.

    This is a replacement for the default "run" command from flask CLI.

    Will use WSGIServer and WebSocketHandler from gevent to properly
    handle websocket connections.

    Note that reloading uses an undocumented API from werkzeug, that
    might stop working in the future.

    Another option would be to use gunicorn, but keep in mind it only
    works on Unix-like systems::

        gunicorn -k flask_sockets.worker app.dev:app \
            --reload --bind localhost:5000
    """

    from werkzeug._reloader import run_with_reloader

    def _run_development_server():

        from gevent import pywsgi
        from geventwebsocket.handler import WebSocketHandler

        app = create_app()
        app.debug = debugger
        server = pywsgi.WSGIServer(
            (host, port), app, handler_class=WebSocketHandler, log=logger
        )
        server.serve_forever()

    if use_reloader:
        # WARNING: This is an undocumented API
        return run_with_reloader(_run_development_server)

    return _run_development_server()
Beispiel #16
0
def run_simple(hostname, port, application, use_reloader=False,
               use_debugger=False, use_evalex=True,
               extra_files=None, reloader_interval=1,
               reloader_type='auto', threaded=False,
               processes=1, request_handler=None, static_files=None,
               passthrough_errors=False, ssl_context=None):
    """Start a WSGI application. Optional features include a reloader,
    multithreading and fork support.

    This function has a command-line interface too::

        python -m werkzeug.serving --help

    .. versionadded:: 0.5
       `static_files` was added to simplify serving of static files as well
       as `passthrough_errors`.

    .. versionadded:: 0.6
       support for SSL was added.

    .. versionadded:: 0.8
       Added support for automatically loading a SSL context from certificate
       file and private key.

    .. versionadded:: 0.9
       Added command-line interface.

    .. versionadded:: 0.10
       Improved the reloader and added support for changing the backend
       through the `reloader_type` parameter.  See :ref:`reloader`
       for more information.

    .. versionchanged:: 0.15
        Bind to a Unix socket by passing a path that starts with
        ``unix://`` as the ``hostname``.

    :param hostname: The host to bind to, for example ``'localhost'``.
        If the value is a path that starts with ``unix://`` it will bind
        to a Unix socket instead of a TCP socket..
    :param port: The port for the server.  eg: ``8080``
    :param application: the WSGI application to execute
    :param use_reloader: should the server automatically restart the python
                         process if modules were changed?
    :param use_debugger: should the werkzeug debugging system be used?
    :param use_evalex: should the exception evaluation feature be enabled?
    :param extra_files: a list of files the reloader should watch
                        additionally to the modules.  For example configuration
                        files.
    :param reloader_interval: the interval for the reloader in seconds.
    :param reloader_type: the type of reloader to use.  The default is
                          auto detection.  Valid values are ``'stat'`` and
                          ``'watchdog'``. See :ref:`reloader` for more
                          information.
    :param threaded: should the process handle each request in a separate
                     thread?
    :param processes: if greater than 1 then handle each request in a new process
                      up to this maximum number of concurrent processes.
    :param request_handler: optional parameter that can be used to replace
                            the default one.  You can use this to replace it
                            with a different
                            :class:`~BaseHTTPServer.BaseHTTPRequestHandler`
                            subclass.
    :param static_files: a list or dict of paths for static files.  This works
                         exactly like :class:`SharedDataMiddleware`, it's actually
                         just wrapping the application in that middleware before
                         serving.
    :param passthrough_errors: set this to `True` to disable the error catching.
                               This means that the server will die on errors but
                               it can be useful to hook debuggers in (pdb etc.)
    :param ssl_context: an SSL context for the connection. Either an
                        :class:`ssl.SSLContext`, a tuple in the form
                        ``(cert_file, pkey_file)``, the string ``'adhoc'`` if
                        the server should automatically create one, or ``None``
                        to disable SSL (which is the default).
    """
    if not isinstance(port, int):
        raise TypeError('port must be an integer')
    if use_debugger:
        from werkzeug.debug import DebuggedApplication
        application = DebuggedApplication(application, use_evalex)
    if static_files:
        from werkzeug.wsgi import SharedDataMiddleware
        application = SharedDataMiddleware(application, static_files)

    def log_startup(sock):
        display_hostname = hostname not in ('', '*') and hostname or 'localhost'
        quit_msg = '(Press CTRL+C to quit)'
        if sock.family is socket.AF_UNIX:
            _log('info', ' * Running on %s %s', display_hostname, quit_msg)
        else:
            if ':' in display_hostname:
                display_hostname = '[%s]' % display_hostname
            port = sock.getsockname()[1]
            _log('info', ' * Running on %s://%s:%d/ %s',
                 ssl_context is None and 'http' or 'https',
                 display_hostname, port, quit_msg)

    def inner():
        try:
            fd = int(os.environ['WERKZEUG_SERVER_FD'])
        except (LookupError, ValueError):
            fd = None
        srv = make_server(hostname, port, application, threaded,
                          processes, request_handler,
                          passthrough_errors, ssl_context,
                          fd=fd)
        if fd is None:
            log_startup(srv.socket)
        srv.serve_forever()

    if use_reloader:
        # If we're not running already in the subprocess that is the
        # reloader we want to open up a socket early to make sure the
        # port is actually available.
        if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
            if port == 0 and not can_open_by_fd:
                raise ValueError('Cannot bind to a random port with enabled '
                                 'reloader if the Python interpreter does '
                                 'not support socket opening by fd.')

            # Create and destroy a socket so that any exceptions are
            # raised before we spawn a separate Python interpreter and
            # lose this ability.
            address_family = select_address_family(hostname, port)
            server_address = get_sockaddr(hostname, port, address_family)
            s = socket.socket(address_family, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind(server_address)
            if hasattr(s, 'set_inheritable'):
                s.set_inheritable(True)

            # If we can open the socket by file descriptor, then we can just
            # reuse this one and our socket will survive the restarts.
            if can_open_by_fd:
                os.environ['WERKZEUG_SERVER_FD'] = str(s.fileno())
                s.listen(LISTEN_QUEUE)
                log_startup(s)
            else:
                s.close()
                if address_family is socket.AF_UNIX:
                    _log('info', "Unlinking %s" % server_address)
                    os.unlink(server_address)

        # Do not use relative imports, otherwise "python -m werkzeug.serving"
        # breaks.
        from werkzeug._reloader import run_with_reloader
        run_with_reloader(inner, extra_files, reloader_interval,
                          reloader_type)
    else:
        inner()
Beispiel #17
0
        ]
        b = px + [
            ord(c)
            for c in '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklnm\n'
        ]
        # b = [0x31, 0x32, 0x33, 0x0A, 0x1D, 0x4C, 0xE0, 0x00, 0x31, 0x32, 0x33, 0x0A]
        b = bytes(px) + pt.get_data()[2:]
        for i in b:
            print(hex(i))
        p._raw(bytes(b))
        p.close()


def do_usb_test2():
    from escpos.printer import Usb
    # p = Usb(0x6868, 0x0500, in_ep=0x84, out_ep=0x3)
    # p = Usb(0x2207, 0x0011, in_ep=0x02, out_ep=0x01)
    # p._raw(b'\x1b\x42\x02\x01')
    # p.close()


if __name__ == '__main__':
    # do_table_test()
    do_all_test()
    # do_usb_test()
    # do_usb_test()
    exit()
    from werkzeug._reloader import run_with_reloader

    run_with_reloader(lambda: do_table_test())
Beispiel #18
0
def run_simple(hostname,
               port,
               application,
               use_reloader=False,
               use_debugger=False,
               use_evalex=True,
               extra_files=None,
               reloader_interval=1,
               reloader_type='auto',
               threaded=False,
               processes=1,
               request_handler=None,
               static_files=None,
               passthrough_errors=False,
               ssl_context=None):
    """Start a WSGI application. Optional features include a reloader,
    multithreading and fork support.

    This function has a command-line interface too::

        python -m werkzeug.serving --help

    .. versionadded:: 0.5
       `static_files` was added to simplify serving of static files as well
       as `passthrough_errors`.

    .. versionadded:: 0.6
       support for SSL was added.

    .. versionadded:: 0.8
       Added support for automatically loading a SSL context from certificate
       file and private key.

    .. versionadded:: 0.9
       Added command-line interface.

    .. versionadded:: 0.10
       Improved the reloader and added support for changing the backend
       through the `reloader_type` parameter.  See :ref:`reloader`
       for more information.

    :param hostname: The host for the application.  eg: ``'localhost'``
    :param port: The port for the server.  eg: ``8080``
    :param application: the WSGI application to execute
    :param use_reloader: should the server automatically restart the python
                         process if modules were changed?
    :param use_debugger: should the werkzeug debugging system be used?
    :param use_evalex: should the exception evaluation feature be enabled?
    :param extra_files: a list of files the reloader should watch
                        additionally to the modules.  For example configuration
                        files.
    :param reloader_interval: the interval for the reloader in seconds.
    :param reloader_type: the type of reloader to use.  The default is
                          auto detection.  Valid values are ``'stat'`` and
                          ``'watchdog'``. See :ref:`reloader` for more
                          information.
    :param threaded: should the process handle each request in a separate
                     thread?
    :param processes: if greater than 1 then handle each request in a new process
                      up to this maximum number of concurrent processes.
    :param request_handler: optional parameter that can be used to replace
                            the default one.  You can use this to replace it
                            with a different
                            :class:`~BaseHTTPServer.BaseHTTPRequestHandler`
                            subclass.
    :param static_files: a dict of paths for static files.  This works exactly
                         like :class:`SharedDataMiddleware`, it's actually
                         just wrapping the application in that middleware before
                         serving.
    :param passthrough_errors: set this to `True` to disable the error catching.
                               This means that the server will die on errors but
                               it can be useful to hook debuggers in (pdb etc.)
    :param ssl_context: an SSL context for the connection. Either an
                        :class:`ssl.SSLContext`, a tuple in the form
                        ``(cert_file, pkey_file)``, the string ``'adhoc'`` if
                        the server should automatically create one, or ``None``
                        to disable SSL (which is the default).
    """
    if use_debugger:
        from werkzeug.debug import DebuggedApplication
        application = DebuggedApplication(application, use_evalex)
    if static_files:
        from werkzeug.wsgi import SharedDataMiddleware
        application = SharedDataMiddleware(application, static_files)

    def log_startup(sock):
        display_hostname = hostname not in ('',
                                            '*') and hostname or 'localhost'
        if ':' in display_hostname:
            display_hostname = '[%s]' % display_hostname
        quit_msg = '(Press CTRL+C to quit)'
        port = sock.getsockname()[1]
        _log('info', ' * Running on %s://%s:%d/ %s',
             ssl_context is None and 'http' or 'https', display_hostname, port,
             quit_msg)

    def inner():
        try:
            fd = int(os.environ['WERKZEUG_SERVER_FD'])
        except (LookupError, ValueError):
            fd = None
        srv = make_server(hostname,
                          port,
                          application,
                          threaded,
                          processes,
                          request_handler,
                          passthrough_errors,
                          ssl_context,
                          fd=fd)
        if fd is None:
            log_startup(srv.socket)
        srv.serve_forever()

    if use_reloader:
        # If we're not running already in the subprocess that is the
        # reloader we want to open up a socket early to make sure the
        # port is actually available.
        if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
            if port == 0 and not can_open_by_fd:
                raise ValueError('Cannot bind to a random port with enabled '
                                 'reloader if the Python interpreter does '
                                 'not support socket opening by fd.')

            # Create and destroy a socket so that any exceptions are
            # raised before we spawn a separate Python interpreter and
            # lose this ability.
            address_family = select_ip_version(hostname, port)
            s = socket.socket(address_family, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind((hostname, port))
            if hasattr(s, 'set_inheritable'):
                s.set_inheritable(True)

            # If we can open the socket by file descriptor, then we can just
            # reuse this one and our socket will survive the restarts.
            if can_open_by_fd:
                os.environ['WERKZEUG_SERVER_FD'] = str(s.fileno())
                s.listen(LISTEN_QUEUE)
                log_startup(s)
            else:
                s.close()

        # Do not use relative imports, otherwise "python -m werkzeug.serving"
        # breaks.
        from werkzeug._reloader import run_with_reloader
        run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
    else:
        inner()
Beispiel #19
0
def wsgi(ctx, port, timeout, cdn, proxy_mode, admin_password,
        db_filter, ws, cron, cron_interval, server_wide_modules, dev):

    debug, config, params, logger = (
        ctx.obj['debug'],
        ctx.obj['config'],
        ctx.obj['params'],
        ctx.obj['logger']
    )

    # Patch odoo config, since we run with gevent
    # we do not need multiple workers, but Odoo needs
    # to be fooled.
    config['workers'] = 2
    config['dev_mode'] = ['all']
    config['admin_passwd'] = admin_password
    config['dbfilter'] = db_filter
    config['server_wide_modules'] = ','.join(server_wide_modules)
    # Odoo still uses a deprecated conf module for server_wide_modules
    import odoo.conf
    odoo.conf.server_wide_modules = server_wide_modules

    if ws:
        from odooku.services.websocket import WebSocketServer as Server
    else:
        from odooku.services.wsgi import WSGIServer as Server
    from odooku.services.wsgi import WSGIApplicationRulesWrapper
    from odooku.services.cron import CronRunner

    # Initialize newrelic_agent
    global newrelic_agent
    if newrelic_agent and any(key in os.environ for key in [
                'NEW_RELIC_LICENSE_KEY',
                'NEW_RELIC_CONFIG_FILE'
            ]):

        newrelic_agent.initialize()
    else:
        newrelic_agent = None

    # Keep track of custom config params
    params.TIMEOUT = timeout
    params.CDN_ENABLED = cdn
    params.WS_ENABLED = ws

    # Load wsgi rules
    rules = WSGIApplicationRulesWrapper.load()

    def serve():
        max_accept = config['db_maxconn']
        if cron:
            cron_runner = CronRunner()
            max_accept -= 1
            gevent.spawn(cron_runner.run_forever, interval=cron_interval)

        server = Server(
            port,
            max_accept=max_accept,
            proxy_mode=proxy_mode,
            rules=rules,
            newrelic_agent=newrelic_agent,
            timeout=timeout
        )

        server.serve_forever()

    if dev:
        logger.warning("Running in development mode")
        run_with_reloader(serve)
    else:
        serve()
Beispiel #20
0
def run_with_reloader(*args, **kwargs):
    # People keep using undocumented APIs.  Do not use this function
    # please, we do not guarantee that it continues working.
    from werkzeug._reloader import run_with_reloader
    return run_with_reloader(*args, **kwargs)
Beispiel #21
0
    def run(self, app, host=None, port=None, **kwargs):  # pragma: no cover
        """Run the SocketIO web server.

        :param app: The Flask application instance.
        :param host: The hostname or IP address for the server to listen on.
                     Defaults to 127.0.0.1.
        :param port: The port number for the server to listen on. Defaults to
                     5000.
        :param debug: ``True`` to start the server in debug mode, ``False`` to
                      start in normal mode.
        :param use_reloader: ``True`` to enable the Flask reloader, ``False``
                             to disable it.
        :param reloader_options: A dictionary with options that are passed to
                                 the Flask reloader, such as ``extra_files``,
                                 ``reloader_type``, etc.
        :param extra_files: A list of additional files that the Flask
                            reloader should watch. Defaults to ``None``.
                            Deprecated, use ``reloader_options`` instead.
        :param log_output: If ``True``, the server logs all incoming
                           connections. If ``False`` logging is disabled.
                           Defaults to ``True`` in debug mode, ``False``
                           in normal mode. Unused when the threading async
                           mode is used.
        :param kwargs: Additional web server options. The web server options
                       are specific to the server used in each of the supported
                       async modes. Note that options provided here will
                       not be seen when using an external web server such
                       as gunicorn, since this method is not called in that
                       case.
        """
        if host is None:
            host = '127.0.0.1'
        if port is None:
            server_name = app.config['SERVER_NAME']
            if server_name and ':' in server_name:
                port = int(server_name.rsplit(':', 1)[1])
            else:
                port = 5000

        debug = kwargs.pop('debug', app.debug)
        log_output = kwargs.pop('log_output', debug)
        use_reloader = kwargs.pop('use_reloader', debug)
        extra_files = kwargs.pop('extra_files', None)
        reloader_options = kwargs.pop('reloader_options', {})
        if extra_files:
            reloader_options['extra_files'] = extra_files

        app.debug = debug
        if app.debug and self.server.eio.async_mode != 'threading':
            # put the debug middleware between the SocketIO middleware
            # and the Flask application instance
            #
            #    mw1   mw2   mw3   Flask app
            #     o ---- o ---- o ---- o
            #    /
            #   o Flask-SocketIO
            #    \  middleware
            #     o
            #  Flask-SocketIO WebSocket handler
            #
            # BECOMES
            #
            #  dbg-mw   mw1   mw2   mw3   Flask app
            #     o ---- o ---- o ---- o ---- o
            #    /
            #   o Flask-SocketIO
            #    \  middleware
            #     o
            #  Flask-SocketIO WebSocket handler
            #
            self.sockio_mw.wsgi_app = DebuggedApplication(
                self.sockio_mw.wsgi_app, evalex=True)

        if self.server.eio.async_mode == 'threading':
            try:
                import simple_websocket  # noqa: F401
            except ImportError:
                from werkzeug._internal import _log
                _log(
                    'warning', 'WebSocket transport not available. Install '
                    'simple-websocket for improved performance.')
            app.run(host=host,
                    port=port,
                    threaded=True,
                    use_reloader=use_reloader,
                    **reloader_options,
                    **kwargs)
        elif self.server.eio.async_mode == 'eventlet':

            def run_server():
                import eventlet
                import eventlet.wsgi
                import eventlet.green
                addresses = eventlet.green.socket.getaddrinfo(host, port)
                if not addresses:
                    raise RuntimeError(
                        'Could not resolve host to a valid address')
                eventlet_socket = eventlet.listen(addresses[0][4],
                                                  addresses[0][0])

                # If provided an SSL argument, use an SSL socket
                ssl_args = [
                    'keyfile', 'certfile', 'server_side', 'cert_reqs',
                    'ssl_version', 'ca_certs', 'do_handshake_on_connect',
                    'suppress_ragged_eofs', 'ciphers'
                ]
                ssl_params = {k: kwargs[k] for k in kwargs if k in ssl_args}
                if len(ssl_params) > 0:
                    for k in ssl_params:
                        kwargs.pop(k)
                    ssl_params['server_side'] = True  # Listening requires true
                    eventlet_socket = eventlet.wrap_ssl(
                        eventlet_socket, **ssl_params)

                eventlet.wsgi.server(eventlet_socket,
                                     app,
                                     log_output=log_output,
                                     **kwargs)

            if use_reloader:
                run_with_reloader(run_server, **reloader_options)
            else:
                run_server()
        elif self.server.eio.async_mode == 'gevent':
            from gevent import pywsgi
            try:
                from geventwebsocket.handler import WebSocketHandler
                websocket = True
            except ImportError:
                app.logger.warning(
                    'WebSocket transport not available. Install '
                    'gevent-websocket for improved performance.')
                websocket = False

            log = 'default'
            if not log_output:
                log = None
            if websocket:
                self.wsgi_server = pywsgi.WSGIServer(
                    (host, port),
                    app,
                    handler_class=WebSocketHandler,
                    log=log,
                    **kwargs)
            else:
                self.wsgi_server = pywsgi.WSGIServer((host, port),
                                                     app,
                                                     log=log,
                                                     **kwargs)

            if use_reloader:
                # monkey patching is required by the reloader
                from gevent import monkey
                monkey.patch_thread()
                monkey.patch_time()

                def run_server():
                    self.wsgi_server.serve_forever()

                run_with_reloader(run_server, **reloader_options)
            else:
                self.wsgi_server.serve_forever()
Beispiel #22
0
def _my_run_simple(
    hostname,
    port,
    application,
    use_reloader,
    use_debugger,
    use_evalex,
    extra_files,
    reloader_interval,
    reloader_type,
    threaded,
    processes,
    request_handler,
    static_files,
    passthrough_errors,
    ssl_context,
):
    """copy-paste-modify of werkzeug with a wishlist feature hack-added

    mainly this exists because the whole http server stack (an inheritance
    hierarchy four classes deep!) does not have a listener/hook interface.

    so the only thing this function accomplishes is to copy-paste what we
    need from `werkzeug.serving.run_simple()` *plus* we hold on to the
    server so we can hack it #here4. details:

      - this is a refactoring of `werkzeug.serving.run_simple`

      - if you want to see what the server would be like without this mostly
        redundant hackery, comment-in #here3 (NOTE you will be WITHOUT jobser).

      - we follow the structure there as much as is practical to do (while
        pruning some unnecesary stuff out

      - spiked at #history-A.1 (the first one, oops)

    """

    if use_debugger:
        from werkzeug.debug import DebuggedApplication
        application = DebuggedApplication(application, use_evalex)
    if static_files:
        from werkzeug.wsgi import SharedDataMiddleware
        application = SharedDataMiddleware(application, static_files)

    def _log_startup(sock):
        _ssl = (lambda: ssl_context is None and 'http' or 'https')()
        _hn = hostname
        _prt = sock.getsockname()[1]
        _msg = '(Press CTRL+C to quit)'
        _ws_log('info', ' * Running on %s://%s:%d/ %s', _ssl, _hn, _prt, _msg)

    def _inner():
        fd = None
        s = os.environ.get('WERKZEUG_SERVER_FD')
        if s is not None:
            fd = int(s)

        srv = ws.make_server(hostname, port, application, threaded, processes,
                             request_handler, passthrough_errors, ssl_context,
                             fd)
        # :#here4:
        if use_reloader:
            _ = ' * WARNING: reloader is on so jobser will not be used!'
            _ws_log('warn', _)
        else:
            # _try_to_capture_that_lyfe(srv)  # doesn't add much
            _hackishly_start_jobser_at_server_start(srv)
            _hackishly_stop_jobser_at_server_stop(srv)

        if fd is None:
            _log_startup(srv.socket)

        srv.serve_forever()

    import os
    if use_reloader:
        if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
            import socket
            addr_fam = socket.AF_INET
            s = socket.socket(addr_fam, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            _ai = socket.getaddrinfo(hostname, port, addr_fam,
                                     socket.SOCK_STREAM, socket.SOL_TCP)
            _sock_addr = _ai[0][4]  # all this is is (host, port)
            s.bind(_sock_addr)
            s.set_inheritable(True)

            os.environ['WERKZEUG_SERVER_FD'] = str(s.fileno())
            s.listen(ws.LISTEN_QUEUE)
            _log_startup(s)

        from werkzeug._reloader import run_with_reloader
        run_with_reloader(_inner, extra_files, reloader_interval,
                          reloader_type)
    else:
        _inner()
Beispiel #23
0
    template_type = body.get('type')

    result = None
    if template_type == 'mustache':
        with cd(project_path):
            renderer = Renderer()
            result = renderer.render_path(entry, data)
    elif template_type == 'jinja':
        env = Environment(loader=FileSystemLoader(project_path))
        template = env.get_template(entry)
        result = template.render(**data)
    else:
        return Response(status=400)

    return Response(
        content=bytes(result, 'utf-8'),
        headers={
            'Content-Type': 'text/plain'
        }
    )





if __name__ == '__main__':
    def run():
        app.run(debug=Config.DEBUG, host='0.0.0.0', port=Config.PORT)

    run_with_reloader(run)
Beispiel #24
0
def run_with_reloader(*args, **kwargs):
    # People keep using undocumented APIs.  Do not use this function
    # please, we do not guarantee that it continues working.
    from werkzeug._reloader import run_with_reloader
    return run_with_reloader(*args, **kwargs)
Beispiel #25
0
from scheduler.scheduler_listener import listener


def scheduler_instant():
    """调度实例"""
    scheduler.init_app(app)
    # 添加全局监听器
    scheduler.add_listener(listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
    scheduler.start()


def rpc_instant():
    """rpc服务端"""
    t3 = ThreadedServer(RPCServer,
                        port=config.exec.port,
                        protocol_config=rpyc.core.protocol.DEFAULT_CONFIG)
    t3.start()


def inner():
    """启动服务"""
    # 调度对象
    t1 = threading.Thread(target=scheduler_instant)
    t1.start()
    # rpc服务端
    rpc_instant()


if __name__ == '__main__':
    run_with_reloader(inner)