Serves a WSGI app to browse objects based on a root object or ZODB URI.
183617
def eye(root=None, zodb_uri=None, port=8080):
    
    if root is not None:
        root_factory = lambda request: Node(root)
    elif zodb_uri is not None:
        if '://' not in zodb_uri:
            # treat it as a file://
            zodb_uri = 'file://' + os.path.abspath(zodb_uri)        
    
        from repoze.zodbconn.finder import PersistentApplicationFinder
        finder = PersistentApplicationFinder(zodb_uri, appmaker=lambda root: Node(root))
        root_factory = lambda request: finder(request.environ)
    else:
        raise RuntimeError("Must specify root object or ZODB URI.")
    
    app = Eye(root_factory)
    
    if 'DEBUG' in os.environ:
        from repoze.debug.pdbpm import PostMortemDebug
        app = PostMortemDebug(app)
    
    serve(app, host='127.0.0.1', port=port)
635816
def configure_urls(apps, index_view=None, prefixes=None):
    '''
    
    '''
    prefixes = prefixes or {}
    urlpatterns = patterns('')

    if index_view:
        from django.views.generic.base import RedirectView
        urlpatterns += patterns('',
            url(r'^$', RedirectView.as_view(pattern_name=index_view, permanent=False)),
        )

    for app_name in apps:
        app_module = importlib.import_module(app_name)
        if module_has_submodule(app_module, 'urls'):
            module = importlib.import_module("%s.urls" % app_name)
            if not hasattr(module, 'urlpatterns'):
                # Resolver will break if the urls.py file is completely blank.
                continue
            app_prefix = prefixes.get(app_name, app_name.replace("_","-"))
            urlpatterns += patterns(
                '',
                url(
                    r'^%s/' % app_prefix if app_prefix else '',
                    include("%s.urls" % app_name),
                ),
            )


    return urlpatterns
592594
def get_api_root_view(self, **kwargs):
        """"""
        class API(views.APIView):
            _ignore_model_permissions = True

            def get(self, request, *args, **kwargs):
                directory_list = get_directory(request)
                result = OrderedDict()
                for group_name, url, endpoints, _ in directory_list:
                    if url:
                        result[group_name] = url
                    else:
                        group = OrderedDict()
                        for endpoint_name, url, _, _ in endpoints:
                            group[endpoint_name] = url
                        result[group_name] = group
                return Response(result)

        return API.as_view()
1087392
def app(environ, start_response):
    
    from wsgi import container

    """Add Environ To Service Container
    Add the environ to the service container. The environ is generated by the
    the WSGI server above and used by a service provider to manipulate the
    incoming requests
    """

    container.bind('Environ', environ)

    """Execute All Service Providers That Require The WSGI Server
    Run all service provider boot methods if the wsgi attribute is true.
    """

    try:
        for provider in container.make('WSGIProviders'):
            container.resolve(provider.boot)
    except Exception as e:
        container.make('ExceptionHandler').load_exception(e)

    """We Are Ready For Launch
    If we have a solid response and not redirecting then we need to return
    a 200 status code along with the data. If we don't, then we'll have
    to return a 302 redirection to where ever the user would like go
    to next.
    """

    start_response(container.make('Request').get_status_code(),
                   container.make('Request').get_and_reset_headers())

    """Final Step
    This will take the data variable from the Service Container and return
    it to the WSGI server.
    """

    return iter([bytes(container.make('Response'), 'utf-8')])
71542
def serve(application, host='127.0.0.1', port=8080, socket=None, **options):
	
	
	# Allow either on-disk socket (recommended) or TCP/IP socket use.
	if not socket:
		bindAddress = (host, int(port))
	else:
		bindAddress = socket
	
	# Bind and start the blocking web server interface.
	WSGIServer(application, bindAddress=bindAddress, **options).run()
175033
def run(self):
        
        server_address = (self.host, self.port)
        threading = True
        if threading:
            httpd_cls = type('WSGIServer', (ThreadingMixIn, WSGIServer), {})
        else:
            httpd_cls = WSGIServer
        self.httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=False)
        wsgi_handler = get_internal_wsgi_application()
        self.httpd.set_app(wsgi_handler)
        self.is_ready.set()
        self.httpd.serve_forever()
