def make_app(global_conf, **app_conf):
        """Returns a Sync Server Application."""
        global_conf.update(app_conf)
        params = convert_config(global_conf)
        app = klass(urls, controllers, params, auth_class)

        if params.get('debug', False):
            app = TransLogger(app, logger_name='syncserver',
                              setup_console_handler=True)

        if params.get('profile', False):
            from repoze.profile.profiler import AccumulatingProfileMiddleware
            app = AccumulatingProfileMiddleware(app,
                                          log_filename='profile.log',
                                          cachegrind_filename='cachegrind.out',
                                          discard_first_request=True,
                                          flush_at_shutdown=True,
                                          path='/__profile__')

        if params.get('client_debug', False):
            # errors are displayed in the user client
            app = ErrorMiddleware(app, debug=True,
                                  show_exceptions_in_wsgi_errors=True)
        else:
            # errors are logged and a 500 is returned with an empty body
            # to avoid any security whole
            app = CatchErrorMiddleware(app, logger_name='syncserver')

        if wrapper is not None:
            app = wrapper(app)
        return app
Example #2
0
    def run(self, netloc='0.0.0.0:9090', reload=True, log=True):
        """Run the CherryPy server."""
        from django.conf import settings
        from django.core.handlers.wsgi import WSGIHandler
        from paste.translogger import TransLogger

        url_parts = urlparse.urlsplit(netloc)
        host = "0.0.0.0"
        port = 9090
        cherrypy.config.update({
            'server.socket_host': host,
            'server.socket_port': port,
            'log.screen': False,
            'engine.autoreload.on': reload,
            'log.access_file': cherry_access_log,
            'log.error_file': cherry_error_log,
        })
        self.cfg_assets(settings.MEDIA_URL, settings.MEDIA_ROOT)
        self.cfg_assets(settings.STATIC_URL, settings.STATIC_ROOT)
        self.cfg_favicon(settings.STATIC_ROOT)
        app = WSGIHandler()
        app = TransLogger(app,
                          logger_name='cherrypy.access',
                          setup_console_handler=False)
        if self.domains:
            app = cherrypy.wsgi.VirtualHost(app, self.domains)
        cherrypy.tree.graft(app)
        cherrypy.engine.start()
Example #3
0
	def run(self):
		logger = "restServer"
		log = logging.getLogger(logger)
		log.info("REST Server started")
		self.mysql_conn = None
		self.mysql_cursor = None
		self.configDBSession = None
		self.configDBEngine = None
		self.debugLogLevel = False

		if logging.root.level == 10:        # DEBUG
			self.debugLogLevel = True

		restAddress = configuration.get("Server", "restServer_address")
		restPort = configuration.get("Server", "restServer_port")

		if restAddress.strip() != "" and restPort.strip() != "":
			app = Flask("restServer")
			api = Api(app)
			api.add_resource(restRoot, '/')
			api.add_resource(restStatus, '/status')
			api.add_resource(restJdbcConnections, '/jdbc_connections')

			log.info("Starting RESTserver on %s:%s"%(restAddress, restPort))
			serve(
				TransLogger(app, setup_console_handler=False, logger=logging.getLogger("restServerAccess")), 
				host=restAddress, 
				port=restPort, 
				ident="DBImport REST Server", 
				url_scheme='https',
				_quiet=True)
Example #4
0
def sesam_logger(logger_name, timestamp=False, app=None):
    if logger_name is None or logger_name is '':
        raise ValueError('Please provide the valid logger name.')
    logger = logging.getLogger(logger_name)
    log_level = os.getenv('LOG_LEVEL')
    level = logging.getLevelName(
        log_level.upper()) if log_level is not None else None
    stdout_handler = logging.StreamHandler()
    stdout_handler.setFormatter(
        logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            if timestamp else '%(name)s - %(levelname)s - %(message)s'))
    logger.addHandler(stdout_handler)
    if not isinstance(level, int):
        logger.warning(
            "Unsupported value or no LOG_LEVEL provided. Hence, setting default log level to INFO."
        )
        level = logging.INFO
    logger.setLevel(level)

    if app:
        wsgi_log_format_string = (
            '"%(REQUEST_METHOD)s %(REQUEST_URI)s %(HTTP_VERSION)s" '
            '%(status)s %(bytes)s')

        app.wsgi_app = TransLogger(app.wsgi_app,
                                   logger_name=logger.name,
                                   format=wsgi_log_format_string,
                                   setup_console_handler=False,
                                   set_logger_level=logger.level)

    return logger
