922Wc%@s dZddkZddkZddkZddkZddkZddkZddkZddkZddk Z ddk Z ddk Z ddk Z ddk lZddklZddklZddkZddklZlZlZy!deidd d dUWn d ZnXydd klZWnej oZd ZnXeadZ edZ!dZ"e!e"dZde#fdYZ$dfdYZ%edZ&dZ'edZ(dfdYZ)dfdYZ*dfdYZ+e+Z,dfd YZ-e i.a/d!Z0d"Z1d#Z2d$Z3d%Z4ed d eeed&dd'd(d)d*d+ged, Z5d-Z6d.Z7ed/Z8d0Z9d1Z:d2Z;d3Z<ed4joe6e7e8d5ndS(6s:A high-level cross-protocol url-grabber. GENERAL ARGUMENTS (kwargs) Where possible, the module-level default is indicated, and legal values are provided. copy_local = 0 [0|1] ignored except for file:// urls, in which case it specifies whether urlgrab should still make a copy of the file, or simply point to the existing copy. The module level default for this option is 0. close_connection = 0 [0|1] tells URLGrabber to close the connection after a file has been transfered. This is ignored unless the download happens with the http keepalive handler (keepalive=1). Otherwise, the connection is left open for further use. The module level default for this option is 0 (keepalive connections will not be closed). keepalive = 1 [0|1] specifies whether keepalive should be used for HTTP/1.1 servers that support it. The module level default for this option is 1 (keepalive is enabled). progress_obj = None a class instance that supports the following methods: po.start(filename, url, basename, length, text) # length will be None if unknown po.update(read) # read == bytes read so far po.end() text = None specifies alternative text to be passed to the progress meter object. If not given, the default progress meter will use the basename of the file. throttle = 1.0 a number - if it's an int, it's the bytes/second throttle limit. If it's a float, it is first multiplied by bandwidth. If throttle == 0, throttling is disabled. If None, the module-level default (which can be set on default_grabber.throttle) is used. See BANDWIDTH THROTTLING for more information. timeout = 300 a positive integer expressing the number of seconds to wait before timing out attempts to connect to a server. If the value is None or 0, connection attempts will not time out. The timeout is passed to the underlying pycurl object as its CONNECTTIMEOUT option, see the curl documentation on CURLOPT_CONNECTTIMEOUT for more information. http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTCONNECTTIMEOUT bandwidth = 0 the nominal max bandwidth in bytes/second. If throttle is a float and bandwidth == 0, throttling is disabled. If None, the module-level default (which can be set on default_grabber.bandwidth) is used. See BANDWIDTH THROTTLING for more information. range = None a tuple of the form (first_byte, last_byte) describing a byte range to retrieve. Either or both of the values may set to None. If first_byte is None, byte offset 0 is assumed. If last_byte is None, the last byte available is assumed. Note that the range specification is python-like in that (0,10) will yeild the first 10 bytes of the file. If set to None, no range will be used. reget = None [None|'simple'|'check_timestamp'] whether to attempt to reget a partially-downloaded file. Reget only applies to .urlgrab and (obviously) only if there is a partially downloaded file. Reget has two modes: 'simple' -- the local file will always be trusted. If there are 100 bytes in the local file, then the download will always begin 100 bytes into the requested file. 'check_timestamp' -- the timestamp of the server file will be compared to the timestamp of the local file. ONLY if the local file is newer than or the same age as the server file will reget be used. If the server file is newer, or the timestamp is not returned, the entire file will be fetched. NOTE: urlgrabber can do very little to verify that the partial file on disk is identical to the beginning of the remote file. You may want to either employ a custom "checkfunc" or simply avoid using reget in situations where corruption is a concern. user_agent = 'urlgrabber/VERSION' a string, usually of the form 'AGENT/VERSION' that is provided to HTTP servers in the User-agent header. The module level default for this option is "urlgrabber/VERSION". http_headers = None a tuple of 2-tuples, each containing a header and value. These will be used for http and https requests only. For example, you can do http_headers = (('Pragma', 'no-cache'),) ftp_headers = None this is just like http_headers, but will be used for ftp requests. proxies = None a dictionary that maps protocol schemes to proxy hosts. For example, to use a proxy server on host "foo" port 3128 for http and https URLs: proxies={ 'http' : 'http://foo:3128', 'https' : 'http://foo:3128' } note that proxy authentication information may be provided using normal URL constructs: proxies={ 'http' : 'http://user:host@foo:3128' } Lastly, if proxies is None, the default environment settings will be used. prefix = None a url prefix that will be prepended to all requested urls. For example: g = URLGrabber(prefix='http://foo.com/mirror/') g.urlgrab('some/file.txt') ## this will fetch 'http://foo.com/mirror/some/file.txt' This option exists primarily to allow identical behavior to MirrorGroup (and derived) instances. Note: a '/' will be inserted if necessary, so you cannot specify a prefix that ends with a partial file or directory name. opener = None No-op when using the curl backend (default) cache_openers = True No-op when using the curl backend (default) data = None Only relevant for the HTTP family (and ignored for other protocols), this allows HTTP POSTs. When the data kwarg is present (and not None), an HTTP request will automatically become a POST rather than GET. This is done by direct passthrough to urllib2. If you use this, you may also want to set the 'Content-length' and 'Content-type' headers with the http_headers option. Note that python 2.2 handles the case of these badly and if you do not use the proper case (shown here), your values will be overridden with the defaults. urlparser = URLParser() The URLParser class handles pre-processing of URLs, including auth-handling for user/pass encoded in http urls, file handing (that is, filenames not sent as a URL), and URL quoting. If you want to override any of this behavior, you can pass in a replacement instance. See also the 'quote' option. quote = None Whether or not to quote the path portion of a url. quote = 1 -> quote the URLs (they're not quoted yet) quote = 0 -> do not quote them (they're already quoted) quote = None -> guess what to do This option only affects proper urls like 'file:///etc/passwd'; it does not affect 'raw' filenames like '/etc/passwd'. The latter will always be quoted as they are converted to URLs. Also, only the path part of a url is quoted. If you need more fine-grained control, you should probably subclass URLParser and pass it in via the 'urlparser' option. ssl_ca_cert = None this option can be used if M2Crypto is available and will be ignored otherwise. If provided, it will be used to create an SSL context. If both ssl_ca_cert and ssl_context are provided, then ssl_context will be ignored and a new context will be created from ssl_ca_cert. ssl_context = None No-op when using the curl backend (default) self.ssl_verify_peer = True Check the server's certificate to make sure it is valid with what our CA validates self.ssl_verify_host = True Check the server's hostname to make sure it matches the certificate DN self.ssl_key = None Path to the key the client should use to connect/authenticate with self.ssl_key_type = 'PEM' PEM or DER - format of key self.ssl_cert = None Path to the ssl certificate the client should use to to authenticate with self.ssl_cert_type = 'PEM' PEM or DER - format of certificate self.ssl_key_pass = None password to access the ssl_key self.size = None size (in bytes) or Maximum size of the thing being downloaded. This is mostly to keep us from exploding with an endless datastream self.max_header_size = 2097152 Maximum size (in bytes) of the headers. ftp_disable_epsv = False False, True This options disables Extended Passive Mode (the EPSV command) which does not work correctly on some buggy ftp servers. RETRY RELATED ARGUMENTS retry = None the number of times to retry the grab before bailing. If this is zero, it will retry forever. This was intentional... really, it was :). If this value is not supplied or is supplied but is None retrying does not occur. retrycodes = [-1,2,4,5,6,7] a sequence of errorcodes (values of e.errno) for which it should retry. See the doc on URLGrabError for more details on this. You might consider modifying a copy of the default codes rather than building yours from scratch so that if the list is extended in the future (or one code is split into two) you can still enjoy the benefits of the default list. You can do that with something like this: retrycodes = urlgrabber.grabber.URLGrabberOptions().retrycodes if 12 not in retrycodes: retrycodes.append(12) checkfunc = None a function to do additional checks. This defaults to None, which means no additional checking. The function should simply return on a successful check. It should raise URLGrabError on an unsuccessful check. Raising of any other exception will be considered immediate failure and no retries will occur. If it raises URLGrabError, the error code will determine the retry behavior. Negative error numbers are reserved for use by these passed in functions, so you can use many negative numbers for different types of failure. By default, -1 results in a retry, but this can be customized with retrycodes. If you simply pass in a function, it will be given exactly one argument: a CallbackObject instance with the .url attribute defined and either .filename (for urlgrab) or .data (for urlread). For urlgrab, .filename is the name of the local file. For urlread, .data is the actual string data. If you need other arguments passed to the callback (program state of some sort), you can do so like this: checkfunc=(function, ('arg1', 2), {'kwarg': 3}) if the downloaded file has filename /tmp/stuff, then this will result in this call (for urlgrab): function(obj, 'arg1', 2, kwarg=3) # obj.filename = '/tmp/stuff' # obj.url = 'http://foo.com/stuff' NOTE: both the "args" tuple and "kwargs" dict must be present if you use this syntax, but either (or both) can be empty. failure_callback = None The callback that gets called during retries when an attempt to fetch a file fails. The syntax for specifying the callback is identical to checkfunc, except for the attributes defined in the CallbackObject instance. The attributes for failure_callback are: exception = the raised exception url = the url we're trying to fetch tries = the number of tries so far (including this one) retry = the value of the retry option The callback is present primarily to inform the calling program of the failure, but if it raises an exception (including the one it's passed) that exception will NOT be caught and will therefore cause future retries to be aborted. The callback is called for EVERY failure, including the last one. On the last try, the callback can raise an alternate exception, but it cannot (without severe trickiness) prevent the exception from being raised. interrupt_callback = None This callback is called if KeyboardInterrupt is received at any point in the transfer. Basically, this callback can have three impacts on the fetch process based on the way it exits: 1) raise no exception: the current fetch will be aborted, but any further retries will still take place 2) raise a URLGrabError: if you're using a MirrorGroup, then this will prompt a failover to the next mirror according to the behavior of the MirrorGroup subclass. It is recommended that you raise URLGrabError with code 15, 'user abort'. If you are NOT using a MirrorGroup subclass, then this is the same as (3). 3) raise some other exception (such as KeyboardInterrupt), which will not be caught at either the grabber or mirror levels. That is, it will be raised up all the way to the caller. This callback is very similar to failure_callback. They are passed the same arguments, so you could use the same function for both. BANDWIDTH THROTTLING urlgrabber supports throttling via two values: throttle and bandwidth Between the two, you can either specify and absolute throttle threshold or specify a theshold as a fraction of maximum available bandwidth. throttle is a number - if it's an int, it's the bytes/second throttle limit. If it's a float, it is first multiplied by bandwidth. If throttle == 0, throttling is disabled. If None, the module-level default (which can be set with set_throttle) is used. bandwidth is the nominal max bandwidth in bytes/second. If throttle is a float and bandwidth == 0, throttling is disabled. If None, the module-level default (which can be set with set_bandwidth) is used. THROTTLING EXAMPLES: Lets say you have a 100 Mbps connection. This is (about) 10^8 bits per second, or 12,500,000 Bytes per second. You have a number of throttling options: *) set_bandwidth(12500000); set_throttle(0.5) # throttle is a float This will limit urlgrab to use half of your available bandwidth. *) set_throttle(6250000) # throttle is an int This will also limit urlgrab to use half of your available bandwidth, regardless of what bandwidth is set to. *) set_throttle(6250000); set_throttle(1.0) # float Use half your bandwidth *) set_throttle(6250000); set_throttle(2.0) # float Use up to 12,500,000 Bytes per second (your nominal max bandwidth) *) set_throttle(6250000); set_throttle(0) # throttle = 0 Disable throttling - this is more efficient than a very large throttle setting. *) set_throttle(0); set_throttle(1.0) # throttle is float, bandwidth = 0 Disable throttling - this is the default when the module is loaded. SUGGESTED AUTHOR IMPLEMENTATION (THROTTLING) While this is flexible, it's not extremely obvious to the user. I suggest you implement a float throttle as a percent to make the distinction between absolute and relative throttling very explicit. Also, you may want to convert the units to something more convenient than bytes/second, such as kbps or kB/s, etc. iN(tparse150(tStringIO(t HTTPException(trange_tuple_normalizetrange_tuple_to_headert RangeErrorsfrom t.is import __version__s???(t_cCs|S(N((tst((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRscCs |adS(sSet the DEBUG object. This is called by _init_default_logger when the environment variable URLGRABBER_DEBUG is set, but can also be called by a calling program. Basically, if the calling program uses the logging module and would like to incorporate urlgrabber logging, then it can do so this way. It's probably not necessary as most internal logging is only for debugging purposes. The passed-in object should be a logging.Logger instance. It will be pushed into the keepalive and byterange modules if they're being used. The mirror module pulls this object in on import, so you will need to manually push into it. In fact, you may find it tidier to simply push your logging object (or objects) into each of these modules independently. N(tDEBUG(tDBOBJ((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt set_loggerscCsyR|djotid}n|id}ddk}|ii|dd}|djot|d}n|djo tn|i d}t |djo|d}nd}|djo|i t i }n3|d jo|i t i}n|i|}|i||id }|i||i|Wn"tttfj o d}nXt|dS( stExamines the environment variable URLGRABBER_DEBUG and creates a logging object (logging.logger) based on the contents. It takes the form URLGRABBER_DEBUG=level,filename where "level" can be either an integer or a log level from the logging module (DEBUG, INFO, etc). If the integer is zero or less, logging will be disabled. Filename is the filename where logs will be sent. If it is "-", then stdout will be used. If the filename is empty or missing, stderr will be used. If the variable cannot be processed or the logging module cannot be imported (python < 2.3) then logging will be disabled. Here are some examples: URLGRABBER_DEBUG=1,debug.txt # log everything to debug.txt URLGRABBER_DEBUG=WARNING,- # log warning and higher to stdout URLGRABBER_DEBUG=INFO # log info and higher to stderr This funtion is called during module initialization. It is not intended to be called from outside. The only reason it is a function at all is to keep the module-level namespace tidy and to collect the code into a nice block.tURLGRABBER_DEBUGt,iNiis%(asctime)s %(message)stt-t urlgrabber(tNonetostenvirontsplittloggingt _levelNamestgettintt ValueErrort Formattertlent StreamHandlertsyststderrtstdoutt FileHandlert setFormattert getLoggert addHandlertsetLeveltKeyErrort ImportErrorR (tlogspectdbinfoRtlevelt formattertfilenamethandlerR ((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt_init_default_loggers4         cCs2tpdStidttidtdS(Nsurlgrabber version = %sstrans function "_" = %s(R tinfot __version__R(((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt_log_package_statescCs|S(N((R((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRst URLGrabErrorcBseZdZdZRS(s URLGrabError error codes: URLGrabber error codes (0 -- 255) 0 - everything looks good (you should never see this) 1 - malformed url 2 - local file doesn't exist 3 - request for non-file local file (dir, etc) 4 - IOError on fetch 5 - OSError on fetch 6 - no content length header when we expected one 7 - HTTPException 8 - Exceeded read limit (for urlread) 9 - Requested byte range not satisfiable. 10 - Byte range requested, but range support unavailable 11 - Illegal reget mode 12 - Socket timeout 13 - malformed proxy url 14 - HTTPError (includes .code and .exception attributes) 15 - user abort 16 - error writing to local file MirrorGroup error codes (256 -- 511) 256 - No more mirrors left to try Custom (non-builtin) classes derived from MirrorGroup (512 -- 767) [ this range reserved for application-specific error codes ] Retry codes (< 0) -1 - retry the download, unknown reason Note: to test which group a code is in, you can simply do integer division by 256: e.errno / 256 Negative codes are reserved for use by functions passed in to retrygrab with checkfunc. The value -1 is built in as a generic retry code and is already included in the retrycodes list. Therefore, you can create a custom check function that simply returns -1 and the fetch will be re-tried. For more customized retries, you can use other negative number and include them in retry-codes. This is nice for outputting useful messages about what failed. You can use these error codes like so: try: urlgrab(url) except URLGrabError, e: if e.errno == 3: ... # or print e.strerror # or simply print e #### print '[Errno %i] %s' % (e.errno, e.strerror) cGsti||d|_dS(NsNo url specified(tIOErrort__init__turl(tselftargs((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR3Vs(t__name__t __module__t__doc__R3(((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR1!s4tCallbackObjectcBseZdZdZRS(sContainer for returned callback data. This is currently a dummy class into which urlgrabber can stuff information for passing to callbacks. This way, the prototype for all callbacks is the same, regardless of the data that will be passed back. Any function that accepts a callback function as an argument SHOULD document what it will define in this object. It is possible that this class will have some greater functionality in the future. cKs|ii|dS(N(t__dict__tupdate(R5tkwargs((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR3fs(R7R8R9R3(((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR:Zs cKsti|||S(sJgrab the file at and make a local copy at If filename is none, the basename of the url is used. urlgrab returns the filename of the local file, which may be different from the passed-in filename if the copy_local kwarg == 0. See module documentation for a description of possible kwargs. (tdefault_grabberturlgrab(R4R+R=((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR?iscKsti||S(s0open the url and return a file object If a progress object or throttle specifications exist, then a special file object will be returned that supports them. The file object can be treated like any other file object. See module documentation for a description of possible kwargs. (R>turlopen(R4R=((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR@sscKsti|||S(s`read the url into a string, up to 'limit' bytes If the limit is exceeded, an exception will be thrown. Note that urlread is NOT intended to be used as a way of saying "I want the first N bytes" but rather 'read the whole file into memory, but don't use too much' See module documentation for a description of possible kwargs. (R>turlread(R4tlimitR=((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRA}st URLParsercBsAeZdZdZdZdZdZdZdZRS(sGProcess the URLs before passing them to urllib2. This class does several things: * add any prefix * translate a "raw" file to a proper file: url * handle any http or https auth that's encoded within the url * quote the url Only the "parse" method is called directly, and it calls sub-methods. An instance of this class is held in the options object, which means that it's easy to change the behavior by sub-classing and passing the replacement in. It need only have a method like: url, parts = urlparser.parse(url, opts) c CsG|i}|io|i||i}nti|}|\}}}}} } | p#t|djoc|tijoS|ddjotii |}ndt i |}ti|}d}n|djo|i ||}n|djo|i|}n|o|i|}nti|}||fS( sparse the url and return the (modified) url and its parts Note: a raw file WILL be quoted when it's converted to a URL. However, other urls (ones which come with a proper scheme) may or may not be quoted according to opts.quote opts.quote = 1 --> quote it opts.quote = 0 --> do not quote it opts.quote = None --> guess iis/\sfile:thttpthttps(RDREN(tquotetprefixt add_prefixturlparseRtstringtlettersRtpathtabspathturllibt pathname2urlt process_httpRtguess_should_quotet urlunparse( R5R4toptsRFtpartstschemethostRLtparmtquerytfrag((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pytparses&  +   cCsB|ddjp|ddjo||}n|d|}|S(Nit/i((R5R4RG((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRHs"c Cs.|\}}}}}}||||||fS(N(( R5RTR4RURVRLRWRXRY((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRPscCs=|\}}}}}}ti|}||||||fS(s quote the URL This method quotes ONLY the path part. If you need to quote other parts, you should override this and pass in your derived class. The other alternative is to quote other parts before passing into urlgrabber. (RNRF(R5RTRURVRLRWRXRY((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRFst0123456789ABCDEFc Cs|\}}}}}}d|jodSti|d}|djox|djot||djodS||d|d!i} | d|ijp| d|ijodSti|d|d}qLWdSdS(s Guess whether we should quote a path. This amounts to guessing whether it's already quoted. find ' ' -> 1 find '%' -> 1 find '%XX' -> 0 else -> 1 t it%iii(RJtfindRtupperthexvals( R5RTRURVRLRWRXRYtindtcode((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRQs    ( R7R8R9RZRHRPRFRaRQ(((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRCs %   tURLGrabberOptionscBs\eZdZd dZdZdZdZdZdZ dZ dd Z RS( sClass to ease kwargs handling.cKs5||_|djo|in|i|dS(sInitialize URLGrabberOptions object. Set default values for all options and then update options specified in kwargs. N(tdelegateRt _set_defaultst_set_attributes(R5ReR=((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR3s  cCs;|io$t|i|ot|i|St|dS(N(RethasattrtgetattrtAttributeError(R5tname((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt __getattr__scCsQ|idjodSt|itdjot|iS|i|iSdS(sRCalculate raw throttle value from throttle and bandwidth values. iN(tthrottlettypetfloatt bandwidth(R5((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt raw_throttles cKstd||S(sCreate a derived URLGrabberOptions instance. This method creates a new instance and overrides the options specified in kwargs. Re(Rd(R5R=((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pytderivescKsm|ii||idot|i|_n|idjo#tdtd|ifndS(s7Update object attributes with those provided in kwargs.trangetsimpletcheck_timestampi sIllegal reget mode: %sN(NRtRu( R;R<thas_keyRRstregetRR1R(R5R=((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRgs cCsjd|_d|_d|_d|_ddddddg|_d|_d|_d|_d|_ d t |_ d |_ d|_ d|_d|_d|_d|_d|_t|_d |_d|_d|_d|_d|_t|_d|_d|_d|_t|_t|_ d|_!d |_"d|_#d |_$d|_%d|_&d |_'t(|_)dS(sSet all options to their default values. When adding new options, make sure a default is provided here. g?iiiiiiis urlgrabber/%sii,tPEMi N(*Rt progress_objRmRptretryt retrycodest checkfunct copy_localtclose_connectionRsR/t user_agentt keepalivetproxiesRwtfailure_callbacktinterrupt_callbackRGtopenertTruet cache_openersttimeoutttextt http_headerst ftp_headerstdataRCt urlparserRFt ssl_ca_certt ssl_contexttssl_verify_peertssl_verify_hosttssl_keyt ssl_key_typetssl_certt ssl_cert_typet ssl_key_passtsizetmax_header_sizetFalsetftp_disable_epsv(R5((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRf!sJ                                   cCs |iS(N(tformat(R5((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt__repr__Mss cCs|ii}|idj o|idn|id}x9|D]1}||dt|t|i|f}qGW|io2|ii|d}||dd|f}n||d}|S(NRes{ s %-15s: %s, s s %-15s: %s s 'delegate't}(R;tkeysReRtremovetsorttreprR(R5tindentRtstktdf((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRPs  % N( R7R8R9RR3RlRqRrRgRfRR(((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRds   , t URLGrabbercBsJeZdZdZdZdZddZddZdZ RS(sProvides easy opening of URLs with a variety of options. All options are specified as kwargs. Options may be specified when the class is created and may be overridden on a per request basis. New objects inherit default values from default_grabber. cKst||_dS(N(RdRS(R5R=((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR3hsc Gsd}x|d}d}d}d}to!tid||i|dny9t||f|h}totidn|SWnPtj o!} | }|i}| i}n%tj o} | }|i }nXtotid|n|oototid|n|i |\} } } t d|d|dd |d |i} | | | | n|idjp||ijototid nn|dj o8||i jo(totid ||i nq q dS( Niisattempt %i/%s: %stsuccesss exception: %sscalling callback: %st exceptionR4ttriesRzsretries exceeded, re-raisings)retrycode (%i) not in list %s, re-raising( RR R.RztapplyR1RterrnotKeyboardInterruptRt_make_callbackR:R{(R5RStfuncR6RRt retrycodetcallbacktrtetcb_functcb_argst cb_kwargstobj((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt_retryksN      cKsk|ii|}totidt|n|ii||\}}d}|i|||S(sopen the url and return a file object If a progress object or throttle value specified when this object was created, then a special file object will be returned that supports them. The file object can be treated like any other file object. scombined options: %scSst|ddd|S(NR+RS(tPyCurlFileObjectR(RSR4((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt retryfuncs(RSRrR tdebugRRRZR(R5R4R=RSRTR((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR@s  c s ii|}totidt|n|ii||\}}|\}}}} } } |d jo0ti i t i |}|p d}qn|djo7|i o,t i|}|oti id||}nti i|p/tdtd|f} || _| qti i|p/tdtd|f} || _| q|ipf|id j oQi|i\} }}t}||_||_t| |f||n|Snfd }i||||S( s grab the file at and make a local copy at If filename is none, the basename of the url is used. urlgrab returns the filename of the local file, which may be different from the passed-in filename if copy_local == 0. scombined options: %ss index.htmltfiles//isLocal file does not exist: %sisNot a normal file: %scst|||}zo|i|idj oQi|i\}}}t}||_||_t||f||nWd|i X|S(N( Rt_do_grabR|RRR:R+R4Rtclose(RSR4R+tfoRRRR(R5(s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRs     N(RSRrR RRRRZRRRLtbasenameRNtunquoteR}t url2pathnametnormpathtexistsR1RR4tisfileRsR|RR:R+RR(R5R4R+R=RSRTRURVRLRWRXRYterrRRRRR((R5s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR?sB          c  sii|}totidt|n|ii||\}}|dj o|d}nfd}i||||}|oEt ||jo2t dt d||f}||_ |n|S(s2read the url into a string, up to 'limit' bytes If the limit is exceeded, an exception will be thrown. Note that urlread is NOT intended to be used as a way of saying "I want the first N bytes" but rather 'read the whole file into memory, but don't use too much' scombined options: %sic st|ddd|}d}z|djo|i}n|i|}|idj oQi|i\}}}t}||_||_t||f||nWd|i X|S(NR+RSR( RRtreadR|RR:RR4RR( RSR4RBRRRRRR(R5(s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRs     isExceeded limit (%i): %sN( RSRrR RRRRZRRRR1RR4( R5R4RBR=RSRTRRR((R5s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRAs   cCs#t|o|dhfS|SdS(N((tcallable(R5t callback_obj((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRs N( R7R8R9R3RR@RR?RAR(((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR_s  /  ; ,RcBseZdZdZdZdZdZdZeeZ eddZ hdZ d Z d Z d Zd Zd ZdZddZdZddZddZddZddZdZdZRS(cCsd|_d|_d|_||_ti|id|_||_t |_ d|_ ||_ |i i djo tdnt |_d|_d|_ti|_d|_d|_d|_t |_d|_d|_t |_|idS( NRiRusYcheck_timestamp regets are not implemented in this ver of urlgrabber. Please report this.iii (NN(RRt _hdr_dumpt _parsed_hdrR4RIturlsplitRUR+Rtappendt reget_timeRSRwtNotImplementedErrort _completet_rbuft _rbufsizettimet_ttimet_tsizet _amount_readt _reget_lengtht _prog_runningt_errorRt _hdr_endedt_do_open(R5R4R+RS((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR3s.                   cCs|iS(si Provide the geturl() method, used to be got from urllib.addinfourl, via. urllib.URLopener.* (R4(R5((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pytgeturl5scCs1t|i|ot|i|St|dS(sThis effectively allows us to wrap at the instance level. Any attribute not found in _this_ object will be searched for in self.fo. This includes methods.N(RhRRiRj(R5Rk((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRl:sc Csy|ip|iiop|i|i}|iii|iti|i |i d|d|ii t |_|iii |iqn|it|7_|ii|t|SWntj odSXdS(NRRi(RRSRyRRtstartt_prog_reportnameRNRR4t_prog_basenameRRR<RRRtwriteR(R5tbufR((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt _retrieveCs      cCs'|iod|_d|_t|_n|idt|id|iiodSy|i|7_|idjoB|i i ddjo&|i d d }t ||_n|idjod}|id o1|d i}t|djo d}q1n!|idot|}n|ot ||_qOn|i i ddjoKd i|i d d }|i}ti|d|_||_nt|idjo2|djo%t|_totidqnt|SWntj o tiSXdS(NRitcurtmax_sizeiRDREscontent-lengtht:itftps213 iis150 tlocations s header ended:(shttpshttps(R(RRRRt_over_max_sizeRRSRRUtlowerR_RRRt startswithtstripRtjoinRIRR4RR R.RtpycurltREADFUNC_ABORT(R5RtlengthRR((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt _hdr_retrieveVsD    ,  # cCsq|io|iS|iid}|d7}t}|i|i||idti||_|iS(Ns ii(RRR_RRtseekt mimetoolstMessage(R5t statusendthdrfp((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt_return_hdr_objs    tfgetcCs|iitiS((tcurl_objtgetinfoRt RESPONSE_CODE(R5((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pytsc Cs|p |i}n|ip|iitidn|iitit|iitit |iiti |i |iiti |i |iiti|i|iitit |iitit |iitit to|iitit n|io|iiti|in|iitit |iitidd}t|dot|ipd}n|iiti||iitid|iiti||idjoZ|io6|iiti |i|iiti!|in|iiti"|i#|i$o|iiti%dn|i&o|iiti'|i&n|i(o|iiti)|i(n|i*o3|iiti+|i*|iitidn|i,o|iiti-|i,n|i.o|iiti/|i.qAn|i0oa|idjoQg}x.|i0D]#\}}|i1d ||fqkW|iiti2|n|i3p |i4o1|i5}|o|iiti6|qnt|d o3|i7o&|iiti8t|i7n|i9ox|i9i:D]\}}|id joE|d joqNq|d jo d }n|iiti;|qN|idjoE|djoqNq|d jo d }n|iiti;|qNqNWn|i<o<|iiti=t |iiti>|i?|i<n|i@o|iitiAtn|iitiB|iCdS(Niii,RiREiRDs%s:%sRqRt_none_R(shttpshttps(shttpshttps(shttpshttps(DRSRRtsetoptRt FORBID_REUSEt NOPROGRESSRtNOSIGNALRt WRITEFUNCTIONRtHEADERFUNCTIONRtPROGRESSFUNCTIONt_progress_updatet FAILONERRORt OPT_FILETIMEtFOLLOWLOCATIONR tVERBOSERt USERAGENTt MAXREDIRSRhRRtCONNECTTIMEOUTtLOW_SPEED_LIMITtLOW_SPEED_TIMERURtCAPATHtCAINFOtSSL_VERIFYPEERRRtSSL_VERIFYHOSTRtSSLKEYRt SSLKEYTYPERtSSLCERTRt SSLCERTTYPERt SSLKEYPASSWDRRt HTTPHEADERRsRwt _build_rangetRANGERqtMAX_RECV_SPEED_LARGERtitemstPROXYRtPOSTt POSTFIELDSt_to_utf8Rt FTP_USE_EPSVtURLR4( R5RSRtheadersttagtcontentt range_strRUtproxy((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt _set_optss          !  &      " & cCs%|iodSy|iiWntij o}|i}|id}|ido|id}n|djoR|djoE|djo8tdt d|i |f}|i |_ t n|djo8tdt d |i |f}|i |_ |n|d jo1t d }td |}|i |_ |ni|d jo8t d|i }td |}|i |_ |n$|djo8tdt d|i |f}|i |_ t n|djo1t d}td |}|i |_ |n|djo:t d}td |}|i |_ ||_ |nZ|djoW|ido|id}nt d|i }td |}|i |_ |nt |iddjo~|idjon|idjod|i|i f}q|id jod|i|i f}qd|i |if}n^d|t |idf}|id!jo#|od|jo djn p |}ntd |}||_ ||_|nBX|ido2|id}td |}|i |_ |ndS("Niiii+is'User (or something) called abort %s: %sii sTimeout on %s: %si#sproblem making ssl connectionii%sCould not open/read %si*i:s)problem with the local client certificatei<s1Peer cert cannot be verified or peer cert invalidi?is Max download size exceeded on %sRRDREsHTTP Error %s : %s RsFTP Error %s : %s s!Unknown Error: URL=%s , scheme=%ssPYCURL ERROR %s - "%s"(shttpshttps(sftp(shttpshttps(RRtperformRterrort http_codeR6RR1RR4RRctstrRURt URLGRabError(R5RRcterrcodeRtmsg((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt _do_performs   '"   "          "              *6      cCs1t|_|ii|i|i|iS(N(t _curl_cacheRtresetR%RR(R5((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR[s     cCsdS(N((R5((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt _add_headerscscCsd}d}|iiot|itijotyti|i}Wnt j oqX|ti |_ |ti }||_ ||_|df}d|_n|iio7|ii}|do|d||df}qn|o)t|}|o|iddSndS(NiRit=(RRSRwRnR+ttypest StringTypesRtstattOSErrortST_MTIMERtST_SIZERRRRsRR(R5t reget_lengthtrtRtheader((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRfs*&         c Cs|i|ifSys|iioGti}ti|iiz|i|}Wdti|Xn|i|}|i}Wn0t j o=}t dt d|i |f}|i |_ |nt j o=}t dt d||i f}|i |_ |ntij oR}t dt d||i f}|i|_||_|i |_ |nKtj o}t|doNt|itio8t dt d|i |f}|i |_ |qt d t d |i |f}|i |_ |ntj o=}t d t d||i f}|i |_ |n]tj oF}t d t d |ii|i |f}|i |_ |n X||fSdS(NisBad URL: %s : %si s%s on %sitreasoni sTimeout on %s: %sisIOError on %s: %siisHTTP Exception (%s) on %s: %s(RthdrRSRtsockettgetdefaulttimeouttsetdefaulttimeouttopenR.RR1RR4Rturllib2t HTTPErrorRcRR2Rht isinstanceR;R5Rt __class__R7( R5treqRtold_toRR<RRtnew_e((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt _make_requestsT  "  "  "    &"  "  "    c Cst|iodSt}t|itijo|iot}t|i|_t i i |i|_ |i o d}nd}totid|i|fnyt|i||_Wq.tj o=}tdtd|i|f}|i|_|q.Xnd|_d|_ t|_|i|o|ii|ii|iiti}|djosyt i|i||fWqtj oC}tdtd |i|i|f}|i|_|qXnyt|id |_Wqgtj o=}tdtd |i|f}|i|_|qgXn|ii d t|_dS( s.dump the file to a filename or StringIO bufferNtabtwbs$opening local file "%s" with mode %sis-error opening local file from %s, IOError: %stMEMORYis7error setting timestamp on file %s from %s, OSError: %sRs'error opening file from %s, IOError: %si(!RRRnR+R2R3RR)RRRLRRRR R.R@RR2R1RR4RR-tflushRRRRt INFO_FILETIMEtutimeR5R(R5t _was_filenametmodeRRtmod_time((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRs\ #               c Cs|io?|dj o2t|i}||jo||}qIdSn|ip|in|ig}t|i}x|djp|o|iioX|i|iiti|i }|djoti |nti|_ n|djo |i }nt ||i }y|i i|}Wntij o=}tdtd|i|f} |i| _| ntij o=}tdtd|i|f|i| _| nJtj o=}tdtd|i|f|i| _| nXt|} | pPn|o|| }n|i||| }| |_|i| |_qWti|d|_dS( sfill the buffer to contain at least 'amt' bytes by reading from the underlying file object. If amt is None, then it will read until it gets nothing more. It updates the progress meter and throttles after every self._rbufsize bytes.NiisSocket Error on %s: %si sTimeout on %s: %ssIOError on %s: %sR(RRRRRRSRqRRRtsleepRtminRRR=R'R1RR4RR2RRRJR( R5tamttLRtbufsizetdifft readamounttnewRRtnewsize((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt _fill_buffersZ     "  "  "      cCso|id|i|iodSy2|io$||i7}|iii|nWntj odSXdS(NRi(RRRRRSRyR<R(R5tdownload_totalt downloadedt upload_totaltuploaded((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRCs  cCs|p*|iip |i}q1|ii}n|ptS|tt|djo3td|i||f}ti|f|_ t StS(Ng?s-Downloaded more than max size for %s: %s > %s( RSRRRRoRR4RtE_FILESIZE_EXCEEDEDRR(R5RRR,((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRNs   treplacecCs*t|to|id|}n|S(s2convert 'unicode' to an encoded utf-8 byte string sutf-8(RCtunicodetencode(R5Rterrors((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR`scCsS|i||djo|id}|_n|i| |i|}|_|S(NR(R[RR(R5RTR((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRgs   icCsJ|ip|in|iiSti|id}x|djod|jot|ijn oZt|i}|i||i t|i|jpPnti|id|}q=W|djot|i}n |d}d|jot|ijno |}n|i| |i|}|_|S(Ns ii( RRRtreadlineRJR_RRR[R(R5RBtiRUR((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyReos$  5  ' cCs5|io|iii|in|iidS(N(RRSRytendRRR(R5((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRs cCs|iS(si Provide the geturl() method, used to be got from urllib.addinfourl, via. urllib.URLopener.* (R4(R5((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRsN(R7R8R3RRlRRRtpropertyR<R(R%R-RR0RRHRRR[RRRRReR(((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRs0    *   i c    9 F ?     cCstitiadS(sCTo make sure curl has reread the network/dns info we force a reloadN(R.RRtCurl(((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pytreset_curl_objs cCs |t_dS(s8Deprecated. Use: default_grabber.throttle = new_throttleN(R>Rm(t new_throttle((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt set_throttlescCs |t_dS(s:Deprecated. Use: default_grabber.bandwidth = new_bandwidthN(R>Rp(t new_bandwidth((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt set_bandwidthscCs |t_dS(s@Deprecated. Use: default_grabber.progress_obj = new_progress_objN(R>Ry(tnew_progress_obj((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pytset_progress_objscCs |t_dS(s<Deprecated. Use: default_grabber.user_agent = new_user_agentN(R>R(tnew_user_agent((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pytset_user_agentsiiiiiic CsNh|d6|d6|d6|d6|d6|d6|d6| d6} t||| S( s5Deprecated. Use: urlgrab() with the retry arg insteadR}R~RyRmRpRzR{R|(R?( R4R+R}R~RyRmRptnumtriesR{R|R=((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt retrygrabs  c Cs?ytidd!\}}Wn1tj o%dGtidGdGHtinXh}x@tidD]1}ti|dd\}}t||| [copy_local=0|1] [close_connection=0|1]R1g?i is)throttle: %s, throttle bandwidth: %s B/si(ttext_progress_meterRys LOCAL FILE:i(RtargvRtexitRJRRRlRnR>RmRptprogressRuR&RR?R1( R4R+R=taRtvRuRRk((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt _main_tests2      c Cs<ytidd!\}}Wn1tj o%dGtidGdGHtinXh}x@tidD]1}ti|dd\}}t||| [copy_local=0|1] [close_connection=0|1]R1i(RuRytfoocSst|G|GHddk}|i}|djodGHtddn|djodGHtddndGHdS( Nig?s forcing retryg?sforcing failureisforcing immediate failureR(trandomR1(R+thellotthereR}trnum((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pytcfuncs     R~RR|s LOCAL FILE:(shello( RRvRRwRJRRRxRuR&RRtR1( R4R+R=RyRRzRuRRRk((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt _retry_tests.   c Csddk}|djo t}nd|GHt|}|i}|ixtttt gD]r}|i |}|i }t |dd}d|i G||||i }||jo dGHqadGHqaWdS(Nisusing file "%s" for comparisonsistesting %-30s tpassedtFAILED(t cStringIORt__file__R@RRt_test_file_object_smallreadt_test_file_object_readallt_test_file_object_readlinet_test_file_object_readlinesRRR7tgetvalue( R+RRts_inputttestfunctfo_inputt fo_outputtwrapperts_output((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyt_file_object_tests*            cCs2x+|id}|i||pdSqdS(Ni(RR(RRR((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyR s  cCs|i}|i|dS(N(RR(RRR((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRs cCs/x(|i}|i||pdSqdS(N(ReR(RRR((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRs   cCs)|i}|iti|ddS(NR(t readlinesRRJR(RRtli((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyRs t__main__ttest(=R9RRRIRRJRNRARtthreadR2R4RtftplibRRthttplibRR=t byterangeRRRR7RR/ti18nRR&R,RR R R-R0R2R1R:R?R@RARCRdRR>RRiR.RjRlRnRpRrRtR{RRRRRR(((s6/usr/lib/python2.6/site-packages/urlgrabber/grabber.pyts             !   0  9 kl s       $  "