A basic WSGI app
337497
def wsgi_app(self, environ, start_response):
        """"""
        @_LOCAL_MANAGER.middleware
        def _wrapped_app(environ, start_response):
            request = Request(environ)
            setattr(_local, _CURRENT_REQUEST_KEY, request)
            response = self._dispatch_request(request)
            return response(environ, start_response)
        return _wrapped_app(environ, start_response)
726748
def main():
    

    # Log info and above to console
    logging.basicConfig(
        format='%(levelname)s: %(message)s', level=logging.INFO)

    # Get command line input/output arguments
    msg = 'Instantly deploy static HTML sites to S3 at the command line.'
    parser = argparse.ArgumentParser(description=msg)
    parser.add_argument(
        'www_dir',
        help='Directory containing the HTML files for your website.'
    )
    parser.add_argument(
        'bucket_name',
        help='Name of S3 bucket to deploy to, e.g. mybucket.'
    )
    args = parser.parse_args()

    # Deploy the site to S3!
    deploy(args.www_dir, args.bucket_name)
713758
def init_app(self, app):
        '''
        '''
        self.app = app
        self._session_conf = app.config.get('BEAKER_SESSION', {
            'session.type': 'file',
            'session.data_dir': '/tmp/session/data',
            'session.lock_dir': '/tmp/session/lock'
        })
        app.wsgi_app = SessionMiddleware(app.wsgi_app, self._session_conf)
        app.session_interface = BeakerSessionInterface()
320380
def make_wsgi_app(registry=REGISTRY):
    """"""

    def prometheus_app(environ, start_response):
        params = parse_qs(environ.get('QUERY_STRING', ''))
        r = registry
        encoder, content_type = choose_encoder(environ.get('HTTP_ACCEPT'))
        if 'name[]' in params:
            r = r.restricted_registry(params['name[]'])
        output = encoder(r)

        status = str('200 OK')
        headers = [(str('Content-type'), content_type)]
        start_response(status, headers)
        return [output]

    return prometheus_app
1202592
def run(cls, routes, *args, **kwargs): # pragma: no cover
    

    app = init(cls, routes, *args, **kwargs)

    HOST = os.getenv('HOST', '0.0.0.0')
    PORT = int(os.getenv('PORT', 8000))

    aiohttp.web.run_app(app, port=PORT, host=HOST)
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()
949080
def simple(application, host='127.0.0.1', port=8080):
	
	
	# Try to be handy as many terminals allow clicking links.
	print("serving on http://{0}:{1}".format(host, port))
	
	# Bind and launch the server; this is a blocking operation.
	make_server(host, int(port), application).serve_forever()
