Ejemplo n.º 1
0
def main():
    args = parse_args()
    app = import_app(args)

    address, port = args.bind.split(':')

    bjoern.run(app, address, int(port))
Ejemplo n.º 2
0
def init():
    extra_handlers = {
        'application/x-www-form-urlencoded': FormHandler()
    }

    if options.disable_log:
        app = falcon.API()
    else:
        app = falcon.API(middleware=[LoggingMiddleware()])

    # Enable parsing of urlencoded post requests and register the handler
    app.req_options.auto_parse_form_urlencoded = True
    app.req_options.media_handlers.update(extra_handlers)

    # Create root route and register custom 404 handler
    app.add_route('/', RootResource())
    app.add_sink(handle_404, '')

    try:
        bjoern.run(app, options.address, options.port)
    except Exception as ex:
        logger.critical(
            '%s Error starting server on "%s:%s": %s' % (
                init_date, options.address, options.port, ex
            )
        )
        sys.exit(1)
Ejemplo n.º 3
0
def cmd_app():
    def app(environ, start_response):
        start_response('200 OK', [])
        return ["Hello from process %d\n" % os.getpid()]

    import bjoern
    bjoern.run(app, "localhost", 8080, True)
Ejemplo n.º 4
0
def main_loop(opts):
    logger.info('Starting bjoern wsgi server: {}'.format(
        _get_wsgi_server_version()))
    worker_pids = []
    host, port = get_host_and_port(opts)

    logger.info("Listening: {host}:{port}".format(host=host, port=port))
    bjoern.listen(application, host, port)
    for worker_id in range(opts.workers):
        pid = os.fork()
        if pid > 0:
            # in master
            worker_pids.append(pid)
        elif pid == 0:
            # in worker
            logger.info('registering worker-{}'.format(worker_id))
            bjoern.run()
            exit()

    try:
        for _ in range(opts.workers):
            os.wait()
    #: redundant, however it could be rewritten to use out of main signal
    except KeyboardInterrupt:
        for pid in worker_pids:
            os.kill(pid, signal.SIGINT)
    return 0
Ejemplo n.º 5
0
def main():
    file_name = "list_of_actors.json"
    if not os.path.exists(file_name):
        create_new_empty_actors_file(file_name)

    import argparse

    parser = argparse.ArgumentParser(
        "actor_registry", description=("Starts a Actor-Registry server. Usage for callbacks from Smart Grid Actors.")
    )
    parser.add_argument(
        "--host",
        action="store",
        type=str,
        help=("Hostname/IP address to bind the " "server socket to. Default: <your ip address>"),
        default="0.0.0.0",
    )
    parser.add_argument(
        "-p", "--port", type=int, help=("Port to bind the " "server socket to. Default: 80"), default=80
    )
    args = parser.parse_args()

    try:
        import bjoern

        bjoern.run(app, args.host, args.port)
    except ImportError:
        app.run(host=args.host, port=args.port)
Ejemplo n.º 6
0
    def main(self):
        parser, args = self.parse_args(self.description,
                                       self.default_config_file)

        # TODO allow port, socket, and host config from config file
        if not (args.socket or args.port):
            print('Either a socket or port must be specified.\n',
                  file=sys.stderr)
            parser.print_help(sys.stderr)
            exit(2)

        listen_address = args.socket if args.socket else ':'.join(
            [args.host, str(args.port)])

        try:
            bjoern.listen(self.app(),
                          args.host or args.socket,
                          args.port,
                          reuse_port=args.reuse_port)
            print('Listening at {listen_address}'.format(
                listen_address=listen_address),
                  file=sys.stderr)
            bjoern.run()
        except KeyboardInterrupt:
            print('\rExit requested', file=sys.stderr)
            exit()
Ejemplo n.º 7
0
def serve_paste(app, global_conf, **kw):
    """ A handler for PasteDeploy-compatible runners.

    Sample .ini configuration:

     [server:main]
     use = egg:bjoern#main
     host = 127.0.0.1
     port = 8080
     reuse_port = True

    If no host is specified bjoern will bind to all IPv4 IPs (0.0.0.0)
    If no port is specified, bjoern will use a random port
    reuse_port defaults to False
    """
    # Convert the values from the .ini file to something bjoern can work with
    host = kw.get('host', '')
    port = int(kw.get('port', '0')) or False
    if not host and not port and kw.get('listen'):
        listen = kw.get('listen')
        if ':' in listen:
            host = listen.split(':')[0]
            port = int(listen.split(':')[1])
        else:
            host = ''
            port = int(listen)
    if kw.get('reuse_port', '').lower() in ('1', 'true', 'on'):
        reuse_port = True
    else:
        reuse_port = False

    run(app, host, port=port, reuse_port=reuse_port)
    return 0
