Exemplo n.º 1
0
    def log(self, _type, message, *args):
        ''' Silences some endpoints '''
        silent_endpoints = ["/hcalive", "/static", "/favicon.ico"]
        if (isinstance(args[1], str) or not isinstance(args[1], Iterable)
                or (not any(slnt in args[1]
                            for slnt in silent_endpoints) and args[1] != '/')):
            if len(args) >= 5:
                log_params = [('host', self.address_string(), 'red'),
                              ('time', self.log_date_time_string(), 'magenta'),
                              ('method', args[0], 'blue'),
                              ('path', args[1], 'blue'),
                              ('protocol', args[2], 'blue'),
                              ('status', args[3], 'yellow'),
                              ('size', args[4], 'blue')]

                # Standard log layout
                # 127.0.0.1 - - [15/Mar/2019 12:02:23] "POST /mail HTTP/1.1" 504 -
                template = '%s - - [%s] ' + message + '\n'
            else:
                log_params = [('host', self.address_string(), 'red'),
                              ('time', self.log_date_time_string(), 'magenta'),
                              ('status', args[0], 'yellow'),
                              ('msg', args[1], 'blue')]

                # Standard log layout
                # 127.0.0.1 - - [15/Mar/2019 12:02:23] Mensagem de erro
                template = '%s - - [%s] "%s" %s\n'

            parts = []
            for _name, value, color in log_params:
                part = colors.color(str(value), fg=color)
                parts.append(part)

            content = template % tuple(parts)
            _log(_type, content)
Exemplo n.º 2
0
Arquivo: wsgi.py Projeto: QGB/zmirror
 def log(self, type, message, *args):
     if not getattr(self, 'ip_location', None):
         self.ip_location = sys.modules['qgb.N'].ip_location
         self.U = sys.modules['qgb.U']
         self.F = sys.modules['qgb.F']
         # globals()['F']=sys.modules['qgb.F']
         # globals()['U']=sys.modules['qgb.U']
     ip = self.address_string()
     ip = self.ip_location(ip, show_ip=True)
     obj = {
         'ip': ip,
         'client_address ': self.client_address,
         'command        ': self.command,
         'connection     ': self.connection,
         'raw_requestline': self.raw_requestline,
         'headers        ': dict(self.headers)
     }
     self.F.write('log/' + self.U.stime(), self.U.pformat(obj))
     for i in ipLocationList:
         if i in ip:
             break
     else:
         raise Exception('ipLocation %s not allowed' % ip)
     # from IPython import embed;embed()
     _log(
         type,
         '%s [%s] %s\n' % (ip, self.log_date_time_string(), message % args))
     return
Exemplo n.º 3
0
    def log_startup(sock: serving.socket.socket) -> None:
        all_addresses_message = (
            " * Running on all addresses.\n"
            "   WARNING: This is a development server. Do not use it in"
            " a production deployment.")

        if sock.family == serving.af_unix:
            serving._log("info", " * Running on %s (Press CTRL+C to quit)",
                         hostname)
        else:
            if hostname == "0.0.0.0":
                serving._log("warning", all_addresses_message)
                display_hostname = serving.get_interface_ip(
                    serving.socket.AF_INET)
            elif hostname == "::":
                serving._log("warning", all_addresses_message)
                display_hostname = serving.get_interface_ip(
                    serving.socket.AF_INET6)
            else:
                display_hostname = hostname

            if ":" in display_hostname:
                display_hostname = f"[{display_hostname}]"

            serving._log(
                "info",
                " * Running on %s://%s:%d/ (Press CTRL+C to quit)",
                "http" if ssl_context is None else "https",
                display_hostname,
                sock.getsockname()[1],
            )
Exemplo n.º 4
0
        def _reloader_stat_loop(extra_files=None, interval=1):
            """
            When this function is run from the main thread, it will force other
            threads to exit when any modules currently loaded change.

            Copyright notice.  This function is based on the autoreload.py from
            the CherryPy trac which originated from WSGIKit which is now dead.

            :param extra_files: a list of additional files it should watch.
            """
            mtimes = {}

            def touch(fname, times=None):
                """
                emulate bash `touch`
                """
                with file(fname, 'a+'):
                    os.utime(fname, times)

            while 1:
                for filename in chain(_iter_module_files(), extra_files or ()):
                    try:
                        mtime = os.stat(filename).st_mtime
                    except OSError:
                        continue

                    old_time = mtimes.get(filename)

                    if old_time is None:
                        mtimes[filename] = mtime
                        continue
                    elif mtime > old_time:
                        _log('info', ' * Detected change in %r, reloading,' % (
                            filename
                        ))
                        touch(self.tmp_file)
                        sys.exit(3)
                time.sleep(interval)
