Exemplo n.º 1
0
def color_style():
    style = color.color_style()
    style.URL = termcolors.make_style(fg='green', opts=('bold',))
    style.MODULE = termcolors.make_style(fg='yellow')
    style.MODULE_NAME = termcolors.make_style(opts=('bold',))
    style.URL_NAME = termcolors.make_style(fg='red')
    return style
Exemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        if settings.DEBUG:
            self.request_path = None
            self.stats = {"request": {}, "response": {}}
            self.dbs = [c.alias for c in connections.all()]
            self._reset_stats()

            self._start_time = None
            self._end_time = None
            self.host = None  # The HTTP_HOST pulled from the request

            # colorizing methods
            self.white = termcolors.make_style(opts=('bold',), fg='white')
            self.red = termcolors.make_style(opts=('bold',), fg='red')
            self.yellow = termcolors.make_style(opts=('bold',), fg='yellow')
            self.green = termcolors.make_style(fg='green')

            # query type detection regex
            # TODO: make stats classification regex more robust
            self.read_query_regex = re.compile("SELECT .*")

            self.threshold = getattr(
                settings,
                'QUERYCOUNT_THRESHOLDS', {})
            if self.threshold:
              self.threshold['MEDIUM'] = self.threshold.get('MEDIUM', 50)
              self.threshold['HIGH'] = self.threshold.get('HIGH', 200)
              self.threshold['MIN_TIME_TO_LOG'] = self.threshold.get('MIN_TIME_TO_LOG', 0)
              self.threshold['MIN_QUERY_COUNT_TO_LOG'] = self.threshold.get('MIN_QUERY_COUNT_TO_LOG', 0)

            else:
              self.threshold = {'MEDIUM': 50, 'HIGH': 200, 'MIN_TIME_TO_LOG':0, 'MIN_QUERY_COUNT_TO_LOG':0}
            super(QueryCountMiddleware, self).__init__(*args, **kwargs)
Exemplo n.º 3
0
    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if settings.DEBUG:
            self.start = len(connection.queries)

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        if settings.DEBUG and 'runserver' in sys.argv and self.start is not None:
            red = termcolors.make_style(opts=('bold',), fg='red')
            yellow = termcolors.make_style(opts=('bold',), fg='yellow')

            count = len(connection.queries) - self.start
            output = '# queries: %s' % count
            output = output.ljust(15)

            # add some colour
            if count > 100:
                output = red(output)
            elif count > 10:
                output = yellow(output)

            # runserver just prints its output to sys.stderr, so follow suite
            sys.stderr.write(output)

        return response
Exemplo n.º 4
0
    def __init__(self, *args, **kwargs):
        # Call super first, so the MiddlewareMixin's __init__ does its thing.
        super(QueryCountMiddleware, self).__init__(*args, **kwargs)

        if settings.DEBUG:
            self.request_path = None
            self.stats = {"request": {}, "response": {}}
            self.dbs = [c.alias for c in connections.all()]
            self.queries = Counter()
            # start added by santhosh
            self.queries1 = defaultdict(floatdict)
            # end added by santhosh

            self._reset_stats()

            self._start_time = None
            self._end_time = None
            self.host = None  # The HTTP_HOST pulled from the request

            # colorizing methods
            self.white = termcolors.make_style(opts=('bold', ), fg='white')
            self.red = termcolors.make_style(opts=('bold', ), fg='red')
            self.yellow = termcolors.make_style(opts=('bold', ), fg='yellow')
            self.green = termcolors.make_style(fg='green')

            # query type detection regex
            # TODO: make stats classification regex more robust
            self.threshold = QC_SETTINGS['THRESHOLDS']
Exemplo n.º 5
0
    def __init__(self, *args, **kwargs):
        if settings.DEBUG:
            self.request_path = None
            self.stats = {"request": {}, "response": {}}
            self.dbs = [c.alias for c in connections.all()]
            self._reset_stats()

            self._start_time = None
            self._end_time = None
            self.host = None  # The HTTP_HOST pulled from the request

            # colorizing methods
            self.white = termcolors.make_style(opts=('bold',), fg='white')
            self.red = termcolors.make_style(opts=('bold',), fg='red')
            self.yellow = termcolors.make_style(opts=('bold',), fg='yellow')
            self.green = termcolors.make_style(fg='green')

            # query type detection regex
            # TODO: make stats classification regex more robust
            self.read_query_regex = re.compile("SELECT .*")

            self.threshold = getattr(
                settings,
                'QUERYCOUNT_THRESHOLDS',
                {'MEDIUM': 50, 'HIGH': 200}
            )
            super(QueryCountMiddleware, self).__init__(*args, **kwargs)
