Exemplo n.º 1
0
def server(controller, config):
    """Serve the Prodigy REST API.

    controller (prodigy.core.Controller): The initialized controller.
    config (dict): Configuration settings, e.g. via a prodigy.json or recipe.
    """
    global HUG_API
    set_controller(controller, config)

    from waitress.server import create_server
    if config.get('cors', True) is not False:
        HUG_API.http.add_middleware(CORSMiddleware(HUG_API))
    port = os.getenv('PRODIGY_PORT', config.get('port', 8080))
    host = os.getenv('PRODIGY_HOST', config.get('host', 'localhost'))
    server = create_server(
        __hug_wsgi__,
        port=port,
        host=host,  # noqa: F821
        channel_timeout=300,
        expose_tracebacks=True,
        threads=1)
    prints('Starting the web server at http://{}:{} ...'.format(host, port),
           'Open the app in your browser and start annotating!')
    server.run()
    controller.save()
Exemplo n.º 2
0
def new_server(repo_path, session_id):
    app.config['REPOSITORY'] = 'file://' + repo_path
    app.config['SESSION_ID'] = session_id
    if not app._worker_running:
        spawn_worker()
        app._worker_running = True
    return create_server(app, port=0)
Exemplo n.º 3
0
def serve() -> None:
    global col

    col = Collection(col_path(), server=True)
    # don't hold an outer transaction open
    col.db.rollback()
    host = os.getenv("HOST", "0.0.0.0")
    port = int(os.getenv("PORT", "8080"))

    server = create_server(
        app,
        host=host,
        port=port,
        clear_untrusted_proxy_headers=True,
    )

    effective_port = server.effective_port  # type: ignore
    print(f"Sync server listening on http://{host}:{effective_port}/sync/")
    if host == "0.0.0.0":
        ip = socket.gethostbyname(socket.gethostname())
        print(f"Replace 0.0.0.0 with your machine's IP address (perhaps {ip})")
    print(
        "For more info, see https://github.com/ankitects/anki/blob/master/docs/syncserver.md"
    )
    server.run()
Exemplo n.º 4
0
    def run(self):
        try:
            if devMode:
                # idempotent if logging has already been set up
                logging.basicConfig()
            logging.getLogger("waitress").setLevel(logging.ERROR)

            desired_port = int(os.getenv("ANKI_API_PORT", "0"))
            self.server = create_server(
                app,
                host="127.0.0.1",
                port=desired_port,
                clear_untrusted_proxy_headers=True,
            )
            if devMode:
                print("Serving on http://%s:%s" %
                      (self.server.effective_host, self.server.effective_port
                       )  # type: ignore
                      )

            self._ready.set()
            self.server.run()

        except Exception:
            if not self.is_shutdown:
                raise
Exemplo n.º 5
0
def main():

    flask_app = _init_app(sys.argv)

    HOST = flask_app.config.get('HOST')
    PORT = flask_app.config.get('PORT')

    from waitress.server import create_server  # pylint: disable=import-error
    from waitress.wasyncore import poll2  # pylint: disable=import-error

    server = create_server(flask_app, host=HOST, port=PORT)
    logging.warning("server:{} serving {} on http://{}:{}".format(
        server, flask_app, HOST, PORT))

    email_client = create_email_client(flask_app)
    logging.warning("email_client:{}".format(email_client))

    try:

        timeout = 5.0
        while server._map:  # pylint: disable=protected-access
            poll2(timeout, server._map)  # pylint: disable=protected-access
            if email_client:
                email_client.poll()
    except (SystemExit, KeyboardInterrupt):

        server.close()
        if email_client:
            email_client.close()
Exemplo n.º 6
0
 def __init__(self, app, host, port):
     """
     initiate waitress server object
     :param app: Flask app object
     :param host: IP of host
     :param port: target port
     """
     self.server = create_server(app, host=host, port=port)
Exemplo n.º 7
0
 def _makeOne(self, _start=True, _sock=None):
     from waitress.server import create_server
     return create_server(dummy_app,
                          map={},
                          _start=_start,
                          _sock=_sock,
                          _dispatcher=DummyTaskDispatcher(),
                          unix_socket=self.unix_socket,
                          unix_socket_perms='600')
Exemplo n.º 8
0
 def _makeOne(self, application, host='127.0.0.1', port=0,
              _dispatcher=None, adj=None, map=None, _start=True,
              _sock=None, _server=None):
     from waitress.server import create_server
     return create_server(
         application,
         host=host,
         port=port,
         map=map,
         _dispatcher=_dispatcher,
         _start=_start,
         _sock=_sock)