Exemplo n.º 5
0
 def log(self, type, message, *args):
     _log(type, f"{self.address_string()} => {message % args}\n")
Exemplo n.º 6
0
 def log(self, type, message, *args):
     # don't log datetime again
     _log(type, '%s %s\n' % (self.address_string(), message % args))
Exemplo n.º 7
0
 def log(self, type, message, *largs):
     # don't log datetime again
     if " /socket.io/?" not in largs[0] or args.DEBUG:
         _log(type, '%s %s\n' % (self.address_string(), message % largs))
Exemplo n.º 8
0
def run_simple(
    hostname: str,
    port: int,
    application,
    use_reloader: bool = False,
    use_debugger: bool = False,
    use_evalex: bool = True,
    extra_files=None,
    exclude_patterns=None,
    reloader_interval: int = 1,
    reloader_type: str = "auto",
    threaded: bool = False,
    processes: int = 1,
    request_handler=None,
    static_files=None,
    passthrough_errors: bool = False,
    ssl_context=None,
) -> None:

    if not isinstance(port, int):
        raise TypeError("port must be an integer")

    def log_startup(sock: serving.socket.socket) -> None:
        all_addresses_message = (
            " * Running on all addresses.\n"
            "   WARNING: This is a development server. Do not use it in"
            " a production deployment.")

        if sock.family == serving.af_unix:
            serving._log("info", " * Running on %s (Press CTRL+C to quit)",
                         hostname)
        else:
            if hostname == "0.0.0.0":
                serving._log("warning", all_addresses_message)
                display_hostname = serving.get_interface_ip(
                    serving.socket.AF_INET)
            elif hostname == "::":
                serving._log("warning", all_addresses_message)
                display_hostname = serving.get_interface_ip(
                    serving.socket.AF_INET6)
            else:
                display_hostname = hostname

            if ":" in display_hostname:
                display_hostname = f"[{display_hostname}]"

            serving._log(
                "info",
                " * Running on %s://%s:%d/ (Press CTRL+C to quit)",
                "http" if ssl_context is None else "https",
                display_hostname,
                sock.getsockname()[1],
            )

    def inner() -> None:
        try:
            fd: serving.t.Optional[int] = int(
                serving.os.environ["WERKZEUG_SERVER_FD"])
        except (LookupError, ValueError):
            fd = None
        global server
        server = serving.make_server(
            hostname,
            port,
            application,
            threaded,
            processes,
            request_handler,
            passthrough_errors,
            ssl_context,
            fd=fd,
        )
        if fd is None:
            log_startup(server.socket)

    if use_reloader:
        # If we're not running already in the subprocess that is the
        # reloader we want to open up a socket early to make sure the
        # port is actually available.
        if not serving.is_running_from_reloader():
            if port == 0 and not serving.can_open_by_fd:
                raise ValueError("Cannot bind to a random port with enabled "
                                 "reloader if the Python interpreter does "
                                 "not support socket opening by fd.")

            # Create and destroy a socket so that any exceptions are
            # raised before we spawn a separate Python interpreter and
            # lose this ability.
            address_family = serving.select_address_family(hostname, port)
            server_address = serving.get_sockaddr(hostname, port,
                                                  address_family)
            s = serving.socket.socket(address_family,
                                      serving.socket.SOCK_STREAM)
            s.setsockopt(serving.socket.SOL_SOCKET,
                         serving.socket.SO_REUSEADDR, 1)
            s.bind(server_address)
            s.set_inheritable(True)

            # If we can open the socket by file descriptor, then we can just
            # reuse this one and our socket will survive the restarts.
            if serving.can_open_by_fd:
                serving.os.environ["WERKZEUG_SERVER_FD"] = str(s.fileno())
                s.listen(serving.LISTEN_QUEUE)
                log_startup(s)
            else:
                s.close()
                if address_family == serving.af_unix:
                    server_address = serving.t.cast(str, server_address)
                    serving._log("info", "Unlinking %s", server_address)
                    serving.os.unlink(server_address)

        from werkzeug._reloader import run_with_reloader as _rwr

        _rwr(
            inner,
            extra_files=extra_files,
            exclude_patterns=exclude_patterns,
            interval=reloader_interval,
            reloader_type=reloader_type,
        )
    else:
        inner()