B
    ;=[s                 @   sD  d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZ ddlmZmZ ddlZddlmZ dd	lmZ dd
lmZmZmZmZ ddlmZ ddlmZmZm Z  yddl!Z!W n e"k
r   dZ!Y nX G dd dej#Z$dd Z%drddZ&dd Z'dd Z(dd Z)dsddZ*dd Z+ej,dgd d!e+ddd"Z-G d#d$ d$e.Z/G d%d& d&e.Z0ej1e0dd'Z2d(d) Z3G d*d+ d+ej4Z5G d,d- d-e5Z6d.d/ Z7dtd0d1Z8d2d3 Z9G d4d5 d5ej:Z;d6d7 Z<ej=d8d9d:ej>d;d<d=d>d?ej>d@dAdBdCd?ej>dDe; dEdFej>dGej?dd!ddHe<d!dIdJej>dKddLd?ej>dMddNd?ej>dOddPd?ej>dQddRd?e2dSdT Z@ej=dUdVd:e3dWdX ZAej=dYdZd:ej>d[d\eBd]d^d_d`ej>daddbdce3ddde ZCe6dfjDejEdgkrdhndiejEdgkrdjndkdldmZFdudndoZGeHdpkr@eGddq dS )vu   
    flask.cli
    ~~~~~~~~~

    A simple command line application to run flask apps.

    :copyright: © 2010 by the Pallets team.
    :license: BSD, see LICENSE for more details.
    )print_functionN)update_wrapper)
attrgetter)LockThread)import_string   )__version__)
getargspec	iteritemsreraise	text_type)current_app)get_debug_flagget_envget_load_dotenvc               @   s   e Zd ZdZdS )NoAppExceptionz3Raised if an application cannot be found or loaded.N)__name__
__module____qualname____doc__ r   r   (lib/python3.7/site-packages/flask/cli.pyr   '   s   r   c          	      s  ddl m  x&dD ]}t||d}t| r|S qW  fddt|jD }t|dkr`|d S t|dkr~tdj|j	d	xrd
D ]j}t||d}t
|ryt| |}t| r|S W q tk
r   t|sԂ tdj||j	dY qX qW tdj|j	d	dS )zwGiven a module instance this tries to find the best possible
    application in the module or raises an exception.
    r   )Flask)appZapplicationNc                s   g | ]\}}t | r|qS r   )
isinstance).0kv)r   r   r   
<listcomp>:   s    z!find_best_app.<locals>.<listcomp>r   ztDetected multiple Flask applications in module "{module}". Use "FLASK_APP={module}:name" to specify the correct one.)module)
create_appZmake_appzDetected factory "{factory}" in module "{module}", but could not call it without arguments. Use "FLASK_APP='{module}:{factory}(args)'" to specify arguments.)factoryr    znFailed to find Flask application or factory in module "{module}". Use "FLASK_APP={module}:name to specify one.) r   getattrr   r   __dict__lenr   formatr   inspect
isfunctioncall_factory	TypeError_called_with_wrong_args)script_infor    Z	attr_namer   Zmatchesapp_factoryr   )r   r   find_best_app+   s8    





