wsgi application
193215
def application(env, start_response):
    
    path = env["PATH_INFO"]

    if path == "/influx.gif":
        # send response
        start_response("200 OK", [("Content-Type", "image/gif")])
        yield GIF
        # parse the query params and stick them in the queue
        params = parse_qs(env["QUERY_STRING"])
        try:
            site = params.get("site", [""])[0]
            content_id = params.get("content_id", [""])[0]
            event = params.get("event", [""])[0]
            path = params.get("path", [""])[0]
            EVENTS_QUEUE.put((site, content_id, event, path))
        except Exception as e:
            LOGGER.exception(e)

    elif path == "/pageviews.json":
        params = parse_qs(env["QUERY_STRING"])
        data, status = pageviews(params)
        start_response(status, [("Content-Type", "application/json")])
        yield data

    elif path == "/embedviews.json":
        params = parse_qs(env["QUERY_STRING"])
        data, status = embedviews(params)
        start_response(status, [("Content-Type", "application/json")])
        yield data

    elif path == "/contentids.json":
        params = parse_qs(env["QUERY_STRING"])
        data, status = content_ids(params)
        start_response(status, [("Content-Type", "application/json")])
        yield data

    elif path == "/trending.json":
        params = parse_qs(env["QUERY_STRING"])
        data, status = trending(params)
        start_response(status, [("Content-Type", "application/json")])
        yield data

    elif path == "/videoplays.json":
        params = parse_qs(env["QUERY_STRING"])
        data, status = videoplays(params)
        start_response(status, [("Content-Type", "application/json")])
        yield data

    elif path == "/embedplays.json":
        params = parse_qs(env["QUERY_STRING"])
        data, status = embedplays(params)
        start_response(status, [("Content-Type", "application/json")])
        yield data

    else:
        start_response("404 Not Found", [("Content-Type", "text/plain")])
        yield "Nothing Here"
627023
def main(global_settings, **settings):
    """"""
    my_session_factory = SignedCookieSessionFactory('itsaseekreet')
    # Add session engine
    config = Configurator(
        settings=settings,
        session_factory=my_session_factory
    )
    # Add static and templates
    config.add_static_view(name='static', path='static')
    config.include('pyramid_jinja2')
    config.add_jinja2_search_path('templates')
    config.include('ps_crud')

    # Setting up pyramid_sacrud
    config.include('pyramid_sacrud', route_prefix='admin')
    settings = config.get_settings()
    settings['pyramid_sacrud.models'] = (
        ('Docker', [Image(), ]),
    )

    # Make app
    config.scan('views')
    return config.make_wsgi_app()
501045
def build_wsgi_environ_from_event(event):
    """"""
    params = event.get('queryStringParameters')
    environ = EnvironBuilder(method=event.get('httpMethod') or 'GET',
                             path=event.get('path') or '/',
                             headers=event.get('headers') or {},
                             data=event.get('body') or b'',
                             query_string=params or {}).get_environ()
    environ['SERVER_PORT'] = 443
    if 'execute-api' in environ['HTTP_HOST']:
        # this is the API-Gateway hostname, which takes the stage as the first
        # script path component
        environ['SCRIPT_NAME'] = '/' + event['requestContext'].get('stage')
    else:
        # we are using our own hostname, nothing gets added to the script path
        environ['SCRIPT_NAME'] = ''
    environ['wsgi.url_scheme'] = 'https'
    environ['lambda.event'] = event
    return environ
854485
def strip_wsgi(request):
    """"""

    meta = copy(request.META)
    for key in meta:
        if key[:4] == 'wsgi':
            meta[key] = None
    return meta
1067698
def start(self):
        
        logging.info("HTTP server: "
                     "Starting to listen for requests on '%s:%s'..." %
                     (self.conf['addr'], self.conf['port']))

        self.my_server = MyWSGIRefServer(host=self.conf['addr'],
                                         port=self.conf['port'],
                                         romana_http=self)

        self.http_thread = threading.Thread(
                    target = APP.run,
                    name   = "HTTP",
                    kwargs = {"quiet" : True, "server" : self.my_server})

        self.http_thread.daemon = True
        self.http_thread.start()
        time.sleep(1)
        if not self.wsgi_server_started:
            # Set the global flag indicating that everything should stop
            CURRENT_STATE._stop_all = True