def run():
    format_logger = '[%(time)s] %(status)s %(REQUEST_METHOD)s %(REQUEST_URI)s'
    serve(TransLogger(app, format=format_logger),
          host='0.0.0.0',
          port=8080,
          url_scheme='https',
          ident=None)
Example #6
0
def run():
    waitress.serve(
        TransLogger(app, setup_console_handler=False),
        host=env.WAITRESS_HOST,
        port=env.WAITRESS_PORT,
        threads=env.WAITRESS_THREADS,
    )
Example #7
0
  def start_server(self):
    app = self.app

    @app.route('/subtitles.vtt')
    def subtitles():
      # response = bottle.static_file(self.subtitles_fn, root='/', mimetype='text/vtt')
      response = bottle.response
      response.headers['Access-Control-Allow-Origin'] = '*'
      response.headers['Access-Control-Allow-Methods'] = 'GET, HEAD'
      response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
      response.headers['Content-Type'] = 'text/vtt'
      return self.subtitles
    
    @app.get('/media/<id>.<ext>')
    def video(id, ext):
      print(list(bottle.request.headers.items()))
      print('self.transcoder.fn', self.transcoder.fn)
      ranges = list(bottle.parse_range_header(bottle.request.environ['HTTP_RANGE'], 1000000000000))
      print('ranges', ranges)
      offset, end = ranges[0]
      self.transcoder.wait_for_byte(offset)
      response = bottle.static_file(self.transcoder.fn, root='/')
      if 'Last-Modified' in response.headers:
        del response.headers['Last-Modified']
      response.headers['Access-Control-Allow-Origin'] = '*'
      response.headers['Access-Control-Allow-Methods'] = 'GET, HEAD'
      response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
      return response

    # app.run(host=self.ip, port=self.port, server='paste', daemon=True)
    from paste import httpserver
    from paste.translogger import TransLogger
    handler = TransLogger(app, setup_console_handler=True)
    httpserver.serve(handler, host=self.ip, port=str(self.port), daemon_threads=True)
Example #8
0
 def run_server(self):
     if super().start_app():
         LISTEN = f"127.0.0.1:{8080}"
         serve(TransLogger(application=App.create_app_instance([HeartBeat]),
                           logger=AppLogger.logger,
                           setup_console_handler=True)
               , listen=LISTEN)
def start_cherrypy(app,
                   host=None,
                   port=None,
                   ssl_cert_file=None,
                   ssl_key_file=None,
                   is_dev_env=None):

    if not is_dev_env:
        cherrypy.config.update({'environment': 'production'})

    cherrypy.config.update(config.get_cherrypy_config())

    cherrypy.config.update({
        'log.screen': False,
        'server.socket_port': port,
        'server.socket_host': host,
        'server.ssl_certificate': ssl_cert_file,
        'server.ssl_private_key': ssl_key_file
    })

    app_logged = TransLogger(app.wsgi_app, setup_console_handler=False)
    cherrypy.tree.graft(app_logged, '/')

    if not is_dev_env:
        Daemonizer(cherrypy.engine).subscribe()
        PIDFile(cherrypy.engine,
                os.path.join(util.get_user_directory(),
                             PID_FILE_NAME)).subscribe()

    cherrypy.engine.start()
    cherrypy.engine.block()