r/   r   c             C   s\   t |}|j}|j}d|kr*||d| iS |r6|| S |sVt|dkrV|dkrV|| S | S )zTakes an app factory, a ``script_info` object and  optionally a tuple
    of arguments. Checks for the existence of a script_info argument and calls
    the app_factory depending on that and the arguments provided.
    r-   r   N)r
   argsdefaultsr&   )r-   r.   Z	argumentsZ	args_specZ	arg_namesZarg_defaultsr   r   r   r*   d   s    r*   c             C   s@   t  d }z*x$|dk	r2|jj| jkr*dS |j}qW dS ~X dS )zCheck whether calling a function raised a ``TypeError`` because
    the call failed or because something in the factory raised the
    error.

    :param factory: the factory function that was called
    :return: true if the call failed
       NFT)sysexc_infotb_framef_code__code__tb_next)r"   tbr   r   r   r,   w   s    

r,   c       
   
   C   sd  ddl m} td|}|s,tdj|d| \}}yt||}W n0 tk
rv } zt|j	d W dd}~X Y nX t
|r8|rytdj|d}W q ttfk
r } ztd	j||d
W dd}~X Y qX nd}yt| ||}	W nF tk
r4 } z&t|s tdj|||jdW dd}~X Y nX n|}	t|	|rL|	S tdj|j|ddS )zChecks if the given string is a variable name or a function. If it is a
    function, it checks for specified arguments and whether it takes a
    ``script_info`` argument and calls the function with the appropriate
    arguments.
    r   )r   z%^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$z="{name}" is not a valid variable name or function expression.)nameNz	({args},))r0   z.Could not parse the arguments in "{app_name}".)eapp_namer   zc{e}
The factory "{app_name}" in module "{module}" could not be called with the specified arguments.)r;   r<   r    zFA valid Flask application was not obtained from "{module}:{app_name}".)r    r<   )flaskr   rematchr   r'   groupsr$   AttributeErrorr0   r(   r)   astZliteral_eval
ValueErrorSyntaxErrorr*   r+   r,   r   r   )
r-   r    r<   r   r?   r:   r0   attrr;   r   r   r   r   find_app_by_string   sD    
  
$rF   c             C   s   t j| } t j| d dkr0t j| d } t j| dkrLt j| } g }x6t j| \} }|| t jt j	| dsRP qRW t
jd | krt
jd|  d	|ddd S )	zGiven a filename this will try to calculate the python path, add it
    to the search path and return the actual module name that is expected.
    r   z.pyr   __init__z__init__.py.N)ospathrealpathsplitextbasenamedirnamesplitappendexistsjoinr3   insert)rK   module_namer:   r   r   r   prepare_import   s    
rV   Tc             C   s   d}yt | W nT tk
rd   t d jrFtdj|t dn|r\tdj|dnd S Y nX tj	| }|d krt
| |S t| ||S d S )NTrI   z:While importing "{name}", an ImportError was raised:

{tb})r:   r9   zCould not import "{name}".)r:   )
__import__ImportErrorr3   r4   r8   r   r'   	traceback
format_excmodulesr/   rF   )r-   rU   r<   raise_if_not_found__traceback_hide__r    r   r   r   
locate_app   s     


r^   c             C   s:   |r
| j rd S d}tj|ttjd | jd |   d S )Nz+Flask %(version)s
Python %(python_version)s)versionZpython_version)color)Zresilient_parsingclickechor	   r3   r_   r`   exit)ctxparamvaluemessager   r   r   get_version  s    


rh   z	--versionzShow the flask versionF)helpexpose_valuecallbackis_flagZis_eagerc               @   s:   e Zd ZdZdddZdd Zdd Zd	d
 Zdd ZdS )DispatchingAppa  Special application that dispatches to a Flask application which
    is imported by name in a background thread.  If an error happens
    it is recorded and shown as part of the WSGI handling which in case
    of the Werkzeug debugger means that it shows up in the browser.
    Fc             C   s4   || _ d | _t | _d | _|r(|   n|   d S )N)loader_appr   _lock_bg_loading_exc_info_load_unlocked_load_in_background)selfrn   use_eager_loadingr   r   r   rG     s    
zDispatchingApp.__init__c                s$    fdd}t |dd}|  d S )Nc           	      sF   d}  j 2 y   W n tk
r6   t  _Y nX W d Q R X d S )NT)rp   rr   	Exceptionr3   r4   rq   )r]   )rt   r   r   	_load_app*  s    z5DispatchingApp._load_in_background.<locals>._load_appr   )targetr0   )r   start)rt   rw   tr   )rt   r   rs   )  s    z"DispatchingApp._load_in_backgroundc             C   s$   d}| j }|d k	r d | _ t|  d S )NT)rq   r   )rt   r]   r4   r   r   r   _flush_bg_loading_exception4  s
    z*DispatchingApp._flush_bg_loading_exceptionc             C   s   d}|    | _}d | _|S )NT)rn   ro   rq   )rt   r]   rvr   r   r   rr   ;  s    zDispatchingApp._load_unlockedc          	   C   sX   d}| j d k	r|  ||S |   | j& | j d k	r<| j }n|  }|||S Q R X d S )NT)ro   r{   rp   rr   )rt   environZstart_responser]   r|   r   r   r   __call__A  s    