Ejemplo n.º 8
0
def main(debug, port, host):
    if debug:
        app = flask.Flask(__name__)
        app.wsgi_app = application
        app.run(host=host, port=port, debug=True)
    else:
        bjoern.run(application, host=host, port=port)
Ejemplo n.º 9
0
def run():
    @app.route('/redoc/')
    def render_redoc():
        template = '''
            <!DOCTYPE html>
            <html>
            <head>
                <title>ReDoc</title>
                <!-- needed for adaptive design -->
                <meta charset="utf-8"/>
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">

                <!--
                ReDoc doesn't change outer page styles
                -->
                
            </head>
            <body>
                <redoc spec-url="/swagger/"></redoc>
                <script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
            </body>
            </html>
        '''

        return render_template_string(template)

    if app.config['FLASK_ENV'] == 'development':
        app.run(
            port=app.config['PORT'],
            host=app.config['HOST'],
        )
    else:
        print('Starting application in Production Mode', flush=True)
        bjoern.run(app, app.config['HOST'], int(app.config['PORT']))
Ejemplo n.º 10
0
def run():
    # creating the socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 8080))
    sock.listen(1024)
    fd = sock.fileno()

    pid = os.fork()

    if not pid:
        def app(env, sr):
            print env
            sr('200 ok', [])
            return 'hello'

        host = 'fd://%d' % fd
        try:
            bjoern.run(app, host)
        except KeyboardInterrupt:
            pass
    else:
        try:
            os.waitpid(pid, 0)
        except KeyboardInterrupt:
            os.kill(pid, 9)

        sock.close()
Ejemplo n.º 11
0
    def run(self):
        """
        This will run in a separate thread.
        """
        # Set proc name
        self.setprocname()

        # Setup database connection
        engine = sqlalchemy.create_engine(Config.get('datastore'),
                                          poolclass=sqlalchemy.pool.QueuePool,
                                          pool_size=5,
                                          max_overflow=0)
        session_factory = sqlalchemy.orm.sessionmaker(bind=engine)
        scoped_session = sqlalchemy.orm.scoped_session(session_factory)

        # Create WSGI Application
        api = falcon.API(middleware=[
            LoggingMiddleware(),
            DatabaseConnectionMiddleware(scoped_session)
        ])

        # Route Loading
        for route in ROUTES:
            api.add_route(f'{BASE_ENDPOINT}{route}', ROUTES[route]())

        # Start WSGI server
        try:
            logger.info(f'Starting bjoern server on {self._bind}:{self._port}')
            bjoern.run(api, self._bind, self._port)
        except Exception as e:
            logger.info(f'Shutting down bjoern due to: {str(e)}')

        # Dispose all database connection
        with contextlib.suppress(Exception):
            engine.dispose()
Ejemplo n.º 12
0
def cmd_app():
    def app(environ, start_response):
        start_response('200 OK', [])
        return [b"Hello from process %d\n" % os.getpid()]

    import bjoern
    bjoern.run(app, "localhost", 8080, True)
Ejemplo n.º 13
0
def main(workers):
    worker_pids = []
    if workers <= 0:
        workers = multiprocessing.cpu_count()
    if workers == 1:
        print(f"Server started with pid={os.getpid()}")
        bjoern.run(application, 'localhost', 8080)
    else:
        print(f"Starting {workers} worker(s)...")
        bjoern.listen(application, 'localhost', 8080)
        print(f"Master started with pid={os.getpid()}")
        for _ in range(workers):
            pid = os.fork()
            if pid > 0:
                worker_pids.append(pid)
            elif pid == 0:
                try:
                    print(f"Worker started with pid={os.getpid()}")
                    bjoern.run()
                except KeyboardInterrupt:
                    pass
                exit()
        try:
            for _ in range(workers):
                os.wait()
        except KeyboardInterrupt:
            for pid in worker_pids:
                os.kill(pid, signal.SIGINT)