Example #10
0
    def run(self, netloc='localhost:8000', reload=True, log=True):
        """Run the CherryPy server."""
        from django.conf import settings
        from django.core.handlers.wsgi import WSGIHandler
        from paste.translogger import TransLogger

        host, port = urllib.splitnport(netloc, 80)
        host = socket.gethostbyname(host)
        cherrypy.config.update({
            'server.socket_host': host,
            'server.socket_port': port,
            'log.screen': log,
            'engine.autoreload_on': reload,
        })
        self.cfg_assets(settings.MEDIA_URL, settings.MEDIA_ROOT)
        self.cfg_assets(settings.STATIC_URL, settings.STATIC_ROOT)
        self.cfg_favicon(settings.STATIC_ROOT)
        app = WSGIHandler()
        app = TransLogger(app,
                          logger_name='cherrypy.access',
                          setup_console_handler=False)
        if self.domains:
            app = cherrypy.wsgi.VirtualHost(app, self.domains)
        cherrypy.tree.graft(app)
        cherrypy.engine.start()
        cherrypy.engine.block()
Example #11
0
def make_app():
    from webob import Response
    import static
    static_app = static.Cling(c.static_dir)
    if c.static_override:
        from paste.cascade import Cascade
        static_app = Cascade([static.Cling(c.static_override), static_app])

    docs_app = pathpopper_middleware(static.Cling(c.docs_dir))
    code_app = pathpopper_middleware(static.Cling(c.static_dir + "/js"), 2)

    register("^/docs/code/", code_app)
    register("^/docs/", docs_app)

    for location, directory in c.static_map.items():
        topop = 1 + location.count('/')
        more_static = pathpopper_middleware(static.Cling(directory), topop)
        register("^/%s/" % location, more_static)

    app = URLRelay(default=static_app)
    app = auth_tkt.AuthTKTMiddleware(app,
                                     c.secret,
                                     secure=c.secure_cookie,
                                     include_ip=False,
                                     httponly=c.http_only_cookie,
                                     current_domain_cookie=True,
                                     wildcard_cookie=True)
    app = db_middleware(app)

    if c.log_requests_to_stdout:
        from paste.translogger import TransLogger
        app = TransLogger(app)

    app = scriptwrapper_middleware(app)
    return app
Example #12
0
    def run():
        """Funcion encargada de correr el servicio con Waitress"""
        config = configparser.ConfigParser()
        config.read('.conf')
        configurate = config['ENVIRONMENT']
        os.system('cls')
        logger = logging.getLogger('waitress')

        formato = ('%(REMOTE_ADDR)s,[%(time)s],'
                   '%(REQUEST_METHOD)s,%(REQUEST_URI)s,%(HTTP_VERSION)s,'
                   '%(status)s,%(bytes)s,%(HTTP_REFERER)s,%(HTTP_USER_AGENT)s')

        fh = logging.handlers.RotatingFileHandler(
            './storage/logs/log.csv',
            maxBytes=config['LOGS'].getint('maxBytes'),
            backupCount=config['LOGS'].getint('backupCount'))
        logger.addHandler(fh)
        logger.setLevel(logging.DEBUG)
        HOST = configurate['server']
        PORT = configurate['port']
        pid = os.getpid()
        py = psutil.Process(pid)
        memoryUse = py.memory_info()[0] / 2.**30  # memory use in GB...I think
        print('memory use:', memoryUse)
        serve(TransLogger(app,
                          setup_console_handler=True,
                          logger=logger,
                          format=formato),
              host=HOST,
              port=PORT)
Example #13
0
    def run_server(self, app):
        try:
            import cherrypy
            from paste.translogger import TransLogger

        except ImportError:
            print "Cherrypy and paste are required."
            return

        # Enable WSGI access logging via Paste
        app_logged = TransLogger(app)

        # Mount the WSGI callable object (app) on the root directory
        cherrypy.tree.graft(app_logged, '/')
        cherrypy.tree.mount(
            None, '/static', {
                '/': {
                    'tools.staticdir.dir': app.static_folder,
                    'tools.staticdir.on': True,
                }
            })

        # Set the configuration of the web server
        cherrypy.config.update({
            'engine.autoreload.on': True,
            'log.screen': True,
            'server.socket_port': self.port,
            'server.socket_host': self.host
        })

        # Start the CherryPy WSGI web server

        cherrypy.engine.start()
        cherrypy.engine.block()
Example #14
0
def run_server():
    global app

    port = 8090
    print('Listening on port:', port)

    serve(TransLogger(app), host='0.0.0.0', port=port)
