o 3aX@sdZddlZddlZddlZddlmZmZddlmZddl Z ddl m Z ddl m Z ddlmZmZddlmZmZdd lmZd ZGd d d eZGd ddeZGdddeZddZddZGdddeZGdddeZGdddZGdddeZ GdddeZ!dS)z Base classes for writing management commands (named commands which can be executed through ``django-admin`` or ``manage.py``). N)ArgumentParser HelpFormatter) TextIOBase)checks)ImproperlyConfigured) color_styleno_style)DEFAULT_DB_ALIAS connections)RemovedInDjango41Warning__all__cs&eZdZdZddfdd ZZS) CommandErrora Exception class indicating a problem while executing a management command. If this exception is raised during the execution of a management command, it will be caught and turned into a nicely-printed error message to the appropriate output stream (i.e., stderr); as a result, raising this exception (with a sensible description of the error) is the preferred way to indicate that something has gone wrong in the execution of a command. ) returncodecs||_tj|i|dSN)rsuper__init__)selfrargskwargs __class__=/usr/lib/python3/dist-packages/django/core/management/base.pyr!szCommandError.__init__)__name__ __module__ __qualname____doc__r __classcell__rrrrr s r c@seZdZdZdS)SystemCheckErrorzC The system check framework detected unrecoverable errors. N)rrrrrrrrr&srcsBeZdZdZdddfdd Zd fdd Zfdd ZZS) CommandParserz Customized ArgumentParser class to improve some error messages and prevent SystemExit in several occasions, as SystemExit is unacceptable when a command is called programmatically. N)missing_args_messagecalled_from_command_linec s"||_||_tjdi|dS)Nr)r!r"rr)rr!r"rrrrr3szCommandParser.__init__cs6|jr|stdd|Ds||jt||S)Ncss|] }|d VqdS)-N) startswith).0argrrr ;sz+CommandParser.parse_args..)r!anyerrorr parse_args)rr namespacerrrr*8s zCommandParser.parse_argscs"|jr t|dStd|)Nz Error: %s)r"rr)r )rmessagerrrr)?s zCommandParser.error)NN)rrrrrr*r)rrrrrr -s r cCs0|jr |jtjd<|jrtjd|jdSdS)z Include any default options that all commands should accept here so that ManagementUtility can handle them before searching for user commands. DJANGO_SETTINGS_MODULErN)settingsosenviron pythonpathsyspathinsert)optionsrrrhandle_default_optionsFs  r6csfdd}|S)zEDecorator that forces a command to run with translations deactivated.c sZddlm}|}|z|i|}W|dur |||S|dur,||ww)Nr) translation) django.utilsr7 get_languagedeactivate_allactivate)rrr7 saved_localeres handle_funcrrwrappedTs   z no_translations..wrappedr)r?r@rr>rno_translationsRs  rAcs<eZdZdZhdZddZfddZfddZZS) DjangoHelpFormatterz Customized formatter so that command-specific arguments appear in the --help output before arguments common to all commands. > --version --no-color --settings --traceback --verbosity --pythonpath --force-color --skip-checkscst|fdddS)Ncst|jj@tkSr)setoption_strings show_last)arrrnz8DjangoHelpFormatter._reordered_actions..)key)sortedractionsrrOr_reordered_actionsks z&DjangoHelpFormatter._reordered_actionscs&tj|||g|Ri|dSr)r add_usagerV)rusagerUrrrrrrWqs&zDjangoHelpFormatter.add_usagecst||dSr)r add_argumentsrVrTrrrrYtz!DjangoHelpFormatter.add_arguments) rrrrrMrVrWrYrrrrrrBas  rBc@sVeZdZdZeddZejddZdddZdd Zd d Z d d Z dddZ dS) OutputWrapperz& Wrapper around stdout/stderr cCs|jSr) _style_funcrOrrr style_func|szOutputWrapper.style_funccCs$|r |r ||_dSdd|_dS)NcS|SrrxrrrrPz*OutputWrapper.style_func..)isattyr\)rr]rrrr]s   cCs||_d|_||_dSr)_outr]ending)routrerrrrs zOutputWrapper.__init__cCs t|j|Sr)getattrrd)rnamerrr __getattr__s zOutputWrapper.__getattr__cCst|jdr |jdSdS)Nflush)hasattrrdrjrOrrrrjs zOutputWrapper.flushcCst|jdo |jS)Nrb)rkrdrbrOrrrrbrZzOutputWrapper.isattyNcCsF|dur|jn|}|r||s||7}|p|j}|j||dSr)reendswithr]rdwrite)rmsgr]rerrrrns  zOutputWrapper.write)rc)rlNN) rrrrpropertyr]setterrrirjrbrnrrrrr[xs   r[c@seZdZdZdZdZdZdZdZdZ dZ ddd Z d d Z d d Z ddZddZddZddZddddejdfddZddZddZdS) BaseCommanda The base class from which all management commands ultimately derive. Use this class if you want access to all of the mechanisms which parse the command-line arguments and work out what code to call in response; if you don't need to change any of that behavior, consider using one of the subclasses defined in this file. If you are interested in overriding/customizing various aspects of the command-parsing and -execution behavior, the normal flow works as follows: 1. ``django-admin`` or ``manage.py`` loads the command class and calls its ``run_from_argv()`` method. 2. The ``run_from_argv()`` method calls ``create_parser()`` to get an ``ArgumentParser`` for the arguments, parses them, performs any environment changes requested by options like ``pythonpath``, and then calls the ``execute()`` method, passing the parsed arguments. 3. The ``execute()`` method attempts to carry out the command by calling the ``handle()`` method with the parsed arguments; any output produced by ``handle()`` will be printed to standard output and, if the command is intended to produce a block of SQL statements, will be wrapped in ``BEGIN`` and ``COMMIT``. 4. If ``handle()`` or ``execute()`` raised any exception (e.g. ``CommandError``), ``run_from_argv()`` will instead print an error message to ``stderr``. Thus, the ``handle()`` method is typically the starting point for subclasses; many built-in commands and command types either place all of their logic in ``handle()``, or perform some additional parsing work in ``handle()`` and then delegate from it to more specialized methods as needed. Several attributes affect behavior at various steps along the way: ``help`` A short description of the command, which will be printed in help messages. ``output_transaction`` A boolean indicating whether the command outputs SQL statements; if ``True``, the output will automatically be wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is ``False``. ``requires_migrations_checks`` A boolean; if ``True``, the command prints a warning if the set of migrations on disk don't match the migrations in the database. ``requires_system_checks`` A list or tuple of tags, e.g. [Tags.staticfiles, Tags.models]. System checks registered in the chosen tags will be checked for errors prior to executing the command. The value '__all__' can be used to specify that all system checks should be performed. Default value is '__all__'. To validate an individual application's models rather than all applications' models, call ``self.check(app_configs)`` from ``handle()``, where ``app_configs`` is the list of application's configuration provided by the app registry. ``stealth_options`` A tuple of any options the command uses which aren't defined by the argument parser. rlFr )stderrstdoutrNcCst|ptj|_t|p tj|_|r|rtd|rt|_n t||_|jj|j_ |j dvr=t dt |j r:tng|_ t|j ttfsN|j tkrPtddSdS)Nz4'no_color' and 'force_color' can't be used together.)FTzUsing a boolean value for requires_system_checks is deprecated. Use '__all__' instead of True, and [] (an empty list) instead of False.z/requires_system_checks must be a list or tuple.)r[r2rtrsr rstylerERRORr]requires_system_checkswarningswarnr ALL_CHECKS isinstancelisttuple TypeError)rrtrsno_color force_colorrrrrs(     zBaseCommand.__init__cCstS)z Return the Django version, which should be correct for all built-in Django commands. User-supplied commands can override this method to return their own version. )django get_versionrOrrrr szBaseCommand.get_versionc Kstddtj||f|jpdtt|ddt|ddd|}|jdd|d|jd d d t gd d d|jddd|jddd|jdddd|jdddd|jdddd|j rh|jdddd| ||S)z} Create and return the ``ArgumentParser`` which will be used to parse the arguments to this command. z%s %sNr!_called_from_command_line)prog descriptionformatter_classr!r"rCversion)actionrz-vrGr)rrz[Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output)defaulttypechoiceshelprEzThe Python path to a settings module, e.g. "myproject.settings.main". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used.)rrHzMA directory to add to the Python path, e.g. "/home/djangoprojects/myproject".rF store_truez Raise on CommandError exceptions)rrrDz"Don't colorize the command output.rIz)Force colorization of the command output.rJzSkip system checks.r) r r/r3basenamerrBrg add_argumentrintrwrY)r prog_name subcommandrparserrrr create_parsersN   zBaseCommand.create_parsercCsdS)zN Entry point for subclassed commands to add custom arguments. NrrrrrrrYCszBaseCommand.add_argumentscCs|||}|dS)za Print the help message for this command, derived from ``self.usage()``. N)r print_help)rrrrrrrrIs  zBaseCommand.print_helpcCsd|_||d|d}||dd}t|}|dd}t|zWz |j|i|Wn9tyh}z-|jr;t |t rL|j t |dd n |j d |jj|ft|jWYd}~nd}~wwWztWdSty{YdSwztWwtyYww) aZ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. If the ``--traceback`` option is present or the raised ``Exception`` is not ``CommandError``, raise it. TrrrNrrcSr^rrr_rrrrPiraz+BaseCommand.run_from_argv..z%s: %s)rrr*varspopr6executer tracebackr{rrsrnstrrrr2exitrr close_allr)rargvrr5 cmd_optionsrerrr run_from_argvQs8      zBaseCommand.run_from_argvcOs|dr |dr td|drtdd|_n |dr#t|_d|j_|dr/t|d|_|dr;t|d|_|j rS|d sS|j t krL| n|j |j d |j rZ| |j|i|}|r|jrt|d t}d |j|j||j|jf}|j||S) z Try to execute this command, performing system checks if needed (as controlled by the ``requires_system_checks`` attribute, except if force-skipped). rrz@The --no-color and --force-color options can't be used together.T)rNrtrs skip_checks)tagsdatabasez%s %s %s)r rrurrsr]getr[rtrwrzcheckrequires_migrations_checkscheck_migrationshandleoutput_transactionr r SQL_KEYWORDopsstart_transaction_sqlend_transaction_sqlrn)rrr5output connectionrrrrus8     zBaseCommand.executecstj||||d}d\}} } d} |rmdd|D} dd|D} dd|D}dd|D}d d|D}|d f|d f|d f| d f| dfg}|D]$\}}|rl| t|7} fdd|D}dt|}| d||f7} qH| rqd}|r| ry| d7} | d| dkrdn | dkrdnd| t|| f7} tfdd|Drjd|| | }t||| | }|r| rÈj |dddSj |dSdS)a Use the system check framework to validate entire Django project. Raise CommandError for any serious message (error or critical errors). If there are only light messages (like warnings), print them to stderr and don't raise an exception. ) app_configsrinclude_deployment_checks databases)rlrlrlrcSs$g|]}|jtjkr|s|qSr)levelrINFO is_silencedr%rrrr $z%BaseCommand.check..cS6g|]}tj|jkrtjkrnn|s|qSr)rrrWARNINGrrrrrr6cSrr)rrrrvrrrrrrrcSrr)rrvrCRITICALrrrrrrrcSs$g|]}tj|jkr|s|qSr)rrrrrrrrrr CRITICALSERRORSWARNINGSINFOSDEBUGSc3s8|]}|rjt|njt|VqdSr) is_seriousrurvrrrrOrrr's z$BaseCommand.check..rcz %s: %s z%System check identified some issues: z)System check identified %s (%s silenced).z no issuesrz1 issuez %s issuesc3s$|] }|o | VqdSr)rrr) fail_levelrrr's"zSystemCheckError: %scSr^rrr_rrrrPraz#BaseCommand.check..N) r run_checkslenjoinrSr(rurvrrsrnrt)rrrdisplay_num_errorsrrr all_issuesheaderbodyfootervisible_issue_countdebugsinfosrxerrors criticals sorted_issuesissues group_name formattedror)rrrrsb         zBaseCommand.checkc Csddlm}z|tt}Wn tyYdSw||jj}|rMt dd|D}|j |j dt|d|d|j |j d dSdS) zv Print a warning if the set of migrations on disk don't match the migrations in the database. r)MigrationExecutorNcSsh|]\}}|jqSr) app_label)r% migration backwardsrrr rQz/BaseCommand.check_migrations..z You have %(unapplied_migration_count)s unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): %(apps_waiting_migration)s.z, )unapplied_migration_countapps_waiting_migrationz-Run 'python manage.py migrate' to apply them.)django.db.migrations.executorrr r rmigration_planloadergraph leaf_nodesrSrtrnruNOTICErr)rrexecutorplanrrrrrs(   zBaseCommand.check_migrationscOtd)za The actual logic of the command. Subclasses must implement this method. z8subclasses of BaseCommand must provide a handle() methodNotImplementedError)rrr5rrrrzBaseCommand.handle)NNFF)rrrrrrrrrwbase_stealth_optionsstealth_optionsrrrrYrrrrrvrrrrrrrrrs,G 0$% E rrc@s,eZdZdZdZddZddZddZd S) AppCommanda A management command which takes one or more installed application labels as arguments, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_app_config()``, which will be called once for each application. z%Enter at least one application label.cCs|jddddddS)Nrr+zOne or more application label.)metavarnargsr)rrrrrrY rZzAppCommand.add_argumentsc sddlmz fdd|D}Wnttfy%}ztd|d}~wwg}|D]}|j|fi|}|r<||q*d|S)Nrappscsg|]}|qSr)get_app_config)r%rrrrrrQz%AppCommand.handle..z8%s. Are you sure your INSTALLED_APPS setting is correct?rc) django.appsr LookupError ImportErrorr handle_app_configappendr)r app_labelsr5rrr app_config app_outputrrrrs    zAppCommand.handlecKr)z Perform the command's actions for app_config, an AppConfig instance corresponding to an application label given on the command line. zBSubclasses of AppCommand must providea handle_app_config() method.r)rrr5rrrrszAppCommand.handle_app_configN)rrrrr!rYrrrrrrrs  rc@s4eZdZdZdZdeZddZddZdd Zd S) LabelCommanda A management command which takes one or more arbitrary arguments (labels) on the command line, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_label()``, which will be called once for each label. If the arguments should be names of installed applications, use ``AppCommand`` instead. labelzEnter at least one %s.cCs|jd|jdddS)Nrr)rr)rrrrrrrY5rZzLabelCommand.add_argumentscOs8g}|D]}|j|fi|}|r||qd|S)Nrc) handle_labelrr)rlabelsr5rr label_outputrrrr8s  zLabelCommand.handlecKr)z} Perform the command's actions for ``label``, which will be the string as given on the command line. z?subclasses of LabelCommand must provide a handle_label() methodr)rrr5rrrr@rzLabelCommand.handle_labelN) rrrrrr!rYrrrrrrr&s  r)"rr/r2rxargparserriorr django.corerdjango.core.exceptionsrdjango.core.management.colorrr django.dbr r django.utils.deprecationr rz Exceptionr rr r6rArBr[rrrrrrrrs2     &f$