Exemplo n.º 6
0
def color_style():
    style = color.color_style()
    style.SECTION = termcolors.make_style(fg="yellow", opts=("bold",))
    style.SUCCESS = termcolors.make_style(fg="green", opts=("bold",))
    style.ERROR = termcolors.make_style(fg="red", opts=("bold",))
    style.INFO = termcolors.make_style(fg="blue", opts=("bold",))
    return style
def color_style():
    style = color.color_style()
    style.FILTER = termcolors.make_style(fg='yellow', opts=('bold', ))
    style.MODULE_NAME = termcolors.make_style(fg='green', opts=('bold', ))
    style.TAG = termcolors.make_style(fg='red', opts=('bold', ))
    style.TAGLIB = termcolors.make_style(fg='blue', opts=('bold', ))
    return style
def color_style():
    style = color.color_style()
    style.PROVIDER = termcolors.make_style(fg='green', opts=('bold',))
    style.COMMAND = termcolors.make_style(opts=('bold',))
    style.UNKNOWN = termcolors.make_style(fg='red')
    style.HELP = termcolors.make_style()
    return style
def color_style():
    style = color.color_style()
    style.FILTER = termcolors.make_style(fg='yellow', opts=('bold',))
    style.MODULE_NAME = termcolors.make_style(fg='green', opts=('bold',))
    style.TAG = termcolors.make_style(fg='red', opts=('bold',))
    style.TAGLIB = termcolors.make_style(fg='blue', opts=('bold',))
    return style
Exemplo n.º 10
0
def color_style():
    style = color.color_style()
    style.SECTION = termcolors.make_style(fg='yellow', opts=('bold', ))
    style.SUCCESS = termcolors.make_style(fg='green', opts=('bold', ))
    style.ERROR = termcolors.make_style(fg='red', opts=('bold', ))
    style.INFO = termcolors.make_style(fg='blue', opts=('bold', ))
    return style
def color_style():
    style = color.color_style()
    style.FILTER = termcolors.make_style(fg="yellow", opts=("bold",))
    style.MODULE_NAME = termcolors.make_style(fg="green", opts=("bold",))
    style.TAG = termcolors.make_style(fg="red", opts=("bold",))
    style.TAGLIB = termcolors.make_style(fg="blue", opts=("bold",))
    return style
Exemplo n.º 12
0
    def __call__(self, request):

        response = self.get_response(request)

        if settings.DEBUG and "runserver" in sys.argv and self.start is not None:
            red = termcolors.make_style(opts=("bold",), fg="red")
            yellow = termcolors.make_style(opts=("bold",), fg="yellow")

            count = len(connection.queries) - self.start
            output = "# queries: %s" % count
            output = output.ljust(18)

            # add some colour
            if count > 100:
                output = red(output)
            elif count > 10:
                output = yellow(output)

            # runserver just prints its output to sys.stderr, so follow suite
            sys.stderr.write(output)

            # for q in connection.queries:
            #     print(q['sql'])

        return response
Exemplo n.º 13
0
def color_style():
    style = color.color_style()
    style.ALREADY = termcolors.make_style(fg='yellow')
    style.OK = termcolors.make_style(fg='green', opts=('bold'),)
    style.REGULAR = termcolors.make_style()

    return style
Exemplo n.º 14
0
 def print_country_summary(self, country_code, region_names, source):
     if self.verbosity >= 2:
         self.stdout.write("\t" + str(list(region_names)) +
                           f"   from {source}")
     if self.verbosity >= 3:
         added = (self.new_regions.keys() - self.old_regions.keys())
         if added:
             self.stdout.write(
                 make_style(fg='green')("\tADDED:   {}".format([
                     tuple(r.values()) for c, r in self.new_regions.items()
                     if c in added
                 ])))
         if self.removed_regions:
             self.stdout.write(
                 make_style(fg='red')("\tREMOVED: {}".format(
                     [tuple(r.values()) for r in self.removed_regions])))
         changed = [
             tuple(
                 f"{self.old_regions[c][field] or '.'}->{self.new_regions[c][field] or '.'}"
                 if self.old_regions[c][field] != self.new_regions[c][field]
                 else self.old_regions[c][field]
                 for field in self.old_regions[c].keys())
             for c in (self.old_regions.keys() & self.new_regions.keys())
             if any(self.old_regions[c][field] != self.new_regions[c][field]
                    for field in self.old_regions[c].keys())
         ]
         if changed:
             self.stdout.write(
                 make_style(fg='magenta')("\tCHANGED: {}".format(changed)))