Ejemplo n.º 14
0
def run_metrics(socket_path, options):
    signal.signal(signal.SIGINT, lambda *args: 0)
    if SETPROCTITLE:
        setproctitle.setproctitle('%s metrics' % options.process_name)
    address = options.metrics_listen
    logging.info('starting metrics worker: %s', address)
    address = address.split(':')
    bjoern.run(metrics_app, address[0], int(address[1]))
Ejemplo n.º 15
0
def wsgi_serve(
    wsgi_handler: Callable,
    host: str = "127.0.0.1",
    port: int = 80,
    workers: int = 1,
) -> None:
    if workers >= 1:
        run(wsgi_handler, host, port)
Ejemplo n.º 16
0
 def start(self):
     log.info("Starting bjoern server")
     try:
         bjoern.run(self.app, "127.0.0.1", 8001)
     except (KeyboardInterrupt, TypeError):
         log.info("bjoern received ctrl-c")
     except Exception as e:
         log.exception("bjoern threw exception")
     log.info("Ending bjoern server")
Ejemplo n.º 17
0
def serve(application: Application,
          host: str = "127.0.0.1",
          port=80,
          debug: bool = False) -> None:
    import bjoern

    wsgi_handler = create_wsgi_handler(application, debug=debug)

    bjoern.run(wsgi_handler, host, port)
Ejemplo n.º 18
0
def _wsgi_benchmark_server(lock, port):
    grpc_wsgi_app = sonora.wsgi.grpcWSGI(None)
    benchmark_pb2_grpc.add_BenchmarkServiceServicer_to_server(
        SyncBenchmark(), grpc_wsgi_app)
    bjoern.listen(grpc_wsgi_app, "localhost", port)

    lock.release()

    bjoern.run()
Ejemplo n.º 19
0
def _wsgi_helloworld_server(lock, port):
    grpc_wsgi_app = sonora.wsgi.grpcWSGI(None)
    helloworld_pb2_grpc.add_GreeterServicer_to_server(SyncGreeter(),
                                                      grpc_wsgi_app)
    bjoern.listen(grpc_wsgi_app, "localhost", port)

    lock.release()

    bjoern.run()
Ejemplo n.º 20
0
def run_bjoern(hostname, portnum):
    """
   Start the server, using the Bjoern server (https://github.com/jonashaag/bjoern)
   """

    log.info("Starting Bjoern server on %s:%s" % (hostname, portnum))

    import bjoern

    bjoern.run(rg_server.wsgi_handle_request, hostname, portnum)
Ejemplo n.º 21
0
def run_metrics(socket_path, options):
    if SETPROCTITLE:
        setproctitle.setproctitle('%s metrics' % options.process_name)
    address = options.metrics_listen
    logging.info('starting metrics worker: %s', address)
    address = address.split(':')
    try:
        bjoern.run(metrics_app, address[0], int(address[1]))
    except KeyboardInterrupt:
        pass
Ejemplo n.º 22
0
    def run_metrics(self, socket_path, options, workers):
        address = options.metrics_listen

        address_parts = address.split(':')

        # Run server, this blocks.
        logging.debug('starting metrics worker (%s) with pid %d', address,
                      os.getpid())
        bjoern.run(partial(metrics_app, workers), address_parts[0],
                   int(address_parts[1]))
Ejemplo n.º 23
0
def main(argv):
    if os.environ['FLASK_MODE'] == 'production':
        import bjoern
        bjoern.run(app, '127.0.0.1', port=8090)
    else:
        app.run(host='0.0.0.0',
                port=8090,
                debug=True,
                use_reloader=True,
                threaded=True)
Ejemplo n.º 24
0
def run_bjoern( hostname, portnum ):
   """
   Start the server, using the Bjoern server (https://github.com/jonashaag/bjoern)
   """
   
   log.info("Starting Bjoern server on %s:%s" % (hostname, portnum))
   
   import bjoern
   
   bjoern.run( rg_server.wsgi_handle_request, hostname, portnum )