587638
def application(self, name, context_root, path):
	
		
		
		return Application(self.__endpoint, name, context_root, path)
945543
def serve(config):
    ""
    from gevent.pywsgi import WSGIServer

    app = make_app(config=config)

    host = app.config.get("HOST", '127.0.0.1')
    port = app.config.get("PORT", 5000)
    http_server = WSGIServer((host, port), app)
    http_server.serve_forever()
1136824
def deploy_webconf():
    
    deployed = []
    log_dir = '/'.join([deployment_root(),'log'])
    #TODO - incorrect - check for actual package to confirm installation
    if webserver_list():
        if env.verbosity:
            print env.host,"DEPLOYING webconf:"
        if not exists(log_dir):
            run('ln -s /var/log log')
        #deploys confs for each domain based on sites app
        if 'apache2' in get_packages():
            deployed += _deploy_webconf('/etc/apache2/sites-available','django-apache-template.txt')
            deployed += _deploy_webconf('/etc/nginx/sites-available','nginx-template.txt')
        elif 'gunicorn' in get_packages():
            deployed += _deploy_webconf('/etc/nginx/sites-available','nginx-gunicorn-template.txt')
        
        if not exists('/var/www/nginx-default'):
            sudo('mkdir /var/www/nginx-default')
        upload_template('woven/maintenance.html','/var/www/nginx-default/maintenance.html',use_sudo=True)
        sudo('chmod ugo+r /var/www/nginx-default/maintenance.html')
    else:
        print env.host,"""WARNING: Apache or Nginx not installed"""
        
    return deployed
794864
async def request(self):
        '''
        '''
        request_headers = self.request_headers()
        environ = self.environ
        method = environ['REQUEST_METHOD']
        data = None
        if method in ENCODE_BODY_METHODS:
            data = DataIterator(self)
        http = self.wsgi.http_client
        try:
            await http.request(method,
                               environ['RAW_URI'],
                               data=data,
                               headers=request_headers,
                               version=environ['SERVER_PROTOCOL'],
                               pre_request=self.pre_request)
        except Exception as exc:
            self.error(exc)
39064
def run_web(self, flask, host='127.0.0.1', port=5000, **options):
        # type: (Zsl, str, int, **Any)->None
        """"""
        return flask.run(
            host=flask.config.get('FLASK_HOST', host),
            port=flask.config.get('FLASK_PORT', port),
            debug=flask.config.get('DEBUG', False),
            **options
        )
505971
def apache_config(config, outputfile):
    '''
        
    '''
    if os.path.exists(outputfile):
        os.rename(outputfile, outputfile + ".old")
        print("Renamed existing Apache config file to " + outputfile + ".old")

    from django.conf import settings
    f = open(outputfile, 'w')
    print("Generating Apache configuration in " + outputfile)
    subdir = (len(settings.HOST_DIR) > 0)
    text = """
    # OpenSubmit Configuration for Apache 2.4
    # These directives are expected to live in some <VirtualHost> block
    """
    if subdir:
        text += "Alias /%s/static/ %s\n" % (settings.HOST_DIR,
                                            settings.STATIC_ROOT)
        text += "    WSGIScriptAlias /%s %s/wsgi.py\n" % (
            settings.HOST_DIR, settings.SCRIPT_ROOT)
    else:
        text += "Alias /static/ %s\n" % (settings.STATIC_ROOT)
        text += "    WSGIScriptAlias / %s/wsgi.py" % (settings.SCRIPT_ROOT)
    text += """
    WSGIPassAuthorization On
    <Directory {static_path}>
         Require all granted
    </Directory>
    <Directory {install_path}>
         <Files wsgi.py>
              Require all granted
         </Files>
    </Directory>
    """.format(static_path=settings.STATIC_ROOT, install_path=settings.SCRIPT_ROOT)

    f.write(text)
    f.close()