Exemplo n.º 15
0
    def process_response(self, request, response):
        if (settings.DEBUG
                and ("runserver" in sys.argv or "runserver_plus" in sys.argv)
                and self.initial_queries is not None):
            colorama.init(autoreset=True)

            # Colour definition
            danger = termcolors.make_style(opts=("bold", ), fg="red")
            warning = termcolors.make_style(opts=("bold", ), fg="yellow")
            ok = termcolors.make_style(opts=("bold", ), fg="green")

            # Calculate number of queries
            count = len(connection.queries) - self.initial_queries
            output = f"[DB queries: {count}] "

            # Apply colour threshold
            if count >= getattr(settings, "NUMBER_OF_QUERIES_DANGER", 50):
                output = danger(output)
            elif count >= getattr(settings, "NUMBER_OF_QUERIES_WARNING", 25):
                output = warning(output)
            else:
                output = ok(output)

            # runserver just prints its output to sys.stderr, so follow suite
            sys.stderr.write(output)

            # Stop colorama to avoid "RecursionError"
            colorama.deinit()

        return response
Exemplo n.º 16
0
def custom_color_style():
    from django.utils import termcolors
    class dummy: pass
    style = dummy()
    style.ERROR = termcolors.make_style(fg='red', opts=('bold',))
    style.WARNING = termcolors.make_style(fg='yellow')
    style.SUCCESS = termcolors.make_style(fg='green', opts=('bold',))
    return style
Exemplo n.º 17
0
def color_style():
    if color.supports_color():
        style = color.color_style()
        style.METRIC = termcolors.make_style(opts=("bold",))
        style.ES_TEMPLATE = termcolors.make_style(fg="yellow")
    else:
        style = no_style()
    return style
Exemplo n.º 18
0
    def __init__(self, stream):
        self.stream = stream
        self.style = {}

        for code, params in _COLORS.items():
            self.style[code] = termcolors.make_style(**params)

        self.reset = termcolors.make_style(opts=('reset'))
Exemplo n.º 19
0
def color_style():
    style = color.color_style()
    style.SECTION = termcolors.make_style(fg='yellow', opts=('bold',))
    style.SUCCESS = termcolors.make_style(fg='green', opts=('bold',))
    style.ERROR = termcolors.make_style(fg='red', opts=('bold',))
    style.INFO = termcolors.make_style(fg='blue', opts=('bold',))
    style.DEFAULT = termcolors.make_style()
    return style
Exemplo n.º 20
0
    def __init__(self, stream):
        self.stream = stream
        self.style = {}

        for code, params in _COLORS.items():
            self.style[code] = termcolors.make_style(**params)

        self.reset = termcolors.make_style(opts=('reset'))
Exemplo n.º 21
0
def color_style():
	style = color.color_style()
	style.BOLD = termcolors.make_style(opts = ('bold',))
	style.GREEN = termcolors.make_style(fg = 'green', opts = ('bold',))
	style.YELLOW = termcolors.make_style(fg = 'yellow')
	style.BLUE = termcolors.make_style(fg = 'blue', opts = ('bold',))
	style.RED = termcolors.make_style(fg = 'red')
	
	return style
Exemplo n.º 22
0
def color_style():
    style = color.color_style()
    style.BOLD = termcolors.make_style(opts=('bold', ))
    style.GREEN = termcolors.make_style(fg='green', opts=('bold', ))
    style.YELLOW = termcolors.make_style(fg='yellow')
    style.BLUE = termcolors.make_style(fg='blue', opts=('bold', ))
    style.RED = termcolors.make_style(fg='red')

    return style
Exemplo n.º 23
0
def color_style():
    style = color.color_style()
    style.ALREADY = termcolors.make_style(fg='yellow')
    style.OK = termcolors.make_style(
        fg='green',
        opts=('bold'),
    )
    style.REGULAR = termcolors.make_style()

    return style
Exemplo n.º 24
0
                def __init__(self, *args, **kwargs):
                    pstats.Stats.__init__(self, *args, **kwargs)

                    class dummy(object): pass
                    style = dummy()
                    style.LONGRUN = termcolors.make_style(opts=('bold',), fg='red')
                    style.NAME = termcolors.make_style(opts=('bold',), fg='cyan')
                    style.FILE = termcolors.make_style(opts=('bold',), fg='yellow')
                    style.APP = termcolors.make_style(opts=('bold',), fg='white')
                    self.style = style
