A very simple approach for a WSGI server.
320883
def serve(self, app, conf):
        

        if self.args.reload:
            try:
                self.watch_and_spawn(conf)
            except ImportError:
                print('The `--reload` option requires `watchdog` to be '
                      'installed.')
                print('   $ pip install watchdog')
        else:
            self._serve(app, conf)
1051050
def main(arguments=None):
    ''''''
    if arguments is None:
        arguments = sys.argv[1:]

    server_parameters = get_server_parameters(arguments)
    config = get_config(server_parameters.config_path, server_parameters.use_environment)
    configure_log(config, server_parameters.log_level.upper())

    validate_config(config, server_parameters)

    importer = get_importer(config)

    with get_context(server_parameters, config, importer) as context:
        application = get_application(context)
        server = run_server(application, context)
        setup_signal_handler(server, config)
        logging.debug('thumbor running at %s:%d' % (context.server.ip, context.server.port))
        tornado.ioloop.IOLoop.instance().start()
1169456
def wsgi(self, environ, start_response):
        """"""
        request = Request(environ)
        ctx = Context(request)
        try:
            try:
                response = self(request, ctx)
                ctx._run_callbacks('finalize', (request, response))
                response = response.conditional_to(request)
            except HTTPException as e:
                response = e.response
            except Exception:
                self.handle_error(request, ctx)
                response = InternalServerError().response

            response.add_callback(lambda: ctx._run_callbacks('close'))
            return response(environ, start_response)
        finally:
            ctx._run_callbacks('teardown', log_errors=True)
182395
def main(port=8000, n_output=10, use_segmenter=False):
    """"""
    global n
    global use_segmenter_flag
    n = n_output
    use_segmenter_flag = use_segmenter
    logging.info("Start webserver...")
    app.run(port=port)
38760
def configure():
    
    import os
    from uwsgiconf.presets.nice import PythonSection

    FILE = os.path.abspath(__file__)
    port = 8000

    configurations = []

    for idx in range(2):

        alias = 'app_%s' % (idx + 1)

        section = PythonSection(
            # Automatically reload uWSGI if this file is changed.
            touch_reload=FILE,

            # To differentiate easily.
            process_prefix=alias,

            # Serve WSGI application (see above) from this very file.
            wsgi_module=FILE,

            # Custom WSGI callable for second app.
            wsgi_callable=alias,

            # One is just enough, no use in worker on every core
            # for this demo.
            workers=1,

        ).networking.register_socket(
            PythonSection.networking.sockets.http('127.0.0.1:%s' % port)
        )

        port += 1

        configurations.append(
            # We give alias for configuration to prevent clashes.
            section.as_configuration(alias=alias))

    return configurations
946452
def create(self):
        """"""
        # url('datastores')
        content = request.environ['wsgi.input'].read(int(request.environ['CONTENT_LENGTH']))
        content = content.decode('utf8')
        content = simplejson.loads(content)
        new = DataStore(content['name'],
                        content['type'],
                        content['ogrstring'])
        results = meta.Session.add(new)
        meta.Session.commit()
        response.status = 201
94302
def wsgi_handler(event, context, app, logger):
    

    environ = build_wsgi_environ_from_event(event)
    wsgi_status = []
    wsgi_headers = []

    logger.info('Processing {} request'.format(environ['REQUEST_METHOD']))

    def start_response(status, headers):
        if len(wsgi_status) or len(wsgi_headers):
            raise RuntimeError('start_response called more than once!')
        wsgi_status.append(status)
        wsgi_headers.append(headers)

    resp = list(app(environ, start_response))
    proxy = {'statusCode': int(wsgi_status[0].split()[0]),
             'headers': {h[0]: h[1] for h in wsgi_headers[0]},
             'body': b''.join(resp).decode('utf-8')}

    logger.info("Returning {}".format(proxy['statusCode']),
                http_status=proxy['statusCode'])

    return proxy
12761
def run(self):
        
        try:
            # Go through the list of possible ports, hoping we can find
            # one that is free to use for the WSGI server.
            for index, port in enumerate(self.possible_ports):
                try:
                    self.httpd = self._create_server(port)
                except socket.error as e:
                    if (index + 1 < len(self.possible_ports) and
                            e.error == errno.EADDRINUSE):
                        # This port is already in use, so we go on and try with
                        # the next one in the list.
                        continue
                    else:
                        # Either none of the given ports are free or the error
                        # is something else than "Address already in use". So
                        # we let that error bubble up to the main thread.
                        raise
                else:
                    # A free port was found.
                    self.port = port
                    break

            self.is_ready.set()
            self.httpd.serve_forever()
        except Exception as e:
            self.error = e
            self.is_ready.set()
950929
def run(host='0.0.0.0', port=5000, reload=True, debug=True):
    
    from werkzeug.serving import run_simple

    app = bootstrap.get_app()
    return run_simple(
        hostname=host,
        port=port,
        application=app,
        use_reloader=reload,
        use_debugger=debug,
    )
1022351
def wsgi_wrap(app):
    '''
    
    '''
    @wraps(app)
    def wrapped(environ, start_response):
        status_headers = [None, None]
        def _start_response(status, headers):
            status_headers[:] = [status, headers]
        body = app(environ, _start_response)
        ret = body, status_headers[0], status_headers[1]
        return ret
    return wrapped