Ejemplo n.º 25
0
def bjoern():
    '''
    For other options in running bjoern see https://github.com/jonashaag/bjoern
    '''
    from finitelycomputable.django_apps.wsgi import application
    import bjoern
    import sys
    try:
        bjoern.run(application, "0.0.0.0", 8000)
    except KeyboardInterrupt:
        sys.exit(1)
Ejemplo n.º 26
0
def main():
    parser = argparse.ArgumentParser('onnxrt-server')
    parser.add_argument('--model', default='/models/model.onnx')
    parser.add_argument('--host', default='0.0.0.0')
    parser.add_argument('--port', type=int, default=8001)
    options = parser.parse_args()

    load_model(options.model)

    wrapped = WSGILogger(app, [StreamHandler(stream=sys.stdout)], ApacheFormatter())

    bjoern.run(wrapped, options.host, options.port)
Ejemplo n.º 27
0
def main():

    options = [
        make_option("--data-dir", dest="data_dir", default=".data/",
                    help="data directory to store user profile"),
        make_option("--host", dest="host", default="127.0.0.1", type=str,
                    help=SUPPRESS_HELP),
        make_option("--port", dest="port", default=8080, type=int,
                    help="port to serve on"),
        make_option("--register", dest="creds", default=None,
                    help="user:passwd credentials"),
        make_option("--enable-registration", dest="registration", action="store_true",
                    help="enable registration"),
        make_option("--prefix", dest="prefix", default="/",
                    help="prefix support for broken servers, deprecated."),
        make_option("--base-url", dest="base_url", default=None,
                    help="set your actual URI such as https://example.org/weave/"),
        make_option("--use-reloader", action="store_true", dest="reloader",
                    help=SUPPRESS_HELP, default=False),
        make_option("--version", action="store_true", dest="version",
                    help=SUPPRESS_HELP, default=False),
        ]

    parser = OptionParser(option_list=options)
    (options, args) = parser.parse_args()

    if options.version:
        print __version__
        sys.exit(0)

    if options.creds:
        """user registration via --register user:pass"""

        try:
            username, passwd = options.creds.split(':', 1)
        except ValueError:
            print '[error] provide credentials as `user:pass`!'
            sys.exit(1)

        try:
            initialize(encode(username), passwd, options.data_dir)
        except WeaveException:
            sys.exit(1)
        sys.exit(0)

    prefix = options.prefix.rstrip('/')
    app = make_app(options.data_dir, prefix, options.base_url, options.registration)

    if bjoern and not options.reloader:
        print ' * Running on http://%s:%s/' % (options.host, options.port)
        bjoern.run(app, options.host, options.port)
    else:
        run_simple(options.host, options.port, app, use_reloader=options.reloader)
Ejemplo n.º 28
0
def start(name):
    print "started server at "+str(host)+":"+str(port)
    if name =="meinheld":
        from meinheld import server
        server.set_access_logger(None)
        server.set_error_logger(None)
        server.listen((host, port))
        server.run(app)
    elif name =="gevent":
        #from gevent import wsgi 
        #wsgi.WSGIServer((host, port), application=app.application, log=None).serve_forever() 
        from gevent.pywsgi import WSGIServer
        WSGIServer((host, port), app, log=None).serve_forever()
    elif name =="bjoern":
        import bjoern
        bjoern.listen(app, host, port)
        bjoern.run() 
    elif name =="eventlet":
        import eventlet
        from eventlet import wsgi
        #worker_pool = eventlet.GreenPool(2000)
        #wsgi.server(eventlet.listen(('', port)), app, custom_pool=worker_pool, log=file('/dev/null', 'w'))
        # max_size
        wsgi.server(eventlet.listen(('', port)), app, max_size=10000, log=file('/dev/null', 'w'))
    elif name =="fapws":
        import fapws._evwsgi as evwsgi
        from fapws import base
        evwsgi.start(host, str(port)) 
        evwsgi.set_base_module(base)
        evwsgi.wsgi_cb(('/', app))
        evwsgi.set_debug(0)        
        evwsgi.run()
    elif name=="uwsgi":
        print ("""Enter this command in the console
                \nsudo uwsgi --http :8000 --master --disable-logging --pythonpath /home/a/g --wsgi-file w.py --listen 2  --buffer-size 2048 --async 10000 --ugreen -p 4
            """)
        #  http://osdir.com/ml/python-wsgi-uwsgi-general/2011-02/msg00136.html
        # 
        #  Re: strange SIGPIPE: writing to a closed pipe/socket/fd on image requested from facebook -msg#00136
        """
SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /1 (ip 127.0.0.1) !!!
uwsgi_response_write_body_do(): Broken pipe [core/writer.c line 260]
IOError: write error
        """
        cmd_txt = "sudo uwsgi --http :8000 --master --harakiri 1 --harakiri-verbose --close-on-exec --disable-logging --pythonpath /home/a/todo/test --wsgi-file w2.py --listen 2  --buffer-size 2048 --async 10000 --ugreen -p 4"
        cmd(cmd_txt)
    elif name=="pycgi":
        from wsgiref.handlers import CGIHandler 
        CGIHandler().run(app)
    elif name=="pystandard":
        from wsgiref.simple_server import make_server
        make_server(host, port, app).serve_forever()