30558
def run_gunicorn(application: WSGIHandler, gunicorn_module_name: str = 'gunicorn_prod'):
    
    from gunicorn.app.base import Application

    class DjangoApplication(Application):
        def init(self, parser, opts, args):
            cfg = self.get_config_from_module_name(gunicorn_module_name)
            clean_cfg = {}
            for k, v in cfg.items():
                # Ignore unknown names
                if k not in self.cfg.settings:
                    continue
                clean_cfg[k.lower()] = v
            return clean_cfg

        def load(self) -> WSGIHandler:
            return application

    return DjangoApplication().run()
3813
def create_gw_response(app, wsgi_env):
    
    response = {}
    buf = []
    result = []

    def start_response(status, headers, exc_info=None):
        result[:] = [status, headers]
        return buf.append

    appr = app(wsgi_env, start_response)
    close_func = getattr(appr, 'close', None)
    try:
        buf.extend(list(appr))
    finally:
        close_func and close_func()

    response['body'] = ''.join(buf)
    response['statusCode'] = result[0].split(' ', 1)[0]
    response['headers'] = {}

    for k, v in result[1]:
        response['headers'][k] = v
    if 'Content-Length' not in response['headers']:
        response['headers']['Content-Length'] = str(len(response['body']))
    if 'Content-Type' not in response['headers']:
        response['headers']['Content-Type'] = 'text/plain'
    return response
96181
def _init_wsgi_server(self):
        
        self.wsgi_server = None

        if self.httpd.active:
            # Only import dependencies when server is active
            from waitress.server import WSGIServer
            from pyrocore.daemon import webapp

            # Set up WSGI stack
            wsgi_app = webapp.make_app(self.httpd)
#            try:
#                import wsgilog
#            except ImportError:
#                self.LOG.info("'wsgilog' middleware not installed")
#            else:
#                wsgi_app = wsgilog.WsgiLog(wsgi_app, **self.httpd.wsgilog)

            ##logging.getLogger('waitress').setLevel(logging.DEBUG)
            self.LOG.debug("Waitress config: %r" % self.httpd.waitress)
            self.wsgi_server = WSGIServer(wsgi_app, **self.httpd.waitress)
            self.LOG.info("Started web server at %s://%s:%d/" % (
                self.httpd.waitress.url_scheme,
                self.wsgi_server.get_server_name(self.wsgi_server.effective_host),
                int(self.wsgi_server.effective_port),
            ))
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__)
        )
670029
def shell(filepath, wsgiapp, interpreter, models):
    
    model_base_classes = get_model_base_classes()
    imported_objects = {}

    if models and model_base_classes:
        insert_import_path_to_sys_modules(filepath)

        for module in find_modules_from_path(filepath):
            for name in dir(module):
                if name.startswith('_'):
                    continue
                obj = getattr(module, name)
                if isinstance(obj, model_base_classes):
                    key = name.split('.')[-1] if '.' in name else name
                    if key in imported_objects:
                        continue
                    imported_objects[key] = obj

    module = SourceFileLoader('module', filepath).load_module()
    imported_objects['app'] = getattr(module, wsgiapp)

    for key in imported_objects.keys():
        click.secho("import {}".format(key), fg='green')
    run_python(interpreter, imported_objects)
634471
def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080,
        interval=1, reloader=False, **kargs):
    
    app = app if app else default_app()
    quiet = bool(kargs.get('quiet', False))
    # Instantiate server, if it is a class instead of an instance
    if isinstance(server, type):
        server = server(host=host, port=port, **kargs)
    if not isinstance(server, ServerAdapter):
        raise RuntimeError("Server must be a subclass of WSGIAdapter")
    if not quiet and isinstance(server, ServerAdapter): # pragma: no cover
        if not reloader or os.environ.get('BOTTLE_CHILD') == 'true':
            print("Bottle server starting up (using %s)..." % repr(server))
            print("Listening on http://%s:%d/" % (server.host, server.port))
            print("Use Ctrl-C to quit.")
            print()
        else:
            print("Bottle auto reloader starting up...")
    try:
        if reloader and interval:
            reloader_run(server, app, interval)
        else:
            server.run(app)
    except KeyboardInterrupt:
        if not quiet: # pragma: no cover
            print("Shutting Down...")