Exemplo n.º 9
0
    def __init__(self, input_q, output_q, endpoint, **kwds):
        global my_input_q, my_output_q, my_recv_q, my_port
        host, port = endpoint.split(':')
        if my_port is not None:
            raise AssertionError('this server is already active on port %s' % my_port)
        my_input_q = input_q
        my_output_q = output_q
        my_port = int(port)

        my_recv_q = gr.msg_queue(10)
        self.q_watcher = queue_watcher(my_input_q, process_qmsg)

        self.server = create_server(application, host=host, port=my_port)
Exemplo n.º 10
0
    def __init__(self):
        # Mute DeprecationWarning
        warnings.simplefilter("ignore", DeprecationWarning)
        # Mute Insecure HTTPS requests made to Sonarr and Radarr
        warnings.filterwarnings('ignore', message='Unverified HTTPS request')
        # Mute Python3 BrokenPipeError
        warnings.simplefilter("ignore", BrokenPipeError)

        self.server = create_server(
            app,
            host=str(settings.general.ip),
            port=int(args.port) if args.port else int(settings.general.port),
            threads=100)
Exemplo n.º 11
0
 def start(self):
     """
     Run the thread.
     """
     address = Settings().value('api/ip address')
     port = Settings().value('api/port')
     Registry().execute('get_website_version')
     try:
         self.server = create_server(application, host=address, port=port)
         self.server.run()
     except OSError:
         log.exception('An error occurred when serving the application.')
     self.quit.emit()
Exemplo n.º 12
0
def createServer(application, logger, **kw):
    global server
    server = create_server(
        TransLogger(application, logger=logger),
        trusted_proxy='*',
        trusted_proxy_headers=('x-forwarded-for',),
        clear_untrusted_proxy_headers=True,
        **kw
    )
    if not hasattr(server, 'addr'):
      server.addr = server.adj.listen[0][3]
    elif not server.addr:
      server.addr = server.sockinfo[3]
    return server
Exemplo n.º 13
0
 def _makeOneWithMulti(self,
                       adj=None,
                       _start=True,
                       app=dummy_app,
                       listen="127.0.0.1:0 127.0.0.1:0"):
     sock = DummySock()
     task_dispatcher = DummyTaskDispatcher()
     map = {}
     from waitress.server import create_server
     return create_server(app,
                          listen=listen,
                          map=map,
                          _dispatcher=task_dispatcher,
                          _start=_start,
                          _sock=sock)
Exemplo n.º 14
0
def createServer(application, logger, **kw):
    global server
    server = create_server(
        TransLogger(application, logger=logger),
        # We handle X-Forwarded-For by ourselves. See ERP5Type/patches/WSGITask.py.
        # trusted_proxy='*',
        # trusted_proxy_headers=('x-forwarded-for',),
        clear_untrusted_proxy_headers=True,
        **kw)
    if not hasattr(server, 'addr'):
        try:
            server.addr = kw['sockets'][0].getsockname()
        except KeyError:
            server.addr = server.adj.listen[0][3]
    elif not server.addr:
        server.addr = server.sockinfo[3]
    return server
Exemplo n.º 15
0
    def __init__(self, input_q, output_q, endpoint, **kwds):
        global my_input_q, my_output_q, my_recv_q, my_port
        host, port = endpoint.split(':')
        if my_port is not None:
            raise AssertionError('this server is already active on port %s' % my_port)
        my_input_q = input_q
        my_output_q = output_q
        my_port = int(port)

        my_recv_q = gr.msg_queue(10)
        self.q_watcher = queue_watcher(my_input_q, process_qmsg)

        try:
            self.server = create_server(application, host=host, port=my_port)
        except:
            sys.stderr.write('Failed to create http terminal server\n%s\n' % traceback.format_exc())
            sys.exit(1)
Exemplo n.º 16
0
    def __call__(self, args, env):
        if not bool(importlib.util.find_spec('waitress')):
            raise VergeMLError(
                "Package waitress is not installed.",
                "To run a REST server, please install waitress first.")

        from waitress.server import create_server
        print("Loading @{} ...".format(args['@AI']))

        assert env.model
        wsgiapp = WSGIApp(env)
        server = create_server(wsgiapp.handler,
                               host=args['host'],
                               port=args['port'],
                               threads=1)
        q = queue.Queue()

        class LoadAIOnHandlerThread:
            def service(self):
                try:
                    env.model.load(env)
                    q.put("DONE")
                except Exception as e:
                    q.put(e)

            def defer(self):
                pass

            def cancel(self):
                pass

        server.task_dispatcher.add_task(LoadAIOnHandlerThread())
        res = q.get()
        if isinstance(res, Exception):
            raise res
        else:
            assert res == "DONE"

        url = "http://{}:{}".format(server.effective_host,
                                    server.effective_port)

        print("Serving on " + url)
        if not args['no-browser']:
            webbrowser.open(url)

        server.run()