zDispatchingApp.__call__N)F)	r   r   r   r   rG   rs   r{   rr   r~   r   r   r   r   rm     s   

rm   c               @   s"   e Zd ZdZdddZdd ZdS )
ScriptInfoa  Help object to deal with Flask applications.  This is usually not
    necessary to interface with as it's used internally in the dispatching
    to click.  In future versions of Flask this object will most likely play
    a bigger role.  Typically it's created automatically by the
    :class:`FlaskGroup` but you can also manually create it and pass it
    onwards as click object.
    Nc             C   s(   |pt jd| _|| _i | _d | _d S )NZ	FLASK_APP)rJ   r}   getapp_import_pathr!   data_loaded_app)rt   r   r!   r   r   r   rG   W  s    zScriptInfo.__init__c             C   s   d}| j dk	r| j S d}| jdk	r0t| | j}nh| jrl| jdddg dd \}}t|}t| ||}n,x*dD ]"}t|}t| |ddd}|rrP qrW |std	t }|dk	r||_	|| _ |S )
zLoads the Flask app (if not yet loaded) and returns it.  Calling
        this multiple times will just result in the already loaded app to
        be returned.
        TN:r   r2   )zwsgi.pyzapp.pyF)r\   zCould not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.)
r   r!   r*   r   rP   rV   r^   r   r   debug)rt   r]   r   rK   r:   import_namer   r   r   r   load_appb  s0    

 
zScriptInfo.load_app)NN)r   r   r   r   rG   r   r   r   r   r   r   N  s   
r   )Zensurec                s   t j fdd}t| S )zWraps a callback so that it's guaranteed to be executed with the
    script's application context.  If callbacks are registered directly
    to the ``app.cli`` object then they are wrapped with this function
    by default unless it's disabled.
    c          	      s0   |  t   | j f||S Q R X d S )N)ensure_objectr   r   Zapp_contextZinvoke)Z__ctxr0   kwargs)fr   r   	decorator  s    z"with_appcontext.<locals>.decorator)ra   Zpass_contextr   )r   r   r   )r   r   with_appcontext  s    r   c               @   s    e Zd ZdZdd Zdd ZdS )AppGroupa   This works similar to a regular click :class:`~click.Group` but it
    changes the behavior of the :meth:`command` decorator so that it
    automatically wraps the functions in :func:`with_appcontext`.

    Not to be confused with :class:`FlaskGroup`.
    c                s"    dd fdd}|S )zThis works exactly like the method of the same name on a regular
        :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
        unless it's disabled by passing ``with_appcontext=False``.
        r   Tc                s$   rt | } tjjf | S )N)r   ra   Groupcommand)r   )r0   r   rt   wrap_for_ctxr   r   r     s    z#AppGroup.command.<locals>.decorator)pop)rt   r0   r   r   r   )r0   r   rt   r   r   r     s    zAppGroup.commandc             O   s    | dt tjj| f||S )zThis works exactly like the method of the same name on a regular
        :class:`click.Group` but it defaults the group class to
        :class:`AppGroup`.
        cls)