Exemplo n.º 25
0
    def _restyle_console(self):
        """Restyle console output.

        This will create/re-create the output styles, based on the terminal
        size and whether color is allowed.
        """
        # Recompute the styles, based on whether color is allowed.
        if self.allow_color:
            self.style = color_style()

            self.header_style = termcolors.make_style(fg='yellow',
                                                      bg='black',
                                                      opts=('bold',))
            self.header_sep_style = termcolors.make_style(fg='yellow',
                                                          bg='black')
            self.prompt_style = termcolors.make_style(opts=('bold',))
        else:
            self.style = no_style()

            plain_style = self._plain_style
            self.header_style = plain_style
            self.header_sep_style = plain_style
            self.prompt_style = plain_style

        # Rebuild the text wrappers.
        text_padding = self.default_text_padding

        self.header_wrapper = self.make_text_wrapper(
            left_padding=1,
            right_padding=1)
        self.header_sep_wrapper = self.make_text_wrapper()
        self.text_wrapper = self.make_text_wrapper(
            left_padding=text_padding,
            right_padding=text_padding)
        self.note_wrapper = self.make_text_wrapper(
            prefix='Note: ',
            prefix_style=self.style.WARNING,
            left_padding=text_padding,
            right_padding=text_padding)
        self.warning_wrapper = self.make_text_wrapper(
            prefix='Warning: ',
            prefix_style=self.style.WARNING,
            left_padding=text_padding,
            right_padding=text_padding)
        self.error_wrapper = self.make_text_wrapper(
            prefix='[!] ',
            prefix_style=self.style.ERROR,
            left_padding=text_padding,
            right_padding=text_padding)
        self.item_wrapper = self.make_text_wrapper(
            prefix='* ',
            left_padding=text_padding,
            right_padding=text_padding)
Exemplo n.º 26
0
                def __init__(self, *args, **kwargs):
                    pstats.Stats.__init__(self, *args, **kwargs)

                    class dummy(object):
                        pass

                    style = dummy()
                    style.LONGRUN = termcolors.make_style(opts=("bold",), fg="red")
                    style.NAME = termcolors.make_style(opts=("bold",), fg="cyan")
                    style.FILE = termcolors.make_style(opts=("bold",), fg="yellow")
                    style.APP = termcolors.make_style(opts=("bold",), fg="white")
                    self.style = style
Exemplo n.º 27
0
    def __init__(self, *args, **kwargs):

        if not cfg['enabled']:
            raise MiddlewareNotUsed()

        # colorizing methods
        self.white = termcolors.make_style(fg='white')
        self.red = termcolors.make_style(fg='red')
        self.yellow = termcolors.make_style(fg='yellow')
        self.green = termcolors.make_style(fg='green')

        super(QueryInspectMiddleware, self).__init__(*args, **kwargs)
Exemplo n.º 28
0
 def __init__(self, *args, **kwargs):
     super(CommandMixin, self).__init__(*args, **kwargs)
     self.argv = kwargs.get("argv") or sys.argv[:]
     self.package = self.__class__.__module__.split(".")[0]
     self.basecommand = self.argv[1]
     try:
         self.usercommand = self.argv[2]
     except IndexError:
         self.usercommand = ""
     if supports_color():
         opts = ('bold', )
         self.style.DESTROY = termcolors.make_style(fg='red', opts=opts)
         self.style.NOTFOUND = termcolors.make_style(fg='white', opts=opts)
         self.style.NOTEMPTY = termcolors.make_style(fg='black', opts=opts)
Exemplo n.º 29
0
 def __init__(self, *args, **kwargs):
     super(CommandMixin, self).__init__(*args, **kwargs)
     self.argv = kwargs.get("argv") or sys.argv[:]
     self.package = self.__class__.__module__.split(".")[0]
     self.basecommand = self.argv[1]
     try:
         self.usercommand = self.argv[2]
     except IndexError:
         self.usercommand = ""
     if supports_color():
         opts = ('bold',)
         self.style.DESTROY = termcolors.make_style(fg='red', opts=opts)
         self.style.NOTFOUND = termcolors.make_style(fg='white', opts=opts)
         self.style.NOTEMPTY = termcolors.make_style(fg='black', opts=opts)
Exemplo n.º 30
0
 def __init__(self, *args, **kwargs):
     super(VerboseCommandMixin, self).__init__(*args, **kwargs)
     self.dry_run = False
     if supports_color():
         opts = ('bold',)
         self.style.EXISTS = \
             termcolors.make_style(fg='blue', opts=opts)
         self.style.APPEND = \
             termcolors.make_style(fg='yellow', opts=opts)
         self.style.CREATE = \
             termcolors.make_style(fg='green', opts=opts)
         self.style.REVERT = \
             termcolors.make_style(fg='magenta', opts=opts)
         self.style.BACKUP = \
             termcolors.make_style(fg='cyan', opts=opts)
Exemplo n.º 31
0
 def __init__(self, *args, **kwargs):
     super(VerboseCommandMixin, self).__init__()
     self.dry_run = False
     if supports_color():
         opts = ('bold',)
         self.style.EXISTS = \
             termcolors.make_style(fg='blue', opts=opts)
         self.style.APPEND = \
             termcolors.make_style(fg='yellow', opts=opts)
         self.style.CREATE = \
             termcolors.make_style(fg='green', opts=opts)
         self.style.REVERT = \
             termcolors.make_style(fg='magenta', opts=opts)
         self.style.BACKUP = \
             termcolors.make_style(fg='cyan', opts=opts)