Ejemplo n.º 29
0
def run_notify(socket_path, options):
    signal.signal(signal.SIGINT, lambda *args: 0)
    if SETPROCTITLE:
        setproctitle.setproctitle('%s notify' % options.process_name)
    if options.with_metrics:
        middleware=[FalconMetrics()]
    else:
        middleware=None
    app = kopano_rest.NotifyAPI(options=options, middleware=middleware)
    app.add_error_handler(Exception, error_handler)
    unix_socket = 'unix:' + os.path.join(socket_path, 'notify.sock')
    logging.info('starting notify worker: %s', unix_socket)
    bjoern.run(app, unix_socket)
Ejemplo n.º 30
0
def startRestService(train_persist_location, endpoint):
    storage_data_train = get_storage_data(os.getenv("STORAGE_TRAIN"))
    storage_train = build_minio_client(storage_data_train)
    minio_download_training(storage_train, storage_data_train["bucket"],
                            train_persist_location, "data/train.zip")
    unzip("data/train.zip", "data/train")
    restapp = app(train_directory="data/train", endpoint=endpoint)
    host = os.getenv("HOST")
    if os.getenv("PORT") is None:
        port = 5000
    else:
        port = int(os.getenv("PORT"))
    bjoern.run(restapp, host, port)
Ejemplo n.º 31
0
def main(argv):
    del argv  # Unused.

    app = create_app(FLAGS.database_path)

    if FLAGS.init_db:
        with app.app_context():
            db.init_db()

    print('Serving app...')
    # http_server = WSGIServer((FLAGS.host, FLAGS.port), app)
    # http_server.serve_forever()
    bjoern.run(app, FLAGS.host, FLAGS.port, statsd={'enable': True, 'port': 5082})
Ejemplo n.º 32
0
def serve(*middleware, host: str = "0.0.0.0", port: int = 80) -> None:
    if not middleware:
        application = Application(router)
    else:
        application = Application(*middleware)

    try:
        from bjoern import run

        run(application, host=host, port=port)
    except ImportError as error:
        raise RuntimeError(
            "`bjoern` module could not be found, please run `pip install bjoern`."
        )
Ejemplo n.º 33
0
Archivo: wsgi.py Proyecto: innerr/stars
def bjoern(entry, app, port, params):
    import bjoern
    def server(environ, start_response):
        headers, response = entry(environ, app)
        start_response('200 OK', headers)
        if isinstance(response, str):
            response = (response,)
        return response
    try:
        bjoern.listen(server, '0.0.0.0', port)
        bjoern.run()
    except KeyboardInterrupt:
        pass
    print 'Closing...'
Ejemplo n.º 34
0
def run_notify(socket_path, options):
    if SETPROCTITLE:
        setproctitle.setproctitle('kopano-mfr notify')
    if options.with_metrics:
        middleware = [FalconMetrics()]
    else:
        middleware = None
    app = kopano_rest.NotifyAPI(options=options, middleware=middleware)
    app.add_error_handler(Exception, error_handler)
    unix_socket = 'unix:' + os.path.join(socket_path, 'notify.sock')
    logging.info('starting notify worker: %s', unix_socket)
    try:
        bjoern.run(app, unix_socket)
    except KeyboardInterrupt:
        pass