1364650
def server(self, default_not_found=True, base_url=None):
        """"""
        falcon_api = falcon.API(middleware=self.middleware)
        default_not_found = self.documentation_404() if default_not_found is True else None
        base_url = self.base_url if base_url is None else base_url

        not_found_handler = default_not_found
        self.api._ensure_started()
        if self.not_found_handlers:
            if len(self.not_found_handlers) == 1 and None in self.not_found_handlers:
                not_found_handler = self.not_found_handlers[None]
            else:
                not_found_handler = partial(self.version_router, api_version=False,
                                            versions=self.not_found_handlers, not_found=default_not_found)
                not_found_handler.interface = True

        if not_found_handler:
            falcon_api.add_sink(not_found_handler)
            self._not_found = not_found_handler

        for sink_base_url, sinks in self.sinks.items():
            for url, extra_sink in sinks.items():
                falcon_api.add_sink(extra_sink, sink_base_url + url + '(?P<path>.*)')

        for router_base_url, routes in self.routes.items():
            for url, methods in routes.items():
                router = {}
                for method, versions in methods.items():
                    method_function = "on_{0}".format(method.lower())
                    if len(versions) == 1 and None in versions.keys():
                        router[method_function] = versions[None]
                    else:
                        router[method_function] = partial(self.version_router, versions=versions,
                                                          not_found=not_found_handler)

                router = namedtuple('Router', router.keys())(**router)
                falcon_api.add_route(router_base_url + url, router)
                if self.versions and self.versions != (None, ):
                    falcon_api.add_route(router_base_url + '/v{api_version}' + url, router)

        def error_serializer(request, response, error):
            response.content_type = self.output_format.content_type
            response.body = self.output_format({"errors": {error.title: error.description}},
                                               request, response)

        falcon_api.set_error_serializer(error_serializer)
        return falcon_api
14743
def app(environ, start_response):
    """"""
    r = HttpRequestHandler(environ, start_response, Router).dispatch()
    return r
799677
def _request(self, http_method, relative_url='', **kwargs):
        """"""
        # It could be possible to call api.resource.get('/index')
        # but it would be non-intuitive that the path would resolve
        # to root of domain
        relative_url = self._remove_leading_slash(relative_url)

        # Add default kwargs with possible custom kwargs returned by
        # before_request
        new_kwargs = self.default_kwargs().copy()
        custom_kwargs = self.before_request(
            http_method,
            relative_url,
            kwargs.copy()
        )
        new_kwargs.update(custom_kwargs)

        response = requests.request(
            http_method,
            self._join_url(relative_url),
            **new_kwargs
        )

        return self.after_request(response)
586297
def run(self, app):
        """"""
        GlimLog.info('Glim server started on %s environment' % self.args.env)
        try:
            kwargs = Config.get('app.server.options')
            run(app.wsgi,
                host=Config.get('app.server.host'),
                port=Config.get('app.server.port'),
                debug=Config.get('app.server.debugger'),
                reloader=Config.get('app.server.reloader'),
                server=Config.get('app.server.wsgi'),
                **kwargs)
        except Exception as e:
            print(traceback.format_exc())
            exit()
796486
def serve(application, host='127.0.0.1', port=8080, **options):
	
	
	# Wrap our our WSGI application (potentially stack) in a Tornado adapter.
	container = tornado.wsgi.WSGIContainer(application)
	
	# Spin up a Tornado HTTP server using this container.
	http_server = tornado.httpserver.HTTPServer(container, **options)
	http_server.listen(int(port), host)
	
	# Start and block on the Tornado IO loop.
	tornado.ioloop.IOLoop.instance().start()
20986
def get_wsgi_server(
        self, sock, wsgi_app, protocol=HttpOnlyProtocol, debug=False
    ):
        """"""
        return wsgi.Server(
            sock,
            sock.getsockname(),
            wsgi_app,
            protocol=protocol,
            debug=debug,
            log=getLogger(__name__)
        )
247030
def serveInBackground(port, serverName, prefix='/status/'):
  """"""
  import flask, threading
  from wsgiref.simple_server import make_server
  app = flask.Flask(__name__)
  registerStatsHandler(app, serverName, prefix)
  server = threading.Thread(target=make_server('', port, app).serve_forever)
  server.daemon = True
  server.start()
  return server