Example #15
0
def serve(entrypoint: str, location: str, deps: str, wsgi: bool, host: str,
          port: int) -> typing.Any:
    """CLI serve."""
    if deps:
        click.echo(f"Installing deps: {deps}")
        _deps(deps, location)

    signal.signal(signal.SIGTERM, handle_sigterm)

    app = ps.generate_app()
    app = ps.append_entrypoint(app, entrypoint, os.path.abspath(location))

    if not wsgi:
        click.echo("Starting Flask Development server")
        app.run(
            host=os.getenv("DPLOY_KICKSTART_HOST", "0.0.0.0"),
            port=int(os.getenv("DPLOY_KICKSTART_PORT", 8080)),
        )
    else:
        click.echo("Starting Waitress server")
        waitress_serve(
            TransLogger(app, setup_console_handler=False),
            host=os.getenv("dploy_kickstart_HOST", "0.0.0.0"),
            port=int(os.getenv("dploy_kickstart_PORT", 8080)),
        )
Example #16
0
def make_app(global_conf, full_stack=True, static_files=True, **app_conf):
    """Create a Pylons WSGI application and return it

    ``global_conf``
        The inherited configuration for this application. Normally from
        the [DEFAULT] section of the Paste ini file.

    ``full_stack``
        Whether this application provides a full WSGI stack (by default,
        meaning it handles its own exceptions and errors). Disable
        full_stack when this application is "managed" by another WSGI
        middleware.

    ``static_files``
        Whether this application serves its own static files; disable
        when another web server is responsible for serving them.

    ``app_conf``
        The application's local configuration. Normally specified in
        the [app:<name>] section of the Paste ini file (where <name>
        defaults to main).

    """
    # Configure the Pylons environment
    config = load_environment(global_conf, app_conf)

    # The Pylons WSGI app
    app = PylonsApp(config=config)

    # Routing/Session/Cache Middleware
    app = RoutesMiddleware(app, config['routes.map'], singleton=False)
    app = SessionMiddleware(app, config)

    # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares)
    format = ('%(REMOTE_ADDR)s - %(REMOTE_USER)s [%(time)s] '
              '"%(REQUEST_METHOD)s %(REQUEST_URI)s %(HTTP_VERSION)s" '
              '%(status)s %(bytes)s')
    app = TransLogger(app, format=format, logger_name="access")

    if asbool(full_stack):
        # Handle Python exceptions
        app = ErrorHandler(app, global_conf, **config['pylons.errorware'])

        # Display error documents for 401, 403, 404 status codes (and
        # 500 when debug is disabled)
        if asbool(config['debug']):
            app = StatusCodeRedirect(app)
        else:
            app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])

    # Establish the Registry for this application
    app = RegistryManager(app)

    if asbool(static_files):
        # Serve static files
        static_app = StaticURLParser(config['pylons.paths']['static_files'])
        app = Cascade([static_app, app])
    app.config = config
    return app
Example #17
0
def enable_translogger(app):
    """Makes `wsgi` logger which uses `access_log` handler enable.

    Same as to add `translogger` into [pipeline:main] section.
    """
    # pylint: disable=relative-import
    from paste.translogger import TransLogger
    return TransLogger(app, setup_console_handler=False)
Example #18
0
 def run(self, handler):
     # Send parameter start_loop=false so we can put the paste server in a
     # variable for later stopping.
     handler = TransLogger(handler, setup_console_handler=(not self.quiet))
     self.paste = httpserver.serve(
         handler, host=self.host, port=str(self.port), start_loop=False
     )
     self.paste.serve_forever()
Example #19
0
 def run(self, handler):  # pragma: no cover
     from paste import httpserver
     from paste.translogger import TransLogger
     handler = TransLogger(handler, setup_console_handler=(not self.quiet))
     httpserver.serve(handler,
                      host=self.host,
                      port=str(self.port),
                      **self.options)
Example #20
0
 def run(self, handler):
     from paste import httpserver
     from paste.translogger import TransLogger
     app = TransLogger(handler)
     httpserver.serve(app,
                      host=self.host,
                      port=str(self.port),
                      **self.options)