Ejemplo n.º 35
0
def main():
    parser = argparse.ArgumentParser(epilog='Gemüse kaufen!')
    parser.add_argument('host', help='(without http://)')
    parser.add_argument('port', type=int)
    parser.add_argument('--display-host', dest='custom_host')
    parser.add_argument('repo', nargs='+', type=valid_directory,
                        help='repository directories to serve')
    args = parser.parse_args()
    sys.argv = ['this is a hack'] + args.repo

    from klaus import app
    if args.custom_host:
        app.custom_host = args.custom_host

    run(app, args.host, args.port)
Ejemplo n.º 36
0
def main():
    parser = argparse.ArgumentParser(epilog="Gemüse kaufen!")
    parser.add_argument("host", help="(without http://)")
    parser.add_argument("port", type=int)
    parser.add_argument("--display-host", dest="custom_host")
    parser.add_argument("repo", nargs="+", type=valid_directory, help="repository directories to serve")
    args = parser.parse_args()
    sys.argv = ["this is a hack"] + args.repo

    from klaus import app

    if args.custom_host:
        app.custom_host = args.custom_host

    run(app, args.host, args.port)
Ejemplo n.º 37
0
def run_app(socket_path, n, options):
    if SETPROCTITLE:
        setproctitle.setproctitle('%s rest %d' % (options.process_name, n))
    if options.with_metrics:
        middleware = [FalconMetrics()]
    else:
        middleware = None
    app = kopano_rest.RestAPI(options=options, middleware=middleware)
    app.add_error_handler(Exception, error_handler)
    unix_socket = 'unix:' + os.path.join(socket_path, 'rest%d.sock' % n)
    logging.info('starting rest worker: %s', unix_socket)
    try:
        bjoern.run(app, unix_socket)
    except KeyboardInterrupt:
        pass
Ejemplo n.º 38
0
def start(controller):
    global app

    app.controller = controller
    app.settings = controller.settings
    app.authorised_sessions = []

    log.info("Starting bjoern server")
    try:
        bjoern.run(app, "127.0.0.1", 8001)
    except (KeyboardInterrupt, TypeError):
        log.info("bjoern received ctrl-c")
    except Exception as e:
        log.exception("bjoern threw exception")
    log.info("Ending bjoern server")
Ejemplo n.º 39
0
def main():
    parser = argparse.ArgumentParser(epilog='Gemüse kaufen!')
    parser.add_argument('host', help='(without http://)')
    parser.add_argument('port', type=int)
    parser.add_argument('--display-host', dest='custom_host')
    parser.add_argument('repo', nargs='+', type=valid_directory,
                        help='repository directories to serve')
    args = parser.parse_args()

    from klaus import app
    app.repos = {repo.rstrip(os.sep).split(os.sep)[-1]: repo for repo in args.repo}
    if args.custom_host:
        app.custom_host = args.custom_host

    run(app, args.host, args.port)
Ejemplo n.º 40
0
def serve(listen):
    host, _, port = listen.partition(':')
    host = host or 'localhost'
    port = int(port or 5000)

    # Remove global CLI app context so that app context is set and torn down on
    # each request. This way, Flask-SQLAlchemy app context teardown is called
    # and session is properly remove upon each request.
    ctx = _app_ctx_stack.pop()

    logger.info("Serving on http://%s:%s/.", host, port)
    try:
        bjoern.run(ctx.app, host, port)
    finally:
        # Push back ctx so that CLI context is preserved
        ctx.push()
Ejemplo n.º 41
0
def start():
    def return_tuple(environ, start_response):
        start_response('200 OK', [('Content-Type','text/plain')])
        print 'tuple'
        return ('Hello,', " it's me, ", 'Bob!')

    def return_huge_answer(environ, start_response):
        start_response('200 OK', [('Content-Type','text/plain')])
        return ['x'*(1024*1024)]

    def return_404(environ, start_response):
        start_response('404 Not Found', (('Content-Type','text/plain'), ))
        return "URL %s not found" % environ.get('PATH_INFO', 'UNKNOWN')
        
    dispatch = {
        '/tuple': return_tuple,
        '/huge': return_huge_answer,
    }

    def choose(environ, start_response):
        return dispatch.get(environ.get('PATH_INFO'), return_404)(environ, start_response)
    bjoern.run(choose, '0.0.0.0', 8080)