Exemplo n.º 17
0
 def _makeWithSockets(self,
                      application=dummy_app,
                      _dispatcher=None,
                      map=None,
                      _start=True,
                      _sock=None,
                      _server=None,
                      sockets=None):
     from waitress.server import create_server
     _sockets = []
     if sockets is not None:
         _sockets = sockets
     self.inst = create_server(application,
                               map=map,
                               _dispatcher=_dispatcher,
                               _start=_start,
                               _sock=_sock,
                               sockets=_sockets)
     return self.inst
Exemplo n.º 18
0
    def __init__(self, input_q, output_q, endpoint, **kwds):
        global my_input_q, my_output_q, my_recv_q, my_port
        host, port = endpoint.split(':')
        if my_port is not None:
            raise AssertionError('this server is already active on port %s' %
                                 my_port)
        my_input_q = input_q
        my_output_q = output_q
        my_port = int(port)

        my_recv_q = gr.msg_queue(10)

        SEND_BYTES = 1024
        NTHREADS = 10  # TODO: make #threads a function of #plots ?
        self.server = create_server(application,
                                    host=host,
                                    port=my_port,
                                    send_bytes=SEND_BYTES,
                                    expose_tracebacks=True,
                                    threads=NTHREADS)
Exemplo n.º 19
0
def main():
    """Entrypoint for OS X."""
    root = tk.Tk()
    menubar = tk.Menu(root)
    filemenu = tk.Menu(menubar)
    filemenu.add_command(label="Open Browser",
                         command=lambda: open_webbrowser(port))
    menubar.add_cascade(label="File", menu=filemenu)
    root.config(menu=menubar)
    root.withdraw()
    directory = os.path.expanduser('~/.earthreader')
    repository = urllib.parse.urljoin('file://', directory)
    session_id = Session().identifier
    app.config.update(REPOSITORY=repository,
                      SESSION_ID=session_id,
                      USE_WORKER=True)
    server = create_server(app, port=0)
    port = server.effective_port
    proc = threading.Thread(target=server.run)
    proc.daemon = True
    proc.start()
    open_webbrowser(port)
    root.mainloop()
Exemplo n.º 20
0
    def _makeOne(
        self,
        application=dummy_app,
        host="127.0.0.1",
        port=0,
        _dispatcher=None,
        adj=None,
        map=None,
        _start=True,
        _sock=None,
        _server=None,
    ):
        from waitress.server import create_server

        self.inst = create_server(
            application,
            host=host,
            port=port,
            map=map,
            _dispatcher=_dispatcher,
            _start=_start,
            _sock=_sock,
        )
        return self.inst
Exemplo n.º 21
0
    def test_error_proxy_unsupported(self):
        from waitress.server import create_server
        server = create_server(self.app, host='127.0.0.1', port=0)

        port = server.effective_port

        gevent.spawn(server.run)

        proxies = self.proxy_dict(port)

        # http proxy not supported: just passes through
        res = self.sesh_2.get('http://example.com/path/file?foo=bar',
                              proxies=proxies,
                              verify=self.root_ca_file)

        assert (res.text == 'Requested Url: /path/file?foo=bar')

        # https proxy (via CONNECT) not supported
        with pytest.raises(requests.exceptions.ProxyError) as err:
            res = self.sesh_2.get('https://example.com/path/file?foo=bar',
                                  proxies=proxies,
                                  verify=self.root_ca_file)

        assert '405 ' in str(err.value)
Exemplo n.º 22
0

def serve():
    server.run()


def open_webbrowser(port):
    webbrowser.open('http://0.0.0.0:{}'.format(port))


if __name__ == "__main__":
    directory = os.path.expanduser('~/.earthreader')
    repository = urlparse.urljoin('file://', directory)
    session_id = Session().identifier
    app.config.update(REPOSITORY=repository, SESSION_ID=session_id)
    server = create_server(app, port=0)
    port = server.effective_port
    spawn_worker()
    proc = threading.Thread(target=serve)
    proc.daemon = True
    proc.start()
    open_webbrowser(port)
    root = tk.Tk()
    menubar = tk.Menu(root)
    filemenu = tk.Menu(menubar)
    filemenu.add_command(label="Open Browser",
                         command= lambda: open_webbrowser(port))
    menubar.add_cascade(label="File", menu=filemenu)
    root.config(menu=menubar)
    root.withdraw()
    root.mainloop()