546919
def serve_forever(self):
        

        # Verify that the provider has a server.
        if self.provider.server is None:
            raise ValueError(
                "Cannot start server because the provider has no server to "
                "publish.")

        # Verify that the provider has a database to advertise.
        if not self.provider.server.databases:
            raise ValueError(
                "Cannot start server because the provider has no databases to "
                "publish.")

        # Create WSGI server and run it.
        self.server = WSGIServer((self.ip, self.port), application=self.app)

        # Register Bonjour.
        if self.bonjour:
            self.bonjour.publish(self)

        # Start server until finished
        try:
            self.server.serve_forever()
        except KeyboardInterrupt:
            pass
        finally:
            # Unregister Bonjour
            if self.bonjour:
                self.bonjour.unpublish(self)
739894
def run(filepath, wsgiapp, host, port, reload, interval,
        static, static_root, static_dirs, lineprof, lineprof_file, validate):
    
    insert_import_path_to_sys_modules(filepath)
    module = SourceFileLoader('module', filepath).load_module()
    app = getattr(module, wsgiapp)

    if static:
        from wsgi_static_middleware import StaticMiddleware
        app = StaticMiddleware(app, static_root=static_root, static_dirs=static_dirs)

    if validate:
        from wsgiref.validate import validator
        app = validator(app)

    if lineprof:
        # Caution: wsgi-lineprof is still pre-alpha. Except breaking API Changes.
        from wsgi_lineprof.middleware import LineProfilerMiddleware
        from wsgi_lineprof.filters import FilenameFilter, TotalTimeSorter

        if lineprof_file:
            # Now wsgi-lineprof is now supported only 1 file checking.
            lineprof_file = lineprof_file[0]
        else:
            lineprof_file = os.path.basename(filepath)
        filters = [FilenameFilter(lineprof_file), TotalTimeSorter()]
        app = LineProfilerMiddleware(app, filters=filters)

    if reload:
        run_live_reloading_server(interval, app=app, host=host, port=port)
    else:
        run_server(app=app, host=host, port=port)
263611
def _make_server(self):
    """"""
    app = application.standard_tensorboard_wsgi(self.flags,
                                                self.plugin_loaders,
                                                self.assets_zip_provider)
    return self.server_class(app, self.flags)
24087
def main(global_config, **settings):
    
    # Initialize the database
    engine = engine_from_config(settings, 'sqlalchemy.')
    configure_sql(engine)

    secure_cookies = settings.get('secure_cookies') != 'false'
    if 'pyramid_debugtoolbar' in settings['pyramid.includes']:
        create_schema(global_config['__file__'])
        populate_database()
        secure_cookies = False

    # Configure the webapp
    authen = AuthTktAuthenticationPolicy(secret=settings['auth_secret'],
                                         callback=group_finder,
                                         secure=secure_cookies,
                                         include_ip=False, hashalg='sha512',
                                         wild_domain=False, max_age=5000000)
    author = ACLAuthorizationPolicy()
    session_factory = UnencryptedCookieSessionFactoryConfig(
        settings['cookie_secret'])
    config = Configurator(settings=settings, authentication_policy=authen,
                          authorization_policy=author, root_factory=Root,
                          session_factory=session_factory)
    config.add_static_view('static', 'static', cache_max_age=3600)
    # Add attributes to request
    config.add_request_method(get_user, 'user', reify=True)
    config.add_request_method(get_queue_func, 'queue', reify=True)

    add_routes(config)
    config.scan()
    return config.make_wsgi_app()
15017
def serve(application, host='127.0.0.1', port=8080):
	
	
	# Instantiate the server with a host/port configuration and our application.
	WSGIApplication(application, port=int(port), iface=host).run()
853984
def main():
    """"""

    #
    # setup command line parsing a la argpase
    #
    parser = argparse.ArgumentParser()

    # positional args
    parser.add_argument('uri', metavar='URI', nargs='?', default='/',
                        help='[owserver:]//hostname:port/path')

    #
    # parse command line args
    #
    args = parser.parse_args()

    #
    # parse args.uri and substitute defaults
    #
    urlc = urlsplit(args.uri, scheme='owserver', allow_fragments=False)
    assert urlc.fragment == ''
    if urlc.scheme != 'owserver':
        parser.error("Invalid URI scheme '{0}:'".format(urlc.scheme))
    if urlc.query:
        parser.error("Invalid URI, query component '?{0}' not allowed"
                     .format(urlc.query))
    try:
        host = urlc.hostname or 'localhost'
        port = urlc.port or 4304
    except ValueError as error:
        parser.error("Invalid URI: invalid net location '//{0}/'"
                     .format(urlc.netloc))

    #
    # create owserver proxy object
    #
    try:
        owproxy = protocol.proxy(host, port, persistent=True)
    except protocol.ConnError as error:
        print("Unable to open connection to '{0}:{1}'\n{2}"
              .format(host, port, error), file=sys.stderr)
        sys.exit(1)
    except protocol.ProtocolError as error:
        print("Protocol error, '{0}:{1}' not an owserver?\n{2}"
              .format(host, port, error), file=sys.stderr)
        sys.exit(1)

    stress(owproxy, urlc.path)
773585
def serve(application, host='127.0.0.1', port=8080, threads=4, **kw):
	
	
	# Bind and start the server; this is a blocking process.
	serve_(application, host=host, port=int(port), threads=int(threads), **kw)