Exemplo n.º 32
0
 def print_esperanto_update_summary(self, updated_eonames, linebreak):
     if self.verbosity >= 3:
         if updated_eonames:
             self.stdout.write(
                 make_style(
                     fg='cyan')(("\n" if linebreak else "") +
                                "\tUPDATED: {}".format(updated_eonames)))
Exemplo n.º 33
0
def make_style(config_string=''):
    """
    Create a Style object from the given config_string.

    If config_string is empty django.utils.termcolors.DEFAULT_PALETTE is used.
    """
    class Style(object):
        pass

    style = Style()

    color_settings = termcolors.parse_color_setting(config_string)

    # The nocolor palette has all available roles.
    # Use that palette as the basis for populating
    # the palette as defined in the environment.
    for role in termcolors.PALETTES[termcolors.NOCOLOR_PALETTE]:
        if color_settings:
            format = color_settings.get(role, {})
            style_func = termcolors.make_style(**format)
        else:
            style_func = lambda x: x
        setattr(style, role, style_func)

    # For backwards compatibility,
    # set style for ERROR_OUTPUT == ERROR
    style.ERROR_OUTPUT = style.ERROR

    return style
Exemplo n.º 34
0
def print_and_call_command(command, *args, **kwargs):
    print((termcolors.make_style(fg='cyan', opts=('bold', ))(
        '>>> {} {}{}'.format(
            command, ' '.join(args),
            ' '.join(['{}={}'.format(k, v)
                      for k, v in list(kwargs.items())])))))
    call_command(command, *args, **kwargs)
Exemplo n.º 35
0
def print_and_call_command(command, *args, **kwargs):
    kwargs.setdefault('interactive', True)
    print(termcolors.make_style(fg='cyan', opts=('bold',))('>>> %s %s%s' \
        % (command,
           ' '.join(args),
           ' '.join(['%s=%s' % (k, v) for k, v in kwargs.items()]))))
    call_command(command, *args, **kwargs)
Exemplo n.º 36
0
def make_style(config_string=""):
    """
    Create a Style object from the given config_string.

    If config_string is empty django.utils.termcolors.DEFAULT_PALETTE is used.
    """

    style = Style()

    color_settings = termcolors.parse_color_setting(config_string)

    # The nocolor palette has all available roles.
    # Use that palette as the basis for populating
    # the palette as defined in the environment.
    for role in termcolors.PALETTES[termcolors.NOCOLOR_PALETTE]:
        if color_settings:
            format = color_settings.get(role, {})
            style_func = termcolors.make_style(**format)
        else:

            def style_func(x):
                return x

        setattr(style, role, style_func)

    # For backwards compatibility,
    # set style for ERROR_OUTPUT == ERROR
    style.ERROR_OUTPUT = style.ERROR

    return style
Exemplo n.º 37
0
def color_style():
    """Returns a Style object with the Django color scheme."""
    if not supports_color():
        style = no_style()
    else:
        DJANGO_COLORS = os.environ.get('DJANGO_COLORS', '')
        color_settings = termcolors.parse_color_setting(DJANGO_COLORS)
        if color_settings:

            class dummy:
                pass

            style = dummy()
            # The nocolor palette has all available roles.
            # Use that pallete as the basis for populating
            # the palette as defined in the environment.
            for role in termcolors.PALETTES[termcolors.NOCOLOR_PALETTE]:
                format = color_settings.get(role, {})
                setattr(style, role, termcolors.make_style(**format))
            # For backwards compatibility,
            # set style for ERROR_OUTPUT == ERROR
            style.ERROR_OUTPUT = style.ERROR
        else:
            style = no_style()
    return style
Exemplo n.º 38
0
                def __init__(self, *args, **kwargs):
                    pstats.Stats.__init__(self, *args, **kwargs)

                    class dummy(object):
                        pass

                    style = dummy()
                    style.LONGRUN = termcolors.make_style(opts=('bold', ),
                                                          fg='red')
                    style.NAME = termcolors.make_style(opts=('bold', ),
                                                       fg='cyan')
                    style.FILE = termcolors.make_style(opts=('bold', ),
                                                       fg='yellow')
                    style.APP = termcolors.make_style(opts=('bold', ),
                                                      fg='white')
                    self.style = style
 def handle(self, *args, **options):
     success = termcolors.make_style(fg='green')
     error = termcolors.make_style(fg='red')
     if not self._jsonschema_exist:
         not_exist = '[' + error('ERROR') + '] SIMPLE_JSONSCHEMA is not exist in settings.'
         self.stdout.write(not_exist)
         return
     errors = self._jsonschema_errors
     if len(errors):
         for e in errors:
             title = '\n[' + error('ERROR') + '] schema of ' + str(e['url']) + ' is invalid.'
             self.stdout.write(title)
             self.stdout.write('path: ' + str(list(e['error'].path)))
             self.stdout.write('message: ' + e['error'].message)
             self.stdout.write('schema:\n' + e['schema'] + '\n')
     else:
         self.stdout.write('[' + success('SUCCESS') + '] All jsonschemas are OK.')