Ejemplo n.º 42
0
def run(config, mode):
    """Run production/development server.

    Two modes of operation are available:

    - dev: Run a development server

    - prod: Run a production server (requires the `bjoern` module)
    """
    if mode == 'dev':
        app = create_app(config_file=config,
                         ENV='development',
                         DEBUG=True,
                         TESTING=True)
        app.run(threaded=True)

    elif mode == 'prod':
        if bjoern:
            echo('Starting bjoern on port 8080...')
            bjoern.run(create_app(config_file=config), '0.0.0.0', 8080)
        else:
            raise ClickException('The production server requires `bjoern`, '
                                 'try installing it with '
                                 '`pip install bjoern`.')
Ejemplo n.º 43
0
import bjoern
import os
import signal
from pyDMON import app

host = '0.0.0.0'
port = 5001
NUM_WORKERS = 2
worker_pids = []


bjoern.listen(app, host, port)
for _ in xrange(NUM_WORKERS):
    pid = os.fork()
    if pid > 0:
        # in master
        worker_pids.append(pid)
    elif pid == 0:
        # in worker
        try:
            bjoern.run()
        except KeyboardInterrupt:
            pass
        exit()

try:
    for _ in xrange(NUM_WORKERS):
        os.wait()
except KeyboardInterrupt:
    for pid in worker_pids:
        os.kill(pid, signal.SIGINT)
Ejemplo n.º 44
0
	cmd.extend(*args)

	try:
		output = subprocess.check_output(cmd).splitlines()
		for metric in output:
			database().update(**json.loads(metric))
	except Exception as e:
		traceback.print_exc()
		print e



if __name__ == '__main__':
	if '--serve' in sys.argv:
		try:
			import bjoern
			bjoern.run(wsgiengine(), "127.0.0.1", 8000, reuse_port=True)
		except ImportError:
			wsgiengine().run()
	elif '--run' in sys.argv:
		scripthandler(sys.argv[2], sys.argv[3:])
	else:
		print """Usage:

	main.py --serve 					Run an internal webserver to provide state.json
	main.py --run <scriptname> [args]	Run a script in the scripts directory with optional args, the result updates the state.db
"""



Ejemplo n.º 45
0
 def bjoern(app, address, **options):
     import bjoern
     bjoern.run(app, *address)
Ejemplo n.º 46
0
            status, body = '400 Bad Request', '{"code": "EMPTY_REQUEST","message": "请求体为空"}'
            start_response(status, headers)
            return [body]
        else:
            request_body = environ['wsgi.input'].read(request_body_size)
            try:
                # 创建篮子post数据为空
                if not(route[1] == 'carts' and request_method == "POST"):
                    environ['data'] = json.loads(request_body)
            except:
                # 读取json失败
                status, body = '400 Bad Request', '{"code": "MALFORMED_JSON","message": "格式错误"}'
                start_response(status, headers)
                return [body]

    if not environ.get('token') and resource != 'login':
        status, body = '401 Unauthorized', '{"code": "INVALID_ACCESS_TOKEN","message": "无效的令牌"}'
    else:
        status, body = API[resource][request_method](environ)
        # if resource != 'admin' or (len(route) == 3 and (route[2] == 'orders' or route[1] == 'carts')):
        #     status, body = API[resource][request_method](environ)
        # else:
        #     status = '404 Not Found'

    start_response(status, headers)
    return [body]

if __name__ == '__main__':
    bjoern.run(application, host, port, True)
    #WSGIServer((host, port), application).serve_forever()
Ejemplo n.º 47
0
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