setdefaultr   ra   r   group)rt   r0   r   r   r   r   r     s    zAppGroup.groupN)r   r   r   r   r   r   r   r   r   r   r     s   r   c                   sB   e Zd ZdZdddZdd Zdd	 Zd
d Z fddZ  Z	S )
FlaskGroupa  Special subclass of the :class:`AppGroup` group that supports
    loading more commands from the configured Flask app.  Normally a
    developer does not have to interface with this class but there are
    some very advanced use cases for which it makes sense to create an
    instance of this.

    For information as of why this is useful see :ref:`custom-scripts`.

    :param add_default_commands: if this is True then the default run and
        shell commands wil be added.
    :param add_version_option: adds the ``--version`` option.
    :param create_app: an optional callback that is passed the script info and
        returns the loaded app.
    :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
        files to set environment variables. Will also change the working
        directory to the directory containing the first file found.

    .. versionchanged:: 1.0
        If installed, python-dotenv will be used to load environment variables
        from :file:`.env` and :file:`.flaskenv` files.
    TNc             K   sp   t |dd pd}|r"|t tj| fd|i| || _|| _|rf| t	 | t
 | t d| _d S )Nparamsr   F)listr   rQ   version_optionr   rG   r!   load_dotenvadd_commandrun_commandshell_commandroutes_command_loaded_plugin_commands)rt   Zadd_default_commandsr!   Zadd_version_optionr   Zextrar   r   r   r   rG     s    



zFlaskGroup.__init__c             C   sb   | j r
d S ydd l}W n tk
r0   d| _ d S X x$|dD ]}| | |j q>W d| _ d S )Nr   Tzflask.commands)r   pkg_resourcesrX   Ziter_entry_pointsr   loadr:   )rt   r   Zepr   r   r   _load_plugin_commands  s    z FlaskGroup._load_plugin_commandsc             C   sh   |    t| ||}|d k	r"|S |t}y"| j||}|d k	rL|S W n tk
rb   Y nX d S )N)r   r   get_commandr   r   r   clir   )rt   rd   r:   r|   infor   r   r   r     s    	
zFlaskGroup.get_commandc             C   sd   |    ttj| |}|t}y|| j	| W n t
k
rZ   t  Y nX t|S )N)r   setra   r   list_commandsr   r   updater   r   rv   rY   	print_excsorted)rt   rd   r|   r   r   r   r   r   	  s    
zFlaskGroup.list_commandsc                s^   dt jd< t| jrt  |d}|d kr8t| jd}||d< |dd tt	| j
||S )NtrueZFLASK_RUN_FROM_CLIobj)r!   Zauto_envvar_prefixZFLASK)rJ   r}   r   r   r   r   r!   r   superr   main)rt   r0   r   r   )	__class__r   r   r     s    


zFlaskGroup.main)TNTT)
r   r   r   r   rG   r   r   r   r   __classcell__r   r   )r   r   r     s    
r   c             C   s&   t j| |t| d t j|kS )zTake ``other`` and remove the length of ``path`` from it. Then join it
    to ``path``. If it is the original value, ``path`` is an ancestor of
    ``other``.N)rJ   rK   rS   r&   lstripsep)rK   otherr   r   r   _path_is_ancestor0  s    r   c             C   s   t dkr6| s$tjds$tjdr2tjddd dS | dk	rHt | S d}x>dD ]6}t j|dd	} | sjqR|dkr~tj| }t |  qRW |rt	 |krt
| |dk	S )
a  Load "dotenv" files in order of precedence to set environment variables.

    If an env var is already set it is not overwritten, so earlier files in the
    list are preferred over later files.

    Changes the current working directory to the location of the first file
    found, with the assumption that it is in the top level project directory
    and will be where the Python path should import local packages from.

    This is a no-op if `python-dotenv`_ is not installed.

    .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme

    :param path: Load the file at this location instead of searching.
    :return: ``True`` if a file was loaded.

    .. versionadded:: 1.0
    Nz.envz	.flaskenvzQ * Tip: There are .env files present. Do "pip install python-dotenv" to use them.Zyellow)fg)z.envz	.flaskenvT)Zusecwd)dotenvrJ   rK   rR   ra   sechor   Zfind_dotenvrO   getcwdchdir)rK   Znew_dirr:   r   r   r   r   7  s&    


