def handle(self, *args, **kwargs): self.style = color_style() installed_apps = dict( (a.__name__.rsplit('.', 1)[0], a) for a in get_apps()) # Make sure we always have args if not args: args = [False] app = installed_apps.get(args[0]) if not app: print( self.style.WARN( 'This command requires an existing app name as argument')) print(self.style.WARN('Available apps:')) for app in sorted(installed_apps): print(self.style.WARN(' %s' % app)) sys.exit(1) model_res = [] for arg in args[1:]: model_res.append(re.compile(arg, re.IGNORECASE)) self.handle_app(app, model_res, **kwargs)
def handle(self, *args, **options): if args: (appname, ) = args style = color_style() if settings.ADMIN_FOR: settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR] else: settings_modules = [settings] views = [] for settings_mod in settings_modules: try: urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, ['']) except Exception, e: if options.get('traceback', None): import traceback traceback.print_exc() print style.ERROR('Error occurred while trying to load %s: %s' % (settings_mod.ROOT_URLCONF, str(e))) continue view_functions = \ extract_views_from_urlpatterns(urlconf.urlpatterns) for (func, regex) in view_functions: func_name = hasattr(func, '__name__') and func.__name__ \ or repr(func) views.append('%(url)s\t%(module)s.%(name)s' % {'name': style.MODULE_NAME(func_name), 'module': style.MODULE(func.__module__), 'url': style.URL(simplify_regex(regex))})
def handle(self, *args, **options): if args: appname, = args style = color_style() if settings.ADMIN_FOR: settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR] else: settings_modules = [settings] views = [] for settings_mod in settings_modules: try: urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, ['']) except Exception, e: if options.get('traceback', None): import traceback traceback.print_exc() print style.ERROR("Error occurred while trying to load %s: %s" % (settings_mod.ROOT_URLCONF, str(e))) continue view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns) for (func, regex, url_name) in view_functions: if hasattr(func, '__name__'): func_name = func.__name__ elif hasattr(func, '__class__'): func_name = '%s()' % func.__class__.__name__ else: func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func)) views.append("%(url)s\t%(module)s.%(name)s\t%(url_name)s" % {'name': style.MODULE_NAME(func_name), 'module': style.MODULE(func.__module__), 'url_name': style.URL_NAME(url_name or ''), 'url': style.URL(simplify_regex(regex))})
def test_color_style(self): with force_color_support: style = color.color_style().MODULE_NAME text = 'antigravity' styled_text = style(text) self.assertIn(text, styled_text) self.assertNotEqual(text, styled_text)
def handle(self, *args, **options): self.style = color_style() self.options = options if options["requirements"]: req_files = options["requirements"] elif os.path.exists("requirements.txt"): req_files = ["requirements.txt"] elif os.path.exists("requirements"): req_files = [ "requirements/{0}".format(f) for f in os.listdir("requirements") if os.path.isfile(os.path.join("requirements", f)) and f.lower().endswith(".txt") ] elif os.path.exists("requirements-dev.txt"): req_files = ["requirements-dev.txt"] elif os.path.exists("requirements-prod.txt"): req_files = ["requirements-prod.txt"] else: raise CommandError("Requirements file(s) not found") try: from pip.download import PipSession except ImportError: raise CommandError("Pip version 6 or higher is required") self.reqs = {} with PipSession() as session: for filename in req_files: for req in parse_requirements(filename, session=session): # url attribute changed to link in pip version 6.1.0 and above if LooseVersion(pip.__version__) > LooseVersion('6.0.8'): self.reqs[req.name] = { "pip_req": req, "url": req.link, } else: self.reqs[req.name] = { "pip_req": req, "url": req.url, } if options["github_api_token"]: self.github_api_token = options["github_api_token"] elif os.environ.get("GITHUB_API_TOKEN"): self.github_api_token = os.environ.get("GITHUB_API_TOKEN") else: self.github_api_token = None # only 50 requests per hour self.check_pypi() if HAS_REQUESTS: self.check_github() else: print( self.style.ERROR( "Cannot check github urls. The requests library is not installed. ( pip install requests )" )) self.check_other()
def handle(self, *args, **options): if args: appname, = args style = color_style() if settings.ADMIN_FOR: settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR] else: settings_modules = [settings] language = options.get('language', None) if language is not None: activate(language) decorator = options.get('decorator') if decorator is None: decorator = 'login_required' format_style = options.get('format_style', 'dense') if format_style not in FMTR: raise Exception("Format style '%s' does not exist. Options: %s" % (format_style, FMTR.keys())) fmtr = FMTR[format_style] views = [] for settings_mod in settings_modules: try: urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, ['']) except Exception as e: if options.get('traceback', None): import traceback traceback.print_exc() print(style.ERROR("Error occurred while trying to load %s: %s" % (settings_mod.ROOT_URLCONF, str(e)))) continue view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns) for (func, regex, url_name) in view_functions: if hasattr(func, '__name__'): func_name = func.__name__ elif hasattr(func, '__class__'): func_name = '%s()' % func.__class__.__name__ else: func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func)) func_globals = func.__globals__ if six.PY3 else func.func_globals views.append(fmtr % { 'name': style.MODULE_NAME(func_name), 'module': style.MODULE(func.__module__), 'url_name': style.URL_NAME(url_name or ''), 'url': style.URL(simplify_regex(regex)), 'decorator': decorator if decorator in func_globals else '', }) if not options.get('unsorted', False): views = sorted(views) return "\n".join([v for v in views]) + "\n"
def handle(self, *args, **options): self.style = color_style() self.options = options if options["requirements"]: req_files = options["requirements"] elif os.path.exists("requirements.txt"): req_files = ["requirements.txt"] elif os.path.exists("requirements"): req_files = ["requirements/{0}".format(f) for f in os.listdir("requirements") if os.path.isfile(os.path.join("requirements", f)) and f.lower().endswith(".txt")] elif os.path.exists("requirements-dev.txt"): req_files = ["requirements-dev.txt"] elif os.path.exists("requirements-prod.txt"): req_files = ["requirements-prod.txt"] else: raise CommandError("Requirements file(s) not found") try: from pip.download import PipSession except ImportError: raise CommandError("Pip version 6 or higher is required") self.reqs = {} with PipSession() as session: for filename in req_files: for req in parse_requirements(filename, session=session): # url attribute changed to link in pip version 6.1.0 and above if LooseVersion(pip.__version__) > LooseVersion('6.0.8'): self.reqs[req.name] = { "pip_req": req, "url": req.link, } else: self.reqs[req.name] = { "pip_req": req, "url": req.url, } if options["github_api_token"]: self.github_api_token = options["github_api_token"] elif os.environ.get("GITHUB_API_TOKEN"): self.github_api_token = os.environ.get("GITHUB_API_TOKEN") else: self.github_api_token = None # only 50 requests per hour self.check_pypi() if HAS_REQUESTS: self.check_github() else: print(self.style.ERROR("Cannot check github urls. The requests library is not installed. ( pip install requests )")) self.check_other()
def handle(self, *args, **options): if args: appname, = args style = color_style() if settings.ADMIN_FOR: settings_modules = [ __import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR ] else: settings_modules = [settings] language = options.get('language', None) if language is not None: activate(language) views = [] for settings_mod in settings_modules: try: urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, ['']) except Exception as e: if options.get('traceback', None): import traceback traceback.print_exc() print( style.ERROR("Error occurred while trying to load %s: %s" % (settings_mod.ROOT_URLCONF, str(e)))) continue view_functions = extract_views_from_urlpatterns( urlconf.urlpatterns) for (func, regex, url_name) in view_functions: if hasattr(func, '__name__'): func_name = func.__name__ elif hasattr(func, '__class__'): func_name = '%s()' % func.__class__.__name__ else: func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func)) views.append( "%(url)s\t%(module)s.%(name)s\t%(url_name)s" % { 'name': style.MODULE_NAME(func_name), 'module': style.MODULE(func.__module__), 'url_name': style.URL_NAME(url_name or ''), 'url': style.URL(simplify_regex(regex)) }) if not options.get('unsorted', False): views = sorted(views) return "\n".join([v for v in views]) + "\n"
def handle_noargs(self, **options): self.style = color_style() self.options = options if options["requirements"]: req_files = options["requirements"] elif os.path.exists("requirements.txt"): req_files = ["requirements.txt"] elif os.path.exists("requirements"): req_files = [ "requirements/{0}".format(f) for f in os.listdir("requirements") if os.path.isfile(os.path.join("requirements", f)) and f.lower().endswith(".txt") ] else: sys.exit("requirements not found") self.reqs = {} for filename in req_files: class Object(object): pass mockoptions = Object() mockoptions.default_vcs = "git" mockoptions.skip_requirements_regex = None for req in parse_requirements(filename, options=mockoptions): self.reqs[req.name] = { "pip_req": req, "url": req.url, } if options["github_api_token"]: self.github_api_token = options["github_api_token"] elif os.environ.get("GITHUB_API_TOKEN"): self.github_api_token = os.environ.get("GITHUB_API_TOKEN") else: self.github_api_token = None # only 50 requests per hour self.check_pypi() if HAS_REQUESTS: self.check_github() else: print( self.style.ERROR( "Cannot check github urls. The requests library is not installed. ( pip install requests )" )) self.check_other()
def handle(self, *args, **kwargs): self.style = color_style() installed_apps = dict((a.__name__.rsplit('.', 1)[0], a) for a in get_apps()) # Make sure we always have args app = kwargs.pop('app')[0] if not installed_apps.get(app): print(self.style.WARN('This command requires an existing app name as argument')) print(self.style.WARN('Available apps:')) for app in sorted(installed_apps): print(self.style.WARN(' %s' % app)) sys.exit(1) model_res = [] for arg in args[1:]: model_res.append(re.compile(arg, re.IGNORECASE)) self.handle_app(app, model_res, **kwargs)
def handle(self, *args, **options): self.style = color_style() app_name = options['app_name'] try: app = apps.get_app_config(app_name) except LookupError: print(self.style.WARN('This command requires an existing app name as argument')) print(self.style.WARN('Available apps:')) app_labels = [app.label for app in apps.get_app_configs()] for label in sorted(app_labels): print(self.style.WARN(' %s' % label)) sys.exit(1) model_res = [] for arg in options['model_name']: model_res.append(re.compile(arg, re.IGNORECASE)) self.stdout.write(AdminApp(app, model_res, **options).__str__())
def handle_noargs(self, **options): self.style = color_style() self.options = options if options["requirements"]: req_files = options["requirements"] elif os.path.exists("requirements.txt"): req_files = ["requirements.txt"] elif os.path.exists("requirements"): req_files = ["requirements/{0}".format(f) for f in os.listdir("requirements") if os.path.isfile(os.path.join("requirements", f)) and f.lower().endswith(".txt")] else: sys.exit("requirements not found") self.reqs = {} for filename in req_files: class Object(object): pass mockoptions = Object() mockoptions.default_vcs = "git" mockoptions.skip_requirements_regex = None for req in parse_requirements(filename, options=mockoptions): self.reqs[req.name] = { "pip_req": req, "url": req.url, } if options["github_api_token"]: self.github_api_token = options["github_api_token"] elif os.environ.get("GITHUB_API_TOKEN"): self.github_api_token = os.environ.get("GITHUB_API_TOKEN") else: self.github_api_token = None # only 50 requests per hour self.check_pypi() if HAS_REQUESTS: self.check_github() else: print(self.style.ERROR("Cannot check github urls. The requests library is not installed. ( pip install requests )")) self.check_other()
def handle(self, *args, **kwargs): self.style = color_style() installed_apps = dict((a.__name__.rsplit(".", 1)[0], a) for a in get_apps()) # Make sure we always have args if not args: args = [False] app = installed_apps.get(args[0]) if not app: print(self.style.WARN("This command requires an existing app name as argument")) print(self.style.WARN("Available apps:")) for app in sorted(installed_apps): print(self.style.WARN(" %s" % app)) sys.exit(1) model_res = [] for arg in args[1:]: model_res.append(re.compile(arg, re.IGNORECASE)) self.handle_app(app, model_res, **kwargs)
def _collect_data(self, *args, **options): style = color_style() response = [] apps = models.get_apps() for app in apps: appmodels = get_models(app) abstract_models = [] for appmodel in appmodels: abstract_models = abstract_models + \ [abstract_model for abstract_model in appmodel.__bases__ if hasattr(abstract_model, '_meta') \ and abstract_model._meta.abstract] abstract_models = list(set(abstract_models)) appmodels = abstract_models + appmodels for _model in appmodels: response.append("%(model)s\t%(count)s" % { 'model': style.INFO(_model.__name__) if not options['no_color'] else _model.__name__, 'count': _model.objects.count() } ) return response
def handle(self, *args, **options): if args: appname, = args style = color_style() if settings.ADMIN_FOR: settings_modules = [ __import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR ] else: settings_modules = [settings] views = [] for settings_mod in settings_modules: try: urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, ['']) except Exception, e: if options.get('traceback', None): import traceback traceback.print_exc() print style.ERROR( "Error occurred while trying to load %s: %s" % (settings_mod.ROOT_URLCONF, str(e))) continue view_functions = extract_views_from_urlpatterns( urlconf.urlpatterns) for (func, regex, url_name) in view_functions: func_name = hasattr(func, '__name__') and func.__name__ or repr(func) views.append( "%(url)s\t%(module)s.%(name)s\t%(url_name)s" % { 'name': style.MODULE_NAME(func_name), 'module': style.MODULE(func.__module__), 'url_name': style.URL_NAME(url_name or ''), 'url': style.URL(simplify_regex(regex)) })
import click import json import re import sys from django.core.management.base import OutputWrapper from django_extensions.management.color import color_style LOG_RE = "^\\[(?P<timestamp>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{6})\\] (?P<level>\\w+) \\[(?P<code_ns>[^:]+):(?P<code_line>\\d+)\\] (?P<jmsg>.*)$" h = re.compile(LOG_RE) stdout = OutputWrapper(sys.stdout) stderr = OutputWrapper(sys.stderr) style = color_style() stderr.style_func = style.ERROR @click.command() @click.argument('input', type=click.Path(exists=True)) @click.argument('user', type=str) def user_logs(input, user): logs = [] stdout.write( style.SUCCESS("Parsing '{}' logs from '{}' ".format(user, input))) with open(input, 'r') as f: errors_count = 0 for l in f: matches = h.match(l) level = matches.group('level') try: jmsg = json.loads(matches.group('jmsg'))[0]
def handle(self, *args, **options): style = no_style() if options["no_color"] else color_style() language = options["language"] if language is not None: translation.activate(language) self.LANGUAGES = [ (code, name) for code, name in getattr(settings, "LANGUAGES", []) if code == language ] else: self.LANGUAGES = getattr(settings, "LANGUAGES", ((None, None),)) decorator = options["decorator"] if not decorator: decorator = ["login_required"] format_style = options["format_style"] if format_style not in FMTR: raise CommandError( "Format style '%s' does not exist. Options: %s" % (format_style, ", ".join(sorted(FMTR.keys())),) ) pretty_json = format_style == "pretty-json" if pretty_json: format_style = "json" fmtr = FMTR[format_style] urlconf = options["urlconf"] views = [] if not hasattr(settings, urlconf): raise CommandError( "Settings module {} does not have the attribute {}.".format( settings, urlconf ) ) try: urlconf = __import__(getattr(settings, urlconf), {}, {}, [""]) except Exception as e: if options["traceback"]: import traceback traceback.print_exc() raise CommandError( "Error occurred while trying to load %s: %s" % (getattr(settings, urlconf), str(e)) ) view_functions = self.extract_views_from_urlpatterns(urlconf.urlpatterns) for (func, regex, url_name) in view_functions: if hasattr(func, "__globals__"): func_globals = func.__globals__ elif hasattr(func, "func_globals"): func_globals = func.func_globals else: func_globals = {} decorators = [d for d in decorator if d in func_globals] if isinstance(func, functools.partial): func = func.func decorators.insert(0, "functools.partial") if hasattr(func, "__name__"): func_name = func.__name__ elif hasattr(func, "__class__"): func_name = "%s()" % func.__class__.__name__ else: func_name = re.sub(r" at 0x[0-9a-f]+", "", repr(func)) module = "{0}.{1}".format(func.__module__, func_name) url_name = url_name or "" url = simplify_regex(regex) decorator = ", ".join(decorators) if format_style == "json": views.append( { "url": url, "module": module, "name": url_name, "decorators": decorator, } ) else: views.append( fmtr.format( module="{0}.{1}".format( style.MODULE(func.__module__), style.MODULE_NAME(func_name) ), url_name=style.URL_NAME(url_name), url=style.URL(url), decorator=decorator, ).strip() ) if not options["unsorted"] and format_style != "json": views = sorted(views) if format_style == "aligned": views = [row.split(",", 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] views = [ " ".join( "{0:<{1}}".format(cdata, width) for width, cdata in zip(widths, row) ) for row in views ] elif format_style == "table": # Reformat all data and show in a table format views = [row.split(",", 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] table_views = [] header = ( style.MODULE_NAME("URL"), style.MODULE_NAME("Module"), style.MODULE_NAME("Name"), style.MODULE_NAME("Decorator"), ) table_views.append( " | ".join( "{0:<{1}}".format(title, width) for width, title in zip(widths, header) ) ) table_views.append("-+-".join("-" * width for width in widths)) for row in views: table_views.append( " | ".join( "{0:<{1}}".format(cdata, width) for width, cdata in zip(widths, row) ) ) # Replace original views so we can return the same object views = table_views elif format_style == "json": if pretty_json: return json.dumps(views, indent=4) return json.dumps(views) return "\n".join([v for v in views if settings.ADMIN_URL not in v]) + "\n"
def handle(self, *args, **options): if args: appname, = args if options.get('no_color', False): style = no_style() else: style = color_style() if getattr(settings, 'ADMIN_FOR', None): settings_modules = [ __import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR ] else: settings_modules = [settings] self.LANGUAGES = getattr(settings, 'LANGUAGES', ((None, None), )) language = options.get('language', None) if language is not None: translation.activate(language) self.LANGUAGES = [(code, name) for code, name in self.LANGUAGES if code == language] decorator = options.get('decorator') if not decorator: decorator = ['login_required'] format_style = options.get('format_style') if format_style not in FMTR: raise CommandError( "Format style '%s' does not exist. Options: %s" % (format_style, FMTR.keys())) pretty_json = format_style == 'pretty-json' if pretty_json: format_style = 'json' fmtr = FMTR[format_style] urlconf = options.get('urlconf') views = [] for settings_mod in settings_modules: if not hasattr(settings_mod, urlconf): raise CommandError( "Settings module {} does not have the attribute {}.". format(settings_mod, urlconf)) try: urlconf = __import__(getattr(settings_mod, urlconf), {}, {}, ['']) except Exception as e: if options.get('traceback', None): import traceback traceback.print_exc() print( style.ERROR("Error occurred while trying to load %s: %s" % (getattr(settings_mod, urlconf), str(e)))) continue view_functions = self.extract_views_from_urlpatterns( urlconf.urlpatterns) for (func, regex, url_name) in view_functions: if hasattr(func, '__globals__'): func_globals = func.__globals__ elif hasattr(func, 'func_globals'): func_globals = func.func_globals else: func_globals = {} decorators = [d for d in decorator if d in func_globals] if isinstance(func, functools.partial): func = func.func decorators.insert(0, 'functools.partial') if hasattr(func, '__name__'): func_name = func.__name__ elif hasattr(func, '__class__'): func_name = '%s()' % func.__class__.__name__ else: func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func)) module = '{0}.{1}'.format(func.__module__, func_name) url_name = url_name or '' url = simplify_regex(regex) decorator = ', '.join(decorators) if format_style == 'json': views.append({ "url": url, "module": module, "name": url_name, "decorators": decorator }) else: views.append( fmtr.format( module='{0}.{1}'.format( style.MODULE(func.__module__), style.MODULE_NAME(func_name)), url_name=style.URL_NAME(url_name), url=style.URL(url), decorator=decorator, )) if not options.get('unsorted', False) and format_style != 'json': views = sorted(views) if format_style == 'aligned': views = [row.split(',', 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] views = [ ' '.join('{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row)) for row in views ] elif format_style == 'table': # Reformat all data and show in a table format views = [row.split(',', 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] table_views = [] header = (style.MODULE_NAME('URL'), style.MODULE_NAME('Module'), style.MODULE_NAME('Name'), style.MODULE_NAME('Decorator')) table_views.append(' | '.join( '{0:<{1}}'.format(title, width) for width, title in zip(widths, header))) table_views.append('-+-'.join('-' * width for width in widths)) for row in views: table_views.append(' | '.join( '{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row))) # Replace original views so we can return the same object views = table_views elif format_style == 'json': if pretty_json: return json.dumps(views, indent=4) return json.dumps(views) return "\n".join([v for v in views]) + "\n"
def handle(self, *args, **options): style = no_style() if options['no_color'] else color_style() language = options['language'] if language is not None: translation.activate(language) self.LANGUAGES = [ (code, name) for code, name in getattr(settings, 'LANGUAGES', []) if code == language ] else: self.LANGUAGES = getattr(settings, 'LANGUAGES', ((None, None), )) decorator = options['decorator'] if not decorator: decorator = ['login_required'] host = options['base'] mock_pk = options['mock_pk'] format_style = options['format_style'] if format_style not in FMTR: raise CommandError( "Format style '%s' does not exist. Options: %s" % ( format_style, ", ".join(sorted(FMTR.keys())), )) pretty_json = format_style == 'pretty-json' if pretty_json: format_style = 'json' fmtr = FMTR[format_style] urlconf = options['urlconf'] views = [] if not hasattr(settings, urlconf): raise CommandError( "Settings module {} does not have the attribute {}.".format( settings, urlconf)) try: urlconf = __import__(getattr(settings, urlconf), {}, {}, ['']) except Exception as e: if options['traceback']: import traceback traceback.print_exc() raise CommandError("Error occurred while trying to load %s: %s" % (getattr(settings, urlconf), str(e))) view_functions = self.extract_views_from_urlpatterns( urlconf.urlpatterns) coverage = len(view_functions) for (func, regex, url_name) in view_functions: if hasattr(func, '__globals__'): func_globals = func.__globals__ elif hasattr(func, 'func_globals'): func_globals = func.func_globals else: func_globals = {} decorators = [d for d in decorator if d in func_globals] try: p = re.compile(r'<.*?>|\(.*?\)|\[.*?\]') url = p.sub(str(mock_pk), regex).replace('^', '').replace( '\\', '').replace('$', '') #mock pk 1 conn = urllib.request.urlopen(host + url) response = conn.getcode() conn.close() except urllib.error.HTTPError as e: response = str(e.code) coverage -= 1 except urllib.error.URLError as e: response = e.reason coverage -= 1 except Exception as e: print(url, e) coverage -= 1 response = e if isinstance(func, functools.partial): func = func.func decorators.insert(0, 'functools.partial') if hasattr(func, '__name__'): func_name = func.__name__ elif hasattr(func, '__class__'): func_name = '%s()' % func.__class__.__name__ else: func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func)) module = '{0}.{1}'.format(func.__module__, func_name) url_name = url_name or '' url = simplify_regex(regex) decorator = ', '.join(decorators) code = response if format_style == 'json': views.append({ "url": url, "module": module, "name": url_name, "decorators": decorator, "code": code }) else: views.append( fmtr.format(module='{0}.{1}'.format( style.MODULE(func.__module__), style.MODULE_NAME(func_name)), url_name=style.URL_NAME(url_name), url=style.URL(url), decorator=decorator, code=code).strip()) if not options['unsorted'] and format_style != 'json': views = sorted(views) if format_style == 'aligned': views = [row.split(',', 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] views = [ ' '.join('{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row)) for row in views ] elif format_style == 'table': # Reformat all data and show in a table format views = [row.split(',', 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] table_views = [] header = (style.MODULE_NAME('URL'), style.MODULE_NAME('Module'), style.MODULE_NAME('Name'), style.MODULE_NAME('Decorator')) table_views.append(' | '.join( '{0:<{1}}'.format(title, width) for width, title in zip(widths, header))) table_views.append('-+-'.join('-' * width for width in widths)) for row in views: table_views.append(' | '.join( '{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row))) # Replace original views so we can return the same object views = table_views elif format_style == 'json': if pretty_json: return json.dumps(views, indent=4) return json.dumps(views) return "\n".join([v for v in views ]) + "\n coverage: " + str(coverage) + " / " + str( len(view_functions)) + "\n"
def handle(self, *args, **options): if args: appname, = args style = color_style() if getattr(settings, 'ADMIN_FOR', None): settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR] else: settings_modules = [settings] self.LANGUAGES = getattr(settings, 'LANGUAGES', ((None, None), )) language = options.get('language', None) if language is not None: translation.activate(language) self.LANGUAGES = [(code, name) for code, name in self.LANGUAGES if code == language] decorator = options.get('decorator') if not decorator: decorator = ['login_required'] format_style = options.get('format_style') if format_style not in FMTR: raise CommandError("Format style '%s' does not exist. Options: %s" % (format_style, FMTR.keys())) pretty_json = format_style == 'pretty-json' if pretty_json: format_style = 'json' fmtr = FMTR[format_style] urlconf = options.get('urlconf') views = [] for settings_mod in settings_modules: if not hasattr(settings_mod, urlconf): raise CommandError("Settings module {} does not have the attribute {}.".format(settings_mod, urlconf)) try: urlconf = __import__(getattr(settings_mod, urlconf), {}, {}, ['']) except Exception as e: if options.get('traceback', None): import traceback traceback.print_exc() print(style.ERROR("Error occurred while trying to load %s: %s" % (getattr(settings_mod, urlconf), str(e)))) continue view_functions = self.extract_views_from_urlpatterns(urlconf.urlpatterns) for (func, regex, url_name) in view_functions: if hasattr(func, '__globals__'): func_globals = func.__globals__ elif hasattr(func, 'func_globals'): func_globals = func.func_globals else: func_globals = {} decorators = [d for d in decorator if d in func_globals] if isinstance(func, functools.partial): func = func.func decorators.insert(0, 'functools.partial') if hasattr(func, '__name__'): func_name = func.__name__ elif hasattr(func, '__class__'): func_name = '%s()' % func.__class__.__name__ else: func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func)) module = '{0}.{1}'.format(func.__module__, func_name) url_name = url_name or '' url = simplify_regex(regex) decorator = ', '.join(decorators) if format_style == 'json': views.append({"url": url, "module": module, "name": url_name, "decorators": decorator}) else: views.append(fmtr.format( module='{0}.{1}'.format(style.MODULE(func.__module__), style.MODULE_NAME(func_name)), url_name=style.URL_NAME(url_name), url=style.URL(url), decorator=decorator, )) if not options.get('unsorted', False) and format_style != 'json': views = sorted(views) if format_style == 'aligned': views = [row.split(',', 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] views = [ ' '.join('{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row)) for row in views ] elif format_style == 'table': # Reformat all data and show in a table format views = [row.split(',', 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] table_views = [] header = (style.MODULE_NAME('URL'), style.MODULE_NAME('Module'), style.MODULE_NAME('Name'), style.MODULE_NAME('Decorator')) table_views.append( ' | '.join('{0:<{1}}'.format(title, width) for width, title in zip(widths, header)) ) table_views.append('-+-'.join('-' * width for width in widths)) for row in views: table_views.append( ' | '.join('{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row)) ) # Replace original views so we can return the same object views = table_views elif format_style == 'json': if pretty_json: return json.dumps(views, indent=4) return json.dumps(views) return "\n".join([v for v in views]) + "\n"
def handle(self, *args, **options): if args: appname, = args style = color_style() if settings.ADMIN_FOR: settings_modules = [ __import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR ] else: settings_modules = [settings] language = options.get('language', None) if language is not None: activate(language) decorator = options.get('decorator') if decorator is None: decorator = 'login_required' format_style = options.get('format_style', 'dense') if format_style not in FMTR: raise Exception("Format style '%s' does not exist. Options: %s" % (format_style, FMTR.keys())) fmtr = FMTR[format_style] views = [] for settings_mod in settings_modules: try: urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, ['']) except Exception as e: if options.get('traceback', None): import traceback traceback.print_exc() print( style.ERROR("Error occurred while trying to load %s: %s" % (settings_mod.ROOT_URLCONF, str(e)))) continue view_functions = extract_views_from_urlpatterns( urlconf.urlpatterns) for (func, regex, url_name) in view_functions: if hasattr(func, '__name__'): func_name = func.__name__ elif hasattr(func, '__class__'): func_name = '%s()' % func.__class__.__name__ else: func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func)) func_globals = func.__globals__ if six.PY3 else func.func_globals views.append( fmtr % { 'name': style.MODULE_NAME(func_name), 'module': style.MODULE(func.__module__), 'url_name': style.URL_NAME(url_name or ''), 'url': style.URL(simplify_regex(regex)), 'decorator': decorator if decorator in func_globals else '', }) if not options.get('unsorted', False): views = sorted(views) return "\n".join([v for v in views]) + "\n"
def handle(self, *args, **options): if args: appname, = args style = color_style() if settings.ADMIN_FOR: settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR] else: settings_modules = [settings] language = options.get('language', None) if language is not None: activate(language) decorator = options.get('decorator') if not decorator: decorator = ['login_required'] format_style = options.get('format_style') if format_style not in FMTR: raise CommandError("Format style '%s' does not exist. Options: %s" % (format_style, FMTR.keys())) fmtr = FMTR[format_style] views = [] for settings_mod in settings_modules: try: urlconf = __import__(settings_mod.ROOT_URLCONF, {}, {}, ['']) except Exception as e: if options.get('traceback', None): import traceback traceback.print_exc() print(style.ERROR("Error occurred while trying to load %s: %s" % (settings_mod.ROOT_URLCONF, str(e)))) continue view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns) for (func, regex, url_name) in view_functions: if hasattr(func, '__globals__'): func_globals = func.__globals__ elif hasattr(func, 'func_globals'): func_globals = func.func_globals else: func_globals = {} decorators = [d for d in decorator if d in func_globals] if isinstance(func, functools.partial): func = func.func decorators.insert(0, 'functools.partial') if hasattr(func, '__name__'): func_name = func.__name__ elif hasattr(func, '__class__'): func_name = '%s()' % func.__class__.__name__ else: func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func)) views.append(fmtr.format( module='{0}.{1}'.format(style.MODULE(func.__module__), style.MODULE_NAME(func_name)), url_name=style.URL_NAME(url_name or ''), url=style.URL(simplify_regex(regex)), decorator=', '.join(decorators), )) if not options.get('unsorted', False): views = sorted(views) if format_style == 'aligned': views = [row.split(',', 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] views = [ ' '.join('{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row)) for row in views ] elif format_style == 'table': # Reformat all data and show in a table format views = [row.split(',', 3) for row in views] widths = [len(max(columns, key=len)) for columns in zip(*views)] table_views = [] header = (style.MODULE_NAME('URL'), style.MODULE_NAME('Module'), style.MODULE_NAME('Name'), style.MODULE_NAME('Decorator')) table_views.append( ' | '.join('{0:<{1}}'.format(title, width) for width, title in zip(widths, header)) ) table_views.append('-+-'.join('-' * width for width in widths)) for row in views: table_views.append( ' | '.join('{0:<{1}}'.format(cdata, width) for width, cdata in zip(widths, row)) ) # Replace original views so we can return the same object views = table_views return "\n".join([v for v in views]) + "\n"
def list_model_info(self, options): style = color_style() INFO = getattr(style, "INFO", lambda x: x) WARN = getattr(style, "WARN", lambda x: x) BOLD = getattr(style, "BOLD", lambda x: x) FIELD_CLASS = (True if options.get("field_class", None) is not None else getattr(settings, "MODEL_INFO_FIELD_CLASS", False)) DB_TYPE = True if options.get( "db_type", None) is not None else getattr( settings, "MODEL_INFO_DB_TYPE", False) SIGNATURE = (True if options.get("signature", None) is not None else getattr(settings, "MODEL_INFO_SIGNATURE", False)) ALL_METHODS = (True if options.get("all_methods", None) is not None else getattr(settings, "MODEL_INFO_ALL_METHODS", False)) MODEL = (options.get("model") if options.get("model", None) is not None else getattr(settings, "MODEL_INFO_MODEL", False)) default_methods = [ "check", "clean", "clean_fields", "date_error_message", "delete", "from_db", "full_clean", "get_absolute_url", "get_deferred_fields", "prepare_database_save", "refresh_from_db", "save", "save_base", "serializable_value", "unique_error_message", "validate_unique", ] if MODEL: model_list = [django_apps.get_model(MODEL)] else: model_list = sorted(django_apps.get_models(), key=lambda x: (x._meta.app_label, x._meta.object_name), reverse=False) for model in model_list: self.stdout.write( INFO(model._meta.app_label + "." + model._meta.object_name)) self.stdout.write(BOLD(HALFTAB + "Fields:")) for field in model._meta.get_fields(): field_info = TAB + field.name + " -" if FIELD_CLASS: try: field_info += " " + field.__class__.__name__ except TypeError: field_info += (WARN(" TypeError (field_class)")) except AttributeError: field_info += (WARN(" AttributeError (field_class)")) if FIELD_CLASS and DB_TYPE: field_info += "," if DB_TYPE: try: field_info += " " + field.db_type( connection=connection) except TypeError: field_info += (WARN(" TypeError (db_type)")) except AttributeError: field_info += (WARN(" AttributeError (db_type)")) self.stdout.write(field_info) if ALL_METHODS: self.stdout.write(BOLD(HALFTAB + "Methods (all):")) else: self.stdout.write( BOLD(HALFTAB + "Methods (non-private/internal):")) for method_name in dir(model): try: method = getattr(model, method_name) if ALL_METHODS: if callable(method) and not method_name[0].isupper(): if SIGNATURE: signature = inspect.signature(method) else: signature = "()" self.stdout.write(TAB + method_name + str(signature)) else: if (callable(method) and not method_name.startswith("_") and method_name not in default_methods and not method_name[0].isupper()): if SIGNATURE: signature = inspect.signature(method) else: signature = "()" self.stdout.write(TAB + method_name + str(signature)) except AttributeError: self.stdout.write(TAB + method_name + WARN(" - AttributeError")) except ValueError: self.stdout.write( TAB + method_name + WARN(" - ValueError (could not identify signature)")) self.stdout.write("\n") self.stdout.write(INFO("Total Models Listed: %d" % len(model_list)))