430298
def run(create_app, config, description=None, args=None, namespace=None, options=None):
    
    import argparse

    class HelpFormatter(
        # argparse.RawTextHelpFormatter,
        argparse.RawDescriptionHelpFormatter,
        # argparse.ArgumentDefaultsHelpFormatter,
        # argparse.HelpFormatter,
        ):
        pass

    # Get configurations data if
    envName = getattr(config, 'ENV', None)
    envMap = getattr(config, 'envMap', None)
    envHelp = getattr(config, 'envHelp', {})
    envSelectVar = getattr(config, 'envSelectVar', None)
    configurations = getattr(config, 'configurations', None)
    envSelectable = callable(getattr(config, 'select', None))
    envPrintable = config.__str__ is not object.__str__

    parser = argparse.ArgumentParser(
        description = description or getattr(config, 'description',
            'runs Flask-based web application using Python WSGI reference server'),
        epilog = ''.join((
            '\n\noptional environment variables:\n{}'.format(
                '\n'.join(sorted('  {:<20}  {}'.format(envMap[key], envHelp.get(key, ''))
                for key in envMap))) if envMap else '',
            '\n\navailable environment configurations (*: active):\n{}'.format(
                '\n'.join('{} {}'.format(
                    '*' if envName in c.names else ' ',
                    ' | '.join(c.names)
                ) for c in configurations)) if configurations else '',
        )),
        formatter_class = HelpFormatter)

    parser.add_argument('-b', '--bind', metavar='[HOST|:PORT]', default='127.0.0.1:5000',
        help = 'bind to HOST:PORT (default: 127.0.0.1:5000)')

    debug = config.DEBUG
    debugMsg = ' (default in {})'.format(config.ENV)
    debugTrueMsg = debugMsg if debug else ''
    debugFalseMsg = debugMsg if not debug else ''

    parser.add_argument('-r', '--reload', action='store_true', default=debug,
        help = 'reload server on code change' + debugTrueMsg)
    parser.add_argument('-R', '--no-reload', action='store_false', dest='reload',
        help = 'do not reload server on code change' + debugFalseMsg)

    parser.add_argument('-d', '--debug', action='store_true', default=debug,
        help = 'show debugger on exception' + debugTrueMsg)
    parser.add_argument('-D', '--no-debug', action='store_false', dest='debug',
        help = 'do not show debugger on exception' + debugFalseMsg)

    if envSelectable:
        parser.add_argument('-e', '--env', default=config.ENV,
            help = 'select environment config (default: {})'.format(config.ENV))

    if envPrintable:
        if envSelectable:
            parser.add_argument('-E', '--show-env', nargs='?', const=True,
                help = 'show environment config and exit ({}default: {})'
                    .format('*: all, ' if configurations else '', config.ENV))
        else:
            parser.add_argument('-E', '--show-env', action='store_true',
                help = 'show environment config and exit')

    parser.add_argument('-g', '--gen-key', action='store_true',
        help = 'generate a good secret key and exit')


    args = parser.parse_args(args, namespace)

    if args.gen_key:
        # See http://flask.pocoo.org/docs/0.10/quickstart/#sessions
        import os
        key = os.urandom(24)
        return print(key)
        # return print('{0}\n{0!r}'.format(key))

    if envSelectable and args.env:
        config = config.select(args.env)

    if envPrintable and args.show_env:
        if configurations and args.show_env == '*':
            print('\n\n'.join('# {}\n{}'.format(' | '.join(c.names), c) for c in configurations))
        elif args.show_env is True:
            print(config)
        else:
            print(config.select(args.show_env))

        return

    host, port = (args.bind + ':').split(':')[:2]
    host = host or '127.0.0.1'
    port = int(port) if port else 5000

    return create_app(config).run(host, port, args.debug, use_reloader=args.reload, **(options or {}))
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)
999195
def serve(self, filename):
        ''''''
        if not self.exists(filename):
            abort(404)
        return self.backend.serve(filename)
1211842
def static_serve(request, path, client):
    
    
    if msettings['SERVE_REMOTE']:
        # We're serving from S3, redirect there.
        url = client.remote_media_url().strip('/') + '/%(path)s'
        return redirect(url, permanent=True)

    if not msettings['SERVE_REMOTE'] and msettings['EMULATE_COMBO']:
        # Combo emulation is on and we're serving media locally. Try to see if
        # the given path matches a combo file defined in the JOINED dict in
        # the MEDIASYNC settings dict.
        combo_match = _find_combo_match(path)
        if combo_match:
            # We found a combo file match. Combine it and serve the result.
            return combo_serve(request, combo_match, client)

    # No combo file, but we're serving locally. Use the standard (inefficient)
    # Django static serve view.
    
    resp = serve(request, path, document_root=client.media_root, show_indexes=True)
    try:
        resp.content = client.process(resp.content, resp['Content-Type'], path)
    except KeyError:
        # HTTPNotModifiedResponse lacks the "Content-Type" key.
        pass
    return resp