r   c             C   s   t jddkrdS |dk	r<d|}|s2|d7 }t| td|  | dkrptjdd	d
 tjddd |dk	rtd|rdnd dS )z]Show extra startup messages the first time the server is run,
    ignoring the reloader.
    ZWERKZEUG_RUN_MAINr   Nz * Serving Flask app "{0}"z (lazy loading)z * Environment: {0}Z
productionzJ   WARNING: Do not use the development server in a production environment.Zred)r   z(   Use a production WSGI server instead.T)Zdimz * Debug mode: {0}ZonZoff)rJ   r}   r   r'   ra   rb   r   )envr   r   eager_loadingrg   r   r   r   show_server_bannerh  s    

r   c               @   s$   e Zd ZdZdZdd Zdd ZdS )CertParamTypezClick option type for the ``--cert`` option. Allows either an
    existing file, the string ``'adhoc'``, or an import for a
    :class:`~ssl.SSLContext` object.
    rK   c             C   s   t jdddd| _d S )NTF)rR   dir_okayresolve_path)ra   Path	path_type)rt   r   r   r   rG     s    zCertParamType.__init__c             C   s   y|  |||S  tjk
r   t||| }|dkrnydd l}W n" tk
rh   td||Y nX |S t|dd}tj	dk r|r|S nt
|tjr|S  Y nX d S )Nadhocr   z-Using ad-hoc certificates requires pyOpenSSL.T)Zsilent)r2      )r   ra   BadParameterSTRINGlowerOpenSSLrX   r   r3   version_infor   ssl
SSLContext)rt   rf   re   rd   r   r   r   r   r   convert  s&    
zCertParamType.convertN)r   r   r   r   r:   rG   r   r   r   r   r   r     s   r   c             C   s   | j d}|dk}tjdk r4|o0t|ttf }nt|tj}|dk	r|rZt	
d| ||rlt	
d| ||s~t	
d| |||f| j d< n|r|s|st	
d| ||S )	zThe ``--key`` option must be specified when ``--cert`` is a file.
    Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.
    certr   )r2   r   Nz.When "--cert" is "adhoc", "--key" is not used.z:When "--cert" is an SSLContext object, "--key is not used.z "--cert" must also be specified.zRequired when using "--cert".)r   r   r3   r   r   r   bytesr   r   ra   r   )rd   re   rf   r   Zis_adhocZ
is_contextr   r   r   _validate_key  s0    
r   runzRuns a development server.)Z
short_helpz--hostz-hz	127.0.0.1zThe interface to bind to.)defaultri   z--portz-pi  zThe port to bind to.z--certz(Specify a certificate file to use HTTPS.)typeri   z--key)rR   r   r   z2The key file to use when specifying a certificate.)r   rk   rj   ri   z--reload/--no-reloadzVEnable or disable the reloader. By default the reloader is active if debug is enabled.z--debugger/--no-debuggerzVEnable or disable the debugger. By default the debugger is active if debug is enabled.z--eager-loading/--lazy-loaderzaEnable or disable eager loading. By default eager loading is enabled if the reloader is disabled.z --with-threads/--without-threadsz!Enable or disable multithreading.c          	   C   sr   t  }|dkr|}|dkr|}|dkr,| }tt || j| t| j|d}	ddlm}
 |
|||	||||d dS )a  Run a local development server.

    This server is for development purposes only. It does not provide
    the stability, security, or performance of production WSGI servers.

    The reloader and debugger are enabled by default if
    FLASK_ENV=development or FLASK_DEBUG=1.
    N)ru   r   )
run_simple)Zuse_reloaderZuse_debuggerZthreadedZssl_context)r   r   r   r   rm   r   Zwerkzeug.servingr   )r   ZhostZportreloadZdebuggerr   Zwith_threadsr   r   r   r   r   r   r   r     s    !r   shellz Runs a shell in the app context.c           	   C   s   ddl } ddlm} |jj}dtjtj|j|j	|j
f }i }tjd}|rtj|rt|d}tt| |d| W dQ R X ||  | j||d dS )	a<  Runs an interactive Python shell in the context of a given
    Flask application.  The application will populate the default
    namespace of this shell according to it's configuration.

    This is useful for executing small snippets of management code
    without having to manually configure the application.
    r   N)_app_ctx_stackz)Python %s on %s
