U
    adi-                     @   s   d Z ddlZddlmZ ddlmZ ddlmZ ddlmZm	Z	 ddl
mZ ddlmZ d	ejkZG d
d dZG dd deZdS )z
runprofileserver.py

    Starts a lightweight Web server with profiling enabled.

Credits for kcachegrind support taken from lsprofcalltree.py go to:
 David Allouche
 Jp Calderone & Itamar Shtull-Trauring
 Johan Dahlin
    N)datetime)settings)StaticFilesHandler)BaseCommandCommandError)get_internal_wsgi_application)signalcommandzdjango.contrib.staticfilesc                   @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )KCacheGrindc                 C   s   |  | _d | _d S N)Zgetstatsdataout_file)selfZprofiler r   Z/tmp/pip-unpacked-wheel-portabvm/django_extensions/management/commands/runprofileserver.py__init__   s    
zKCacheGrind.__init__c                 C   s4   || _ | j d |   | jD ]}| | q d S )Nzevents: Ticks
)r   write_print_summaryr   _entry)r   r   entryr   r   r   output   s
    
zKCacheGrind.outputc                 C   s>   d}| j D ]}t|jd }t||}q
| jd|f  d S )Nr     zsummary: %d
)r   int	totaltimemaxr   r   )r   Zmax_costr   r   r   r   r   r   &   s
    
zKCacheGrind._print_summaryc                 C   s   | j }|j}t|tr&|d|  n |d|j  |d|j  t|jd }t|trn|d|  n|d|j	|f  |j
r|j
}ng }t|trd}n|j	}|D ]}| || q|d d S )Nzfn=%s
zfl=%s
r   z0  %s
%d %d
r   
)r   code
isinstancestrr   co_filenameco_namer   
inlinetimeco_firstlinenocalls	_subentry)r   r   r   r   r!   r#   linenosubentryr   r   r   r   -   s&    


zKCacheGrind._entryc                 C   s   | j }|j}t|tr8|d|  |d|jf  n6|d|j  |d|j  |d|j|jf  t	|j
d }|d||f  d S )Nzcfn=%s
zcalls=%d 0
zcfl=%s
zcalls=%d %d
r   r   )r   r   r   r   r   Z	callcountr   r    r"   r   r   )r   r%   r&   r   r   r   r   r   r   r$   L   s    
zKCacheGrind._subentryN)__name__
__module____qualname__r   r   r   r   r$   r   r   r   r   r	      s
   r	   c                       s2   e Zd ZdZdZ fddZedddZ  ZS )	Commandz7Starts a lightweight Web server with profiling enabled.z&[optional port number, or ipaddr:port]c                    s   t  | |jdddd |jddddd	d
 |jdddddd
 |jddddd |jddddd |jdddddd
 |jdddddd
 |jddd dd!d
 tr|jd"dd#dd$d
 |jd%dd&dd'd
 d S )(Naddrport?z$Optional port number, or ipaddr:port)nargshelpz
--noreloadstore_falseuse_reloaderTz*Tells Django to NOT use the auto-reloader.)actiondestdefaultr.   z--nothreadinguse_threadingz"Tells Django to NOT use threading.z--prof-path	prof_pathz/tmpz=Specifies the directory which to save profile information in.)r2   r3   r.   z--prof-file	prof_file{path}.{duration:06d}ms.{time}zASet filename format, default if "{path}.{duration:06d}ms.{time}".z	--nomedia
store_trueno_mediaFzDo not profile MEDIA_URLz--use-cprofileuse_cprofilezUUse cProfile if available, this is disabled per default because of incompatibilities.z--kcachegrind
use_lsprofz]Create kcachegrind compatible lsprof files, this requires and automatically enables cProfile.z
--nostaticuse_static_handlerzCTells Django to NOT automatically serve static files at STATIC_URL.z
--insecureinsecure_servingz3Allows serving static files even if DEBUG is False.)superadd_argumentsadd_argumentUSE_STATICFILES)r   parser	__class__r   r   r?   _   s                        zCommand.add_arguments c                    s&  dd l dd l
dd lddlm |s2d dn2z|d\ W n tk
rb   d|  Y nX  sld  std d }	d	d	d
 t