Exemplo n.º 40
0
    def process_response(self, request, response):
        if settings.DEBUG and 'runserver' in sys.argv and self.start is not None:
            red = termcolors.make_style(opts=('bold',), fg='red')
            yellow = termcolors.make_style(opts=('bold',), fg='yellow')

            count = len(connection.queries) - self.start
            output = '# queries: %s' % count
            output = output.ljust(15)

            # add some colour
            if count > 100:
                output = red(output)
            elif count > 10:
                output = yellow(output)

            # runserver just prints its output to sys.stderr, so follow suite
            sys.stderr.write(output)

        return response
Exemplo n.º 41
0
    def Style():
        """constructs a helper object with coloring methods"""
        class Style(object):
            def __getattr__(self, attr):
                # By default every coloring method returns its argument
                # unmodified.
                return lambda x: x
            pass

        style = Style()

        if os.isatty(1):
            color_names = ('black', 'red', 'green', 'yellow', 'blue',
                    'magenta', 'cyan', 'white')
            for col in color_names:
                setattr(style, col, termcolors.make_style(fg=col))
                setattr(style, "bold_" + col,
                        termcolors.make_style(fg=col, opts=('bold',)))

        return style
Exemplo n.º 42
0
 def processar_group_permission(self, app, apps, options, groupPermission):
     permissoes = []
     if len(apps) == 0 or app in apps:
         permissionFileName = '%s/permissions.xml' % app
         if isfile(permissionFileName) and (len(apps) == 0 or app in apps):
             if options['verbosity'] in ('2', '3'):
                 self.stdout.write(
                     termcolors.make_style(fg='yellow')(u'Processing %s' %
                                                        permissionFileName))
             permissoes = groupPermission.processar(permissionFileName, app)
     return permissoes
Exemplo n.º 43
0
def warn(message, color='yellow', name='Warning', prefix='', print_traceback=True):
    import sys
    from django.utils.termcolors import make_style

    red = make_style(fg=color, opts=('bold',))

    if print_traceback:
        import traceback
        traceback.print_exc()

    sys.stderr.write('{0}{1}: {2}\n'.format(prefix, red(name), message))
 def handle(self, *args, **options):
     success = termcolors.make_style(fg='green')
     error = termcolors.make_style(fg='red')
     if not self._jsonschema_exist:
         not_exist = '[' + error(
             'ERROR') + '] SIMPLE_JSONSCHEMA is not exist in settings.'
         self.stdout.write(not_exist)
         return
     errors = self._jsonschema_errors
     if len(errors):
         for e in errors:
             title = '\n[' + error('ERROR') + '] schema of ' + str(
                 e['url']) + ' is invalid.'
             self.stdout.write(title)
             self.stdout.write('path: ' + str(list(e['error'].path)))
             self.stdout.write('message: ' + e['error'].message)
             self.stdout.write('schema:\n' + e['schema'] + '\n')
     else:
         self.stdout.write('[' + success('SUCCESS') +
                           '] All jsonschemas are OK.')
Exemplo n.º 45
0
    def process_response(self, request, response):
        if settings.DEBUG and 'runserver' in sys.argv and self.start is not None:
            yellow = termcolors.make_style(opts=('bold', ), fg='yellow')

            count = len(connection.queries) - self.start
            output = '# queries: %s' % count
            output = output.ljust(15)

            for q in connection.queries[self.start:]:
                sys.stderr.write(yellow("\t" + q['sql'] + "\n"))

        return response
Exemplo n.º 46
0
    def __init__(self, *args, **kwargs):
        if settings.DEBUG:
            self.request_path = None
            self.stats = {"request": {}, "response": {}}
            self.dbs = [c.alias for c in connections.all()]
            self._reset_stats()

            self._start_time = None
            self._end_time = None
            self.host = None  # The HTTP_HOST pulled from the request

            # colorizing methods
            self.white = termcolors.make_style(opts=('bold',), fg='white')
            self.red = termcolors.make_style(opts=('bold',), fg='red')
            self.yellow = termcolors.make_style(opts=('bold',), fg='yellow')
            self.green = termcolors.make_style(fg='green')

            # query type detection regex
            # TODO: make stats classification regex more robust
            self.threshold = QC_SETTINGS['THRESHOLDS']
            super(QueryCountMiddleware, self).__init__(*args, **kwargs)