Example #21
0
 def run_server(self):
     if super().start_app():
         LISTEN = f"127.0.0.1:{5800}"
         serve(TransLogger(application=App.create_app_instance([HeartBeat, Read, Execute, UpsertByRecord,
                                                                ExtractToCsv, LoadFromCsv]),
                           logger=AppLogger.logger,
                           setup_console_handler=True)
               , listen=LISTEN)
Example #22
0
def build_wsgi_app(raml_file):
    # read raml, create router
    raml = ramlfications.parse(raml_file)
    resources = api.transform_resources(raml, raml.resources)
    resources = filter(filter_absent_method, resources)
    app = build_server(resources)
    print app.map
    app = TransLogger(app, setup_console_handler=False)
    return app
Example #23
0
def get_wsgi_server():
    flower_app = Flower(capp=scheduler,
                        options=default_options,
                        handlers=handlers,
                        **settings)
    wsgi_app = tornado.wsgi.WSGIAdapter(flower_app)
    wsgi_app = ErrorMiddleware(wsgi_app, debug=debug_flag)
    wsgi_app = TransLogger(wsgi_app, setup_console_handler=debug_flag)

    return wsgi_app
Example #24
0
def run_server(wsgi_app, global_conf, host='localhost', port=8080):
    from wsgiutils import wsgiServer
    logged_app = TransLogger(wsgi_app)
    port = int(port)
    # For some reason this is problematic on this server:
    ensure_port_cleanup([(host, port)], maxtries=2, sleeptime=0.5)
    app_map = {'': logged_app}
    server = wsgiServer.WSGIServer((host, port), app_map)
    logged_app.logger.info('Starting HTTP server on http://%s:%s', host, port)
    server.serve_forever()
Example #25
0
def start(known_args):
    """
    Start application in server mode to serve incoming HTTP requests and process data received from clients.

    :param known_args: The argument parser namespace object with supplied arguments.
    :type known_args: :obj:`argparse.Namespace`
    """
    bind_address = '{}:{}'.format(known_args.ipv4, known_args.port)
    logging.info(msg=f'starting application on {bind_address}')
    serve(app=TransLogger(application=create_app()), listen=bind_address)
Example #26
0
def run_server(app):
    app_logged = TransLogger(app)
    cherrypy.tree.graft(app_logged, '/')
    cherrypy.config.update({
        'engine.autoreload.on': True,
        'log.screen': True,
        'server.socker_port': 8099,
        'server.socker_host': '0.0.0.0'
    })
    cherrypy.engine.start()
    cherrypy.engine.block()
Example #27
0
def _run_server(app, port):
    server = luchador.util.create_server(TransLogger(app), port=port)
    app.attr['server'] = server
    _LG.info('Starting server on port %d', port)
    try:
        server.start()
    except KeyboardInterrupt:
        pass
    finally:
        server.stop()
        _LG.info('Server on port %d stopped.', port)
Example #28
0
def run_server(app):
    app_logged = TransLogger(application=app)
    tree.graft(app_logged, '/')
    config.update({
        'engine.autoreload.on': True,
        'log.screen': True,
        'server.socket_port': 5432,
        'server.socket_host': '0.0.0.0'
    })
    engine.start()
    engine.block()
Example #29
0
def cli(ctx):
    if ctx.invoked_subcommand is None:
        if env.APP_ENV == 'prod':
            waitress.serve(
                TransLogger(app, setup_console_handler=False),
                host=env.WAITRESS_HOST,
                port=env.WAITRESS_PORT,
                threads=env.WAITRESS_JOBS,
            )
        else:
            app.run(host='0.0.0.0', port='5000', debug=True)
def add_access_logger(app, logger):
    wsgi_log_format_string = (
        '"%(REQUEST_METHOD)s %(REQUEST_URI)s %(HTTP_VERSION)s" '
        '%(status)s %(bytes)s')

    app.wsgi_app = TransLogger(app.wsgi_app,
                               logger_name=logger.name,
                               format=wsgi_log_format_string,
                               setup_console_handler=False,
                               set_logger_level=logger.level)
    return app