jdkrdpd 	
fdd}|rzddlm} || W n, tk
r   ddlm} || Y nX n|  d S )Nr   )runrE   Z8000:z	127.0.0.1z%r is not a valid port number.r0   shutdown_messager9   win32z
CTRL-BREAKz	CONTROL-Cc                     sb  dd l dd lzdd ld} W n tk
r8   d} Y nX d  d rRd  rzdd ld W n  tk
r   td d Y nX r std| s stdd	 d
 jddddsdtd dd  f
dd}td jdd td
	 t
jf  td	f  td  z\t }trzd }d }|rzt
jsr|rzt|}||}	t|d d W n jk
r0 } zrjdjdjd i}z||j }W n" ttfk
r   t|}Y nX tjjd!| d"  d# W 5 d }~X Y n. tk
r\   rNt t d Y nX d S )$Nr   TFr:   r;   z-cProfile disabled, module cannot be imported!zFKcachegrind compatible output format required cProfile from Python 2.5z;Hotshot profile library not found. (and not using cProfile)r5   r6   1      pathdurationtimer7   zPFilename format is wrong. Default format used: '{path}.{duration:06d}ms.{time}'.c                  S   s<   g } t tdd }|r| | t tdd }|r8| | | S )NZ	MEDIA_URLZ
STATIC_URL)getattrr   append)Zexclude_pathsZ	media_urlZ
static_urlr   r   r   get_exclude_paths   s    

z<Command.handle.<locals>.inner_run.<locals>.get_exclude_pathsc                    s$    	
fdd}|S )Nc                    s@  | d  r.t  fdd D r.| |S  dddpBd}d| f }j
|}rp }n
|}t }z|| |W S t | }|j	d |j
d  }rt|}t|d	}	||	 W 5 Q R X nr|| 	j|t|t d
}
j
d|
 }
s.|  ||
 X d S )NZ	PATH_INFOc                 3   s   | ]}  |V  qd S r
   )
startswith).0pZ	path_infor   r   	<genexpr>   s     zdCommand.handle.<locals>.inner_run.<locals>.make_profiler_handler.<locals>.handler.<locals>.<genexpr>/.rootz
%s.%d.profg     @@wrM   z%s.prof)anystripreplacerP   rN   joinZProfiler   nowsecondsmicrosecondsr	   openr   Z
dump_statsformatr   closerenameZruncall)environZstart_responseZ	path_nameZprofnameZprofstartZelapZelapmsZkgfZ	profname2)USE_CPROFILE
USE_LSPROFcProfilerS   hotshotinner_handlerr9   osr6   r5   rP   rW   r   handler   s2    



zQCommand.handle.<locals>.inner_run.<locals>.make_profiler_handler.<locals>.handlerr   )ro   rq   )
rk   rl   rm   rS   rn   r9   rp   r6   r5   rP   )ro   r   make_profiler_handler   s     z@Command.handle.<locals>.inner_run.<locals>.make_profiler_handlerzPerforming system checks...)Zdisplay_num_errorsz%
Django version %s, using settings %rz.Development server is running at http://%s:%s/zQuit the server with %s.r<   r=   r4   )	threadingz.You don't have permission to access that port.zThat port is already in use.z%That IP address can't be assigned-to.z	Error: %sr      )!rp   rP   rn   ImportErrorrm   printr   re   checkget_versionr   ZSETTINGS_MODULEr   rA   DEBUGr   r   errorEACCESZ
EADDRINUSEZEADDRNOTAVAILerrnoAttributeErrorKeyErrorr   sysstderrr   styleERROR_exitKeyboardInterruptexit)ZHAS_HOTSHOTrr   rq   r<   r=   eZERRORSZ
error_textaddrdjangor|   r9   optionsportZquit_commandrF   r   rH   socket)	rk   rl   rm   rS   rn   rp   r6   r5   rP   r   	inner_run   sz    


"   z!Command.handle.<locals>.inner_run)run_with_reloader)
autoreload)r   r   r|   django.core.servers.basehttprF   split
ValueErrorisdigitr   getr   platformZdjango.utils.autoreloadr   ru   Zdjango.utilsr   main)r   r+   argsr   r0   r   r   r   r   r   r   handle   s8     mzCommand.handle)rE   )	r'   r(   r)   r.   r   r?   r   r   __classcell__r   r   rC   r   r*   [   s
   5r*   )__doc__r   r   Zdjango.confr   Z#django.contrib.staticfiles.handlersr   Zdjango.core.management.baser   r   r   r   Z"django_extensions.management.utilsr   ZINSTALLED_APPSrA   r	   r*   r   r   r   r   <module>   s   
A