1227283
def run_apps(app_lists):
        
        app_mgr = AppManager.get_instance()
        app_mgr.load_apps(app_lists)
        contexts = app_mgr.create_contexts()
        services = app_mgr.instantiate_apps(**contexts)
        webapp = wsgi.start_service(app_mgr)
        if webapp:
            services.append(hub.spawn(webapp))
        try:
            hub.joinall(services)
        finally:
            app_mgr.close()
            for t in services:
                t.kill()
            hub.joinall(services)
            gc.collect()
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()
1316817
def main(global_config, **settings):
    
    engine = engine_from_config(settings, 'sqlalchemy.')
    initialize_sql(engine)
    config = Configurator(settings=settings)
    config.add_static_view('static', 'pyramidraptorized:static', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_view('pyramidraptorized.views.my_view',
                    route_name='home',
                    renderer='templates/mytemplate.pt')
    app = config.make_wsgi_app()
    app = raptorizemw.make_middleware(app)
    return app
1038707
def create_app():
    
    
    # Setup Flask and load app.config
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Setup Flask-MongoEngine
    db = MongoEngine(app)

    # Define the User document.
    # NB: Make sure to add flask_user UserMixin !!!
    class User(db.Document, UserMixin):
        active = db.BooleanField(default=True)

        # User authentication information
        username = db.StringField(default='')
        password = db.StringField()

        # User information
        first_name = db.StringField(default='')
        last_name = db.StringField(default='')

        # Relationships
        roles = db.ListField(db.StringField(), default=[])

    # Setup Flask-User and specify the User data-model
    user_manager = UserManager(app, db, User)

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        # String-based templates
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Home page</h2>
                <p><a href={{ url_for('user.register') }}>Register</a></p>
                <p><a href={{ url_for('user.login') }}>Sign in</a></p>
                <p><a href={{ url_for('home_page') }}>Home page</a> (accessible to anyone)</p>
                <p><a href={{ url_for('member_page') }}>Member page</a> (login required)</p>
                <p><a href={{ url_for('user.logout') }}>Sign out</a></p>
            {% endblock %}
            """)

    # The Members page is only accessible to authenticated users via the @login_required decorator
    @app.route('/members')
    @login_required    # User must be authenticated
    def member_page():
        # String-based templates
        return render_template_string("""
            {% extends "flask_user_layout.html" %}
            {% block content %}
                <h2>Members page</h2>
                <p><a href={{ url_for('user.register') }}>Register</a></p>
                <p><a href={{ url_for('user.login') }}>Sign in</a></p>
                <p><a href={{ url_for('home_page') }}>Home page</a> (accessible to anyone)</p>
                <p><a href={{ url_for('member_page') }}>Member page</a> (login required)</p>
                <p><a href={{ url_for('user.logout') }}>Sign out</a></p>
            {% endblock %}
            """)

    return app
559319
def main(args=None):
    
    logger = cfg.configureLogger()
    for root, dirs, files in os.walk(cfg.dataDir):
        for dir in dirs:
            newDir = os.path.join(root, dir)
            try:
                os.removedirs(newDir)
                logger.info("Deleted empty dir " + str(newDir))
            except:
                pass

    if cfg.useTwisted:
        import logging
        logger = logging.getLogger('analyser.twisted')
        from twisted.internet import reactor
        from twisted.web.resource import Resource
        from twisted.web import static, server
        from twisted.web.wsgi import WSGIResource
        from twisted.application import service
        from twisted.internet import endpoints

        class ReactApp:
            """
            Handles the react app (excluding the static dir).
            """

            def __init__(self, path):
                # TODO allow this to load when in debug mode even if the files don't exist
                self.publicFiles = {f: static.File(os.path.join(path, f)) for f in os.listdir(path) if
                                    os.path.exists(os.path.join(path, f))}
                self.indexHtml = ReactIndex(os.path.join(path, 'index.html'))

            def getFile(self, path):
                """
                overrides getChild so it always just serves index.html unless the file does actually exist (i.e. is an
                icon or something like that)
                """
                return self.publicFiles.get(path.decode('utf-8'), self.indexHtml)

        class ReactIndex(static.File):
            """
            a twisted File which overrides getChild so it always just serves index.html (NB: this is a bit of a hack, 
            there is probably a more correct way to do this but...)
            """

            def getChild(self, path, request):
                return self

        class FlaskAppWrapper(Resource):
            """
            wraps the flask app as a WSGI resource while allow the react index.html (and its associated static content)
            to be served as the default page.
            """

            def __init__(self):
                super().__init__()
                self.wsgi = WSGIResource(reactor, reactor.getThreadPool(), app)
                import sys
                if getattr(sys, 'frozen', False):
                    # pyinstaller lets you copy files to arbitrary locations under the _MEIPASS root dir
                    uiRoot = sys._MEIPASS
                else:
                    # release script moves the ui under the analyser package because setuptools doesn't seem to include
                    # files from outside the package
                    uiRoot = os.path.dirname(__file__)
                logger.info('Serving ui from ' + str(uiRoot))
                self.react = ReactApp(os.path.join(uiRoot, 'ui'))
                self.static = static.File(os.path.join(uiRoot, 'ui', 'static'))

            def getChild(self, path, request):
                """
                Overrides getChild to allow the request to be routed to the wsgi app (i.e. flask for the rest api 
                calls),
                the static dir (i.e. for the packaged css/js etc), the various concrete files (i.e. the public 
                dir from react-app) or to index.html (i.e. the react app) for everything else.
                :param path: 
                :param request: 
                :return: 
                """
                if path == b'api':
                    request.prepath.pop()
                    request.postpath.insert(0, path)
                    return self.wsgi
                elif path == b'static':
                    return self.static
                else:
                    return self.react.getFile(path)

            def render(self, request):
                return self.wsgi.render(request)

        application = service.Application('analyser')
        site = server.Site(FlaskAppWrapper())
        endpoint = endpoints.TCP4ServerEndpoint(reactor, cfg.getPort(), interface='0.0.0.0')
        endpoint.listen(site)
        reactor.run()
    else:
        # get config from a flask standard place not our config yml
        app.run(debug=cfg.runInDebug(), host='0.0.0.0', port=cfg.getPort())
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)
615690
def main():
    # config file
    conf = Config()
    actions = []

    debuglevel = logging.ERROR
    for it in sys.argv[1:]:
        if it == ("-v"):
            debuglevel = logging.WARNING
        elif it == ("-vv"):
            debuglevel = logging.INFO
        elif it == ("-vvv"):
            debuglevel = logging.DEBUG
        if it == ("--valid"):
            actions.append("valid")

    conf.debuglevel = debuglevel

    srv = ServerApp(conf)
    status = srv.login(conf.token)

    if not status:
        sys.exit(100)

    # pick up and run events
    
    srv.do_all_actions(conf)

    """ send data for monitoring """
    if conf.monitoring:
        srv.monitoring()

    """ create repo for web project - apache2/uwsgi"""
    if conf.webproject:
        #data =  srv.get_all_projects()
        #content = aray2xml(data)

        """ Check all repository on this system. """
        srv.check_repo_all()

        """ Recount size of full disk in all project on this system. """
        srv.check_size_all()

        """ reset owners for projects """
        srv.check_rights()

        """ check running services """
        srv.check_services()

        mng = manager(conf)
        for it in actions:
            fc = getattr(mng, it)
            fc()
778520
def _work(self):
        """"""
        server = wsgi.Server(
            name=self._AGENT_BINARY,
            num_threads=CONF.AGENT.worker_count)
        server.start(
            application=_MetadataProxyHandler(),
            port=CONF.bind_port,
            host=CONF.bind_host)
        server.wait()
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()
519174
def main():
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-H", "--host", help="Web server Host address to bind to",
                        default="0.0.0.0", action="store", required=False)
    parser.add_argument("-p", "--port", help="Web server Port to bind to",
                        default=8080, action="store", required=False)
    args = parser.parse_args()

    logging.basicConfig()
    run(host=args.host, port=args.port, reloader=True, server=SERVER)