Exemplo n.º 47
0
    def create_mapping(self, style, conf):
        mapping = {}
        for name, val in conf.items():
            if isinstance(val, dict):
                style_func = make_style(**val)
            else:
                style_func = getattr(style, val, None)

            if style_func:
                mapping[name] = style_func

        return mapping
    def handle_noargs(self, **options):
        error_style = termcolors.make_style(fg='red')
        ok_style = termcolors.make_style(fg='green')
        app_style = termcolors.make_style(fg='white')

        # Compatibility with future Django version which will provide this
        # attribute for every Command instance
        if not hasattr(self, 'stdout'):
            self.stdout = sys.stdout

        # Used for calculating proper output width
        columns = int(os.environ.get('COLUMNS', 80))

        autodiscover()

        # Result page header
        self.stdout.write("Pre-flight checks for applications\n")
        self.stdout.write("=" * columns + '\n')

        applications = gather_checks()

        for application in applications:
            # Separation between applications
            self.stdout.write('\n')

            # Displaying application name in white
            self.stdout.write(app_style(application['name']) + '\n')
            self.stdout.write("-" * columns + '\n')

            for check in application['checks']:
                # Formatting check result line, uses ANSI colors to prettify it
                if check['passed']:
                    status_name = ok_style(" OK")
                else:
                    status_name = error_style("ERROR")

                self.stdout.write(check['name'].ljust(columns - 7) + status_name + '\n')

        # Report correct return code to the shell
        sys.exit(not all(a['passed'] for a in applications))
Exemplo n.º 49
0
    def log(self, message, *args, **kwargs):
        id = kwargs.pop('id', None)
        duration = kwargs.pop('duration', None)
        rowcount = kwargs.pop('rowcount', None)
        level = kwargs.pop('level', logging.INFO)

        tpl_bits = []
        if id:
            tpl_bits.append(self.style.SQL_FIELD('[%s/%s]' % (self.module.logger_name, id)))
        else:
            tpl_bits.append(self.style.SQL_FIELD('[%s]' % self.module.logger_name))
        if duration:
            tpl_bits.append(self.style.SQL_KEYWORD('(%dms)' % duration))
        if rowcount and rowcount >= 0:
            tpl_bits.append('[%d rows]' % rowcount)

        if args:
            message = message % args

        message = smart_str(message)

        if level == logging.ERROR:
            message = self.style.ERROR(message)
        elif level == logging.WARN:
            message = self.style.NOTICE(message)
        else:
            try:
                HTTP_INFO = self.style.HTTP_INFO
            except:
                HTTP_INFO = termcolors.make_style(fg='red')
            message = HTTP_INFO(message)

        tpl = ' '.join(tpl_bits) % dict(
            id=id,
            module=self.module.logger_name,
            asctime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        )

        indent = ' ' * (len(strip_bash_colors(tpl)) + 1)

        new_message = []
        first = True
        for line in message.split('\n'):
            if first:
                new_message.append(line)
            else:
                new_message.append('%s%s' % (indent, line))
            first = False

        message = '%s %s' % (tpl, '\n'.join(new_message))

        sys.stdout.write('    ' + message + '\n')
Exemplo n.º 50
0
    def log(self, message, *args, **kwargs):
        id = kwargs.pop('id', None)
        duration = kwargs.pop('duration', None)
        level = kwargs.pop('level', logging.INFO)

        tpl_bits = []
        if id:
            tpl_bits.append(
                self.style.SQL_FIELD('[%s/%s]' %
                                     (self.module.logger_name, id)))
        else:
            tpl_bits.append(
                self.style.SQL_FIELD('[%s]' % self.module.logger_name))
        if duration:
            tpl_bits.append(self.style.SQL_KEYWORD('(%dms)' % duration))

        if args:
            message = message % args

        message = smart_str(message)

        if level == logging.ERROR:
            message = self.style.ERROR(message)
        elif level == logging.WARN:
            message = self.style.NOTICE(message)
        else:
            try:
                HTTP_INFO = self.style.HTTP_INFO
            except:
                HTTP_INFO = termcolors.make_style(fg='red')
            message = HTTP_INFO(message)

        tpl = ' '.join(tpl_bits) % dict(
            id=id,
            module=self.module.logger_name,
            asctime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        )

        indent = ' ' * (len(strip_bash_colors(tpl)) + 1)

        new_message = []
        first = True
        for line in message.split('\n'):
            if first:
                new_message.append(line)
            else:
                new_message.append('%s%s' % (indent, line))
            first = False

        message = '%s %s' % (tpl, '\n'.join(new_message))

        sys.stdout.write('    ' + message + '\n')