App: %s [%s]
Instance: %sZPYTHONSTARTUPrexec)bannerZlocal)codeZflask.globalsr   topr   r3   r_   platformr   r   Zinstance_pathrJ   r}   r   rK   isfileopenevalcompilereadr   Zmake_shell_contextZinteract)r   r   r   r   rd   Zstartupr   r   r   r   r     s     

 r   ZrouteszShow the routes for the app.z--sortz-s)endpointmethodsruler?   r   zgMethod to sort routes by. "match" is the order that Flask will match routes when dispatching a request.)r   r   ri   z--all-methodszShow HEAD and OPTIONS methods.)rl   ri   c       	         s2  t tj }|s td dS t|r*dnd | dkrJt|t| d}n| dkrbt|dd	 d} fd
d|D }d}t	dd |D t	dd |D t	dd |D f}dd t
||D }dj| }t|j|   t|jdd |D   x4t
||D ]&\}}t||j||j  qW dS )z6Show all registered routes with endpoints and methods.zNo routes were registered.Nr   )ZHEADZOPTIONS)r   r   )keyr   c             S   s
   t | jS )N)r   r   )r   r   r   r   <lambda>E  s    z routes_command.<locals>.<lambda>c                s    g | ]}d  t|j  qS )z, )rS   r   r   )r   r   )ignored_methodsr   r   r   H  s    z"routes_command.<locals>.<listcomp>)ZEndpointZMethodsZRulec             s   s   | ]}t |jV  qd S )N)r&   r   )r   r   r   r   r   	<genexpr>M  s    z!routes_command.<locals>.<genexpr>c             s   s   | ]}t |V  qd S )N)r&   )r   r   r   r   r   r   N  s    c             s   s   | ]}t |jV  qd S )N)r&   r   )r   r   r   r   r   r   O  s    c             S   s   g | ]\}}t t||qS r   )maxr&   )r   hwr   r   r   r   Q  s    z"{{0:<{0}}}  {{1:<{1}}}  {{2:<{2}}}c             s   s   | ]}d | V  qdS )-Nr   )r   widthr   r   r   r   U  s    )r   r   Zurl_mapZ
iter_rulesra   rb   r   r   r   r   zipr'   stripr   r   rstrip)	sortZall_methodsZrulesZrule_methodsZheadersZwidthsrowr   r   r   )r   r   r   (  s(    

r   a  A general utility script for Flask applications.

Provides commands from Flask, extensions, and the application. Loads the
application defined in the FLASK_APP environment variable, or from a wsgi.py
file. Setting the FLASK_ENV environment variable to 'development' will enable
debug mode.


  {prefix}{cmd} FLASK_APP=hello.py
  {prefix}{cmd} FLASK_ENV=development
  {prefix}flask run
posixZexportr   z$ z> )cmdprefix)ri   c             C   sV   t jdd  }| r@d}t jdk r(|d7 }d| }d|g| t _nd }tj||d d S )Nr   r=   )r2   r   z.cliz
python -m z-m)r0   Z	prog_name)r3   argvr   r   r   )	as_moduler0   Zthis_moduler:   r   r   r   r   m  s    
r   __main__)r   )r   )T)N)F)Ir   Z
__future__r   rB   r(   rJ   r>   r   r3   rY   	functoolsr   operatorr   Z	threadingr   r   ra   Zwerkzeug.utilsr   r#   r	   Z_compatr
   r   r   r   globalsr   Zhelpersr   r   r   r   rX   Z
UsageErrorr   r/   r*   r,   rF   rV   r^   rh   ZOptionr   objectrm   r   Zmake_pass_decoratorZpass_script_infor   r   r   r   r   r   r   Z	ParamTyper   r   r   Zoptionr   r   r   ZChoicer   r'   r:   r   r   r   r   r   r   r   <module>
   s   
9
<
6Bs
1('


!$