"""

# Base imports
import os
import sys
from os.path import dirname

# Bjoern imports
import bjoern

# Django imports
import django.core.handlers.wsgi

relPath = dirname(dirname( os.path.abspath(__file__) ))
sys.path.append(os.path.abspath(relPath))

os.environ['DJANGO_SETTINGS_MODULE'] = 'djangobytes.settings'

application = django.core.handlers.wsgi.WSGIHandler()

bjoern.run(application, sys.argv[1], int(sys.argv[2]))
Ejemplo n.º 48
0
 def run(self, handler):
     from bjoern import run
     run(handler, self.host, self.port)
Ejemplo n.º 49
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import sys

# Bjoern is a Fast and Ultra-Lightweight Asynchronous HTTP/1.1 WSGI Server
# https://github.com/jonashaag/bjoern
import bjoern

TEMPLATE = """\
<body>
<html>
<h1>Face Detection Server</h1>
<img src='file:///home/ozan/git/OpenCV/Python/05.jpg'/>
</html>
</body>
"""

def detection(env, sr):
    sr('200 ok', [])
    return TEMPLATE

def wsgi_app(env, start_response):
    return detection(env, start_response)


if __name__ == "__main__":
    bjoern.run(wsgi_app, '0.0.0.0', 12345)
Ejemplo n.º 50
0
            if module.__name__ == module_name:
                for test_ in tests_:
                    if test_.app.__name__ == test_name:
                        test = test_
                        break
                else:
                    continue
                break
    else:
        iterator = iter(tests.chainvalues())
        index -= 1
        while index:
            iterator.next()
            index -= 1
        test = iterator.next()

    assert test is not None
    def chose_test():
        return test.app
else:
    testlist = list(tests.chainvalues())
    def chose_test():
        return random.choice(testlist).app

def app(environ, start_response):
    app = chose_test()
    return app(environ, start_response)

import bjoern
bjoern.run(app, '127.0.0.1', 8080)
Ejemplo n.º 51
0
def app1(env, sr):
    #print(env)
    sr('200 ok', [('Foo', 'Bar'), ('Blah', 'Blubb'), ('Spam', 'Eggs'), ('Blurg', 'asdasjdaskdasdjj asdk jaks / /a jaksdjkas jkasd jkasdj '),
                  ('asd2easdasdjaksdjdkskjkasdjka', 'oasdjkadk kasdk k k k k k ')])
    return [b'hello', b'world']

def app2(env, sr):
    #print(env)
    sr('200 ok', [])
    return b'hello'

def app3(env, sr):
    #print(env)
    sr('200 abc', [('Content-Length', '12')])
    yield b'Hello'
    yield b' World'
    yield b'\n'

def app4(e, sr):
    sr('200 ok', [])
    return [b'hello there ... \n']

apps = (app1, app2, app3, app4)

def wsgi_app(env, start_response):
    return choice(apps)(env, start_response)

if __name__ == '__main__':
    bjoern.run(wsgi_app, '0.0.0.0', 8080)
Ejemplo n.º 52
0
from flask import Flask, request
import bjoern

app = Flask(__name__)

@app.route('/printenv')
def printenv():
    str = []
    print type(request.environ)
    for k, v in sorted(request.environ.iteritems()):
        str.append("<span style='color: red'>%s</span>: %s  " % (k, v))
    res = "<br/>\n".join(str)
    return res

if __name__ == '__main__':
    print "bjoern run ..."
    bjoern.run(app, "0.0.0.0", 8000)
Ejemplo n.º 53
0
def start_bjoern_server(wsgi_application, host_name, port):
    import bjoern
    try:
        bjoern.run(wsgi_application, host_name, port)
    except KeyboardInterrupt:
        pass
Ejemplo n.º 54
0
 def handle(self, address, port, *args, **kwargs):
     bjoern.run(wsgi.application, address, port)
Ejemplo n.º 55
0
#!/usr/bin/env python

import bjoern # for local testing
from wsgi import application

bjoern.run(application, 'localhost', 8080) # for local testing
Ejemplo n.º 56
0
def launch(address, port):
    import bjoern
    bjoern.run(application, address, port)
Ejemplo n.º 57
0
 def run(self, handler):
     from uvweb import run
     run(handler, self.host, self.port)
Ejemplo n.º 58
0
N = 1024
CHUNK = 'a' * 1024
DATA_LEN = N * len(CHUNK)

class _iter(object):
    def __iter__(self):
        for i in xrange(N):
            yield CHUNK

def app(e, s):
    s('200 ok', [('Content-Length', str(DATA_LEN))])
    return _iter()

import bjoern
bjoern.run(app, '0.0.0.0', 8080)
Ejemplo n.º 59
0
import bjoern
bjoern.run(object(), '0.0.0.0', 8080)
Ejemplo n.º 60
0
#!/usr/bin/env python

import os
port = int(os.environ.get('PORT', 7777))

import bjoern
from application import wsgi
bjoern.run(wsgi.application, '0.0.0.0', port)