$Jc @sdZddkZddkZddkZddkZdaddkZeidjo da nda dddYZ d dd YZ d e ei fd YZ d ei fdYZ deifdYZdZdadZdZddZdZddZedjogddkZddkZy$eeidZeidZWndeidGHqXeeendS(s An HTTP handler for urllib2 that supports HTTP 1.1 and keepalive. >>> import urllib2 >>> from keepalive import HTTPHandler >>> keepalive_handler = HTTPHandler() >>> opener = urllib2.build_opener(keepalive_handler) >>> urllib2.install_opener(opener) >>> >>> fo = urllib2.urlopen('http://www.python.org') If a connection to a given host is requested, and all of the existing connections are still in use, another connection will be opened. If the handler tries to use an existing connection but it fails in some way, it will be closed and removed from the pool. To remove the handler, simply re-run build_opener with no arguments, and install that opener. You can explicitly close connections by using the close_connection() method of the returned file-like object (described below) or you can use the handler methods: close_connection(host) close_all() open_connections() NOTE: using the close_connection and close_all methods of the handler should be done with care when using multiple threads. * there is nothing that prevents another thread from creating new connections immediately after connections are closed * no checks are done to prevent in-use connections from being closed >>> keepalive_handler.close_all() EXTRA ATTRIBUTES AND METHODS Upon a status of 200, the object returned has a few additional attributes and methods, which should not be used if you want to remain consistent with the normal urllib2-returned objects: close_connection() - close the connection to the host readlines() - you know, readlines() status - the return status (ie 404) reason - english translation of status (ie 'File not found') If you want the best of both worlds, use this inside an AttributeError-catching try: >>> try: status = fo.status >>> except AttributeError: status = None Unfortunately, these are ONLY there if status == 200, so it's not easy to distinguish between non-200 responses. The reason is that urllib2 tries to do clever things with error codes 301, 302, 401, and 407, and it wraps the object upon return. For python versions earlier than 2.4, you can avoid this fancy error handling by setting the module-level global HANDLE_ERRORS to zero. You see, prior to 2.4, it's the HTTP Handler's job to determine what to handle specially, and what to just pass up. HANDLE_ERRORS == 0 means "pass everything up". In python 2.4, however, this job no longer belongs to the HTTP Handler and is now done by a NEW handler, HTTPErrorProcessor. Here's the bottom line: python version < 2.4 HANDLE_ERRORS == 1 (default) pass up 200, treat the rest as errors HANDLE_ERRORS == 0 pass everything up, error processing is left to the calling code python version >= 2.4 HANDLE_ERRORS == 1 pass up 200, treat the rest as errors HANDLE_ERRORS == 0 (default) pass everything up, let the other handlers (specifically, HTTPErrorProcessor) decide what to do In practice, setting the variable either way makes little difference in python 2.4, so for the most consistent behavior across versions, you probably just want to use the defaults, which will give you exceptions on errors. iNiiiitConnectionManagercBsGeZdZdZdZdZdZdZddZ RS(sV The connection manager must be able to: * keep track of all existing cCs.ti|_h|_h|_h|_dS(N(tthreadt allocate_lockt_lockt_hostmapt_connmapt _readymap(tself((s&/sys/lib/python/mercurial/keepalive.pyt__init__s  cCsu|iizS||ijog|i| host is the host:port spec, as in 'www.cnn.com:8080' as passed in. no error occurs if there is no connection to that host.N(RRRtclose(RR th((s&/sys/lib/python/mercurial/keepalive.pytclose_connectionscCsUxN|iiiD]7\}}x(|D] }|ii||iq)WqWdS(sclose all open connectionsN(RRt iteritemsRR%(RR tconnsR&((s&/sys/lib/python/mercurial/keepalive.pyt close_alls  cCs|ii|ddS(sdtells us that this request is now closed and the the connection is ready for another requestiN(RR(RtrequestR R ((s&/sys/lib/python/mercurial/keepalive.pyt_request_closedsicCs)|o|in|ii|dS(N(R%RR(RR R R%((s&/sys/lib/python/mercurial/keepalive.pyt_remove_connectionscCs|it|S(N(tdo_opentHTTPConnection(Rtreq((s&/sys/lib/python/mercurial/keepalive.pyt http_opensc Cs |i}|ptidny|ii|}x|oQ|i|||}|oPn|i|ii||ii|}q>W||}toti d|t |n|ii ||d|i |||i }Wn0titifj o}ti|nX|io|ii|ntoti d|i|in||_||_|i|_||_|i|_|i|_|i|_|idjpt o|Sn)|iid|||i|i|iSdS(Ns no host givens"creating new connection to %s (%d)isSTATUS: %s, %sithttp(tget_hostturllib2tURLErrorRRt_reuse_connectionR%RtDEBUGtinfotidRt_start_transactiont getresponsetsocketterrorthttplibt HTTPExceptiont will_closetstatustreasont_handlert_hostt get_full_urlt_urlt _connectiontcodetmsgtheaderst HANDLE_ERRORStparent(Rt http_classR0R R&trterr((s&/sys/lib/python/mercurial/keepalive.pyR.s@     $      cCsy |i|||i}Wnptitifj o d}nMto!tidd|t|n|i i ||i nX|djp|i djo.toti d|t|nd}n%toti d|t|n|S(sGstart the transaction with a re-used connection return a response object (r) upon success or None on failure. This DOES not close or remove bad connections in cases where it returns. However, if an unexpected exception occurs, it will close and remove the connection before re-raising. sunexpected exception - closing sconnection to %s (%d)i s&failed to re-use connection to %s (%d)sre-using connection to %s (%d)N(R:R;R<R=R>R?RR7R9RRR%tversionR8(RR&R0R RN((s&/sys/lib/python/mercurial/keepalive.pyR6 s"    $c Cs|ii}tidjo|i|in|i|iitd|i D}h}x9dD]1}||jod|d|i dd >sR saccept-encodingitskip_t-t_tPOSTs content-types Content-types!application/x-www-form-urlencodedscontent-lengthsContent-lengths%dtGET(ii(shostsaccept-encoding(RJtcopytsyst version_infotupdatetunredirected_hdrsRLt addheadersRR treplacethas_datatget_datat putrequestt get_selectort putheaderR!R<R=R4R5t endheaderstsend( RR&R0RJt skipheadersRStdataROtkRT((s&/sys/lib/python/mercurial/keepalive.pyR:7s8 "      "   ( RRRR$R'R*R,R-R1R.R6R:(((s&/sys/lib/python/mercurial/keepalive.pyRs        0 +t HTTPHandlercBseZRS((RR(((s&/sys/lib/python/mercurial/keepalive.pyRkVst HTTPResponsecBsweZddd dZeiiZdZdZ dZ dZ d dZdZ dd Z dd ZRS( icCs|otii||||ntii||||i|_d|_d|_d|_d|_d|_ d|_ d|_ dS(Nti( R>RlRtfilenoRRHt_rbuft _rbufsizeRCRDRFRG(Rtsockt debugleveltstricttmethod((s&/sys/lib/python/mercurial/keepalive.pyRms       cCsR|ioD|iid|_|io |ii||i|iqNndS(N(tfpR%RRCR,RDRG(R((s&/sys/lib/python/mercurial/keepalive.pyR%}s     cCs-|ii|i|idd|idS(NR%i(RCR-RDRGR%(R((s&/sys/lib/python/mercurial/keepalive.pyR'scCs|iS(N(RJ(R((s&/sys/lib/python/mercurial/keepalive.pyR8scCs|iS(N(RF(R((s&/sys/lib/python/mercurial/keepalive.pytgeturlscCs|io\|dj oOt|i}||jo||8}qf|i| }|i||_|Sn|i|i|}d|_|S(NRm(RoRR!t _raw_read(RtamttLts((s&/sys/lib/python/mercurial/keepalive.pytreads   cCs|i}d}xqtoi|djo|ii}|id}|djo|| }nyt|d}Wn,tj o |it i |nX|djoPqn|djo||i |7}n||jo(||i |7}|||_|Sn\||jo1||i |7}|i dd|_|Sn||i |7}||8}|i dd}qWx9to1|ii}|pPn|djoPqqW|i|S(NRmt;iiis ( t chunk_lefttTrueRRutreadlinetfindtintt ValueErrorR%R>tIncompleteReadt _safe_read(RRxR}tvaluetlineti((s&/sys/lib/python/mercurial/keepalive.pyt _read_chunkedsL                    icCs-|iid}x|djod|jot|ijn oe|i|i}|pPn|id}|djo|t|i}n|i||_qW|djot|i}n |d}d|jot|ijno |}n|i| |i|}|_|S(Ns ii(RoRR!RwRp(RtlimitRtnewRi((s&/sys/lib/python/mercurial/keepalive.pyRs8 $  1cCsdd}g}xQ|i}|pPn|i||t|7}|o||joPqq|S(Ni(RR R!(RtsizehintttotalRR((s&/sys/lib/python/mercurial/keepalive.pyt readliness   N(RRRRR>RlR{RwR%R'R8RvRRR(((s&/sys/lib/python/mercurial/keepalive.pyRlYs       8 R/cBseZeZRS((RRRltresponse_class(((s&/sys/lib/python/mercurial/keepalive.pyR/sc Cs)t}t}ti|}ti|hdd<dd<}xd D]}d|||fGH|ay`ti|}|i|iy|i|i }}Wnt j od \}}nXWn!t j o} d| GHqJXd||fGHqJW|a|i } dG| GH|idS( Ntoffitonis. fancy error handling %s (HANDLE_ERRORS = %i)s EXCEPTION: %ss status = %s, reason = %ssopen connections:(ii(NN(RKRkR4t build_openertinstall_openerturlopenR{R%RARBtAttributeErrorRtIOErrorR$R*( turltorigtkeepalive_handlertopenertposRtfoRARBtethosts((s&/sys/lib/python/mercurial/keepalive.pyt error_handlers.    #   cCsJyddkl}Wn#tj oddkl}nX|a||S(Ni(tmd5(thashlibRt ImportError(Rzt_md5((s&/sys/lib/python/mercurial/keepalive.pyRs cCs?d}ti}ti|ti|}|i}|iti|}|d|ifGHtit }ti|ti|}|i}|iti|}|d|ifGHti|}d}x%|i }|o||}qPq|iti|}|d|ifGHdS(Ns%25s: %ss normal urllibskeepalive readRmskeepalive readline( R4RRRR{R%RRt hexdigestRkR(RtformatRRtfootmtf((s&/sys/lib/python/mercurial/keepalive.pyt continuitys0         cCsd||fGHtiidti}ti|t||}d|GHtiidtit}ti|t||}d|GHd||fGHdS(Ns making %i connections to: %ss( first using the normal urllib handlerss TIME: %.3f ss( now using the keepalive handler s improvement factor: %.2f(R[tstdouttwriteR4RRtfetchRk(tNRRtt1tt2((s&/sys/lib/python/mercurial/keepalive.pytcomp>s     c Csddk}g}|i}xqt|D]c}|o|djo|i|nti|}|i}|i|it|q+W|i|} d} x@|dD]4}| d} ||djpd| |fGHqqW| S(Niiis+WARNING: inconsistent length on read %i: %i( ttimetrangetsleepR4RR{R%R R!( RRtdelayRtlenst starttimeRRRtdifftj((s&/sys/lib/python/mercurial/keepalive.pyRPs$   %    cCst}dd dY}|adGHti|}|i}|id}d|GHxJ|djo<tiid|tiit i d|d8}q^Wti id d GHti|}|i}|i||jo d GHnd GH|adS(Nt FakeLoggercBseZdZeZZZRS(cWs ||GHdS(N((RRItargs((s&/sys/lib/python/mercurial/keepalive.pytdebughs(RRRR8twarningR=(((s&/sys/lib/python/mercurial/keepalive.pyRgs s- fetching the file to establish a connectionis; waiting %i seconds for the server to close the connectionis %2iis s! fetching the file a second times data are identicals ERROR: DATA DIFFER(( R7R4RR{R%R[RRtflushRRtstderr(RtdbbackupRRtdata1Rtdata2((s&/sys/lib/python/mercurial/keepalive.pyt test_timeoutds.          i cCsodGHyt|Wn"tj odGHtinXHdGHt|HdGHt||HdGHt|dS(Ns,checking error hander (do this on a non-200)s.exiting - exception will prevent further testss>performing continuity test (making sure stuff isn't corrupted)sperforming speed comparisons#performing dropped-connection check(RRR[texitRRR(RR((s&/sys/lib/python/mercurial/keepalive.pyttests  t__main__s%s (ii(((RR4R>R<RRR7R[R\RKRRRkRlR/RRRRRRRRRRtargvRR(((s&/sys/lib/python/mercurial/keepalive.pysks:     <    "