Exemplo n.º 51
0
def color_style():
    style = color.color_style()
    if color.supports_color():
        style.INFO = termcolors.make_style(fg="green")
        style.WARN = termcolors.make_style(fg="yellow")
        style.BOLD = termcolors.make_style(opts=("bold",))
        style.URL = termcolors.make_style(fg="green", opts=("bold",))
        style.MODULE = termcolors.make_style(fg="yellow")
        style.MODULE_NAME = termcolors.make_style(opts=("bold",))
        style.URL_NAME = termcolors.make_style(fg="red")
    return style
Exemplo n.º 52
0
def color_style():
    if color.supports_color():
        style = color.color_style()
        style.INFO = termcolors.make_style(fg='green')
        style.WARN = termcolors.make_style(fg='yellow')
        style.BOLD = termcolors.make_style(opts=('bold',))
        style.URL = termcolors.make_style(fg='green', opts=('bold',))
        style.MODULE = termcolors.make_style(fg='yellow')
        style.MODULE_NAME = termcolors.make_style(opts=('bold',))
        style.URL_NAME = termcolors.make_style(fg='red')
    else:
        style = no_style()
    return style
Exemplo n.º 53
0
def color_style():
    """Returns a Style object with the Django color scheme."""
    if not supports_color():
        return no_style()
    class dummy: pass
    style = dummy()
    style.ERROR = termcolors.make_style(fg='red', opts=('bold',))
    style.ERROR_OUTPUT = termcolors.make_style(fg='red', opts=('bold',))
    style.NOTICE = termcolors.make_style(fg='red')
    style.SQL_FIELD = termcolors.make_style(fg='green', opts=('bold',))
    style.SQL_COLTYPE = termcolors.make_style(fg='green')
    style.SQL_KEYWORD = termcolors.make_style(fg='yellow')
    style.SQL_TABLE = termcolors.make_style(opts=('bold',))
    return style
Exemplo n.º 54
0
def color_style():
    """Returns a Style object with the Django color scheme."""
    if (sys.platform == 'win32' or sys.platform == 'Pocket PC'
        or sys.platform.startswith('java') or not sys.stdout.isatty()):
        return no_style()
    class dummy: pass
    style = dummy()
    style.ERROR = termcolors.make_style(fg='red', opts=('bold',))
    style.ERROR_OUTPUT = termcolors.make_style(fg='red', opts=('bold',))
    style.NOTICE = termcolors.make_style(fg='red')
    style.SQL_FIELD = termcolors.make_style(fg='green', opts=('bold',))
    style.SQL_COLTYPE = termcolors.make_style(fg='green')
    style.SQL_KEYWORD = termcolors.make_style(fg='yellow')
    style.SQL_TABLE = termcolors.make_style(opts=('bold',))
    return style
Exemplo n.º 55
0
def color_style():
    style = color.color_style()
    if color.supports_color():
        style.INFO = termcolors.make_style(fg="green")
        style.WARN = termcolors.make_style(fg="yellow")
        style.BOLD = termcolors.make_style(opts=("bold",))
        style.URL = termcolors.make_style(fg="green", opts=("bold",))
        style.MODULE = termcolors.make_style(fg="yellow")
        style.MODULE_NAME = termcolors.make_style(opts=("bold",))
        style.URL_NAME = termcolors.make_style(fg="red")
    else:
        for role in ("INFO", "WARN", "BOLD", "URL", "MODULE", "MODULE_NAME", "URL_NAME"):
            if not hasattr(style, role):
                setattr(style, role, _dummy_style_func)
    return style
Exemplo n.º 56
0
def color_style():
    style = color.color_style()
    if color.supports_color():
        style.INFO = termcolors.make_style(fg='green')
        style.WARN = termcolors.make_style(fg='yellow')
        style.BOLD = termcolors.make_style(opts=('bold',))
        style.URL = termcolors.make_style(fg='green', opts=('bold',))
        style.MODULE = termcolors.make_style(fg='yellow')
        style.MODULE_NAME = termcolors.make_style(opts=('bold',))
        style.URL_NAME = termcolors.make_style(fg='red')
    else:
        for role in ('INFO', 'WARN', 'BOLD', 'URL', 'MODULE', 'MODULE_NAME', 'URL_NAME'):
            if not hasattr(style, role):
                setattr(style, role, _dummy_style_func)
    return style
Exemplo n.º 57
0
def color_style():
    """Returns a Style object with the Django color scheme."""
    if not supports_color():
        style = no_style()
    else:
        DJANGO_COLORS = os.environ.get('DJANGO_COLORS', '')
        color_settings = termcolors.parse_color_setting(DJANGO_COLORS)
        if color_settings:
            class dummy: pass
            style = dummy()
            # The nocolor palette has all available roles.
            # Use that pallete as the basis for populating
            # the palette as defined in the environment.
            for role in termcolors.PALETTES[termcolors.NOCOLOR_PALETTE]:
                format = color_settings.get(role,{})
                setattr(style, role, termcolors.make_style(**format))
        else:
            style = no_style()
    return style