-
Notifications
You must be signed in to change notification settings - Fork 43
/
curl.py
1988 lines (1454 loc) · 55.6 KB
/
curl.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of the `pypath` python module
#
# Copyright 2014-2023
# EMBL, EMBL-EBI, Uniklinik RWTH Aachen, Heidelberg University
#
# Authors: see the file `README.rst`
# Contact: Dénes Türei (turei.denes@gmail.com)
#
# Distributed under the GPLv3 License.
# See accompanying file LICENSE.txt or copy at
# https://www.gnu.org/licenses/gpl-3.0.html
#
# Website: https://pypath.omnipathdb.org/
#
from future.utils import iteritems
from past.builtins import xrange, range
import importlib as imp
import sys
import os
import io
import shutil
import struct
import pypath.share.settings as settings
import pypath.share.session as session_mod
import pypath.share.cache as cache_mod
_logger = session_mod.log()
import pycurl
try:
from cStringIO import StringIO
BytesIO = StringIO
except:
try:
from StringIO import StringIO
from StringIO import StringIO as BytesIO
except:
from io import BytesIO
from io import StringIO
try:
import cPickle as pickle
except:
import pickle
import urllib
try:
import urllib2
except ImportError:
# this works seemless in Py3:
import urllib.request
urllib2 = urllib.request
try:
import urlparse
except:
# this works seemless in Py3:
import urllib.parse
urlparse = urllib.parse
if not hasattr(urllib, 'quote'):
import urllib.parse
_urllib = urllib
urllib = _urllib.parse
try:
import pysftp
except:
_logger.msg(
'Module `pysftp` not available. '
'Only downloading of a small number of resources '
'relies on this module. '
'Please install by PIP if it is necessary for you.',
'curl',
-1,
)
import codecs
import gzip
import zipfile
import tarfile
import hashlib
import re
from contextlib import closing
import pypath.share.progress as progress
import pypath.share.common as common
import pypath_common._constants as _const
import pypath.share.settings as settings
try:
basestring
except NameError:
basestring = str
if 'long' not in __builtins__:
long = int
if 'unicode' not in __builtins__:
unicode = str
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
# global contexts for modifying Curl() behviour
CACHE = None
CACHEDEL = False
CACHEPRINT = False
DRYRUN = False
PRESERVE = False
DEBUG = False
LASTCURL = None
show_cache = False
_re_url = re.compile(r'^(?:http|https|ftp)://')
def is_url(url):
return bool(_re_url.match(url))
class _global_context(object):
"""
This is a metaclass for context handlers working by
setting a module level variable to certain value.
"""
def __init__(self, name, on_off):
"""
:param str name: Name of the module level variable.
:param on_off: Value of the module level variable in the context.
"""
self.name = name
self.module = sys.modules[__name__]
self.on_off = on_off
def __enter__(self):
self._store_value = getattr(self.module, self.name)
setattr(self.module, self.name, self.on_off)
def __exit__(self, exception_type, exception_value, traceback):
if exception_type is not None:
sys.stdout.write(
'%s, %s, %s\n' %
(str(exception_type), str(exception_value), str(traceback)))
sys.stdout.flush()
setattr(self.module, self.name, self._store_value)
class _global_context_on(_global_context):
"""
This is a metaclass for context handlers working by
setting a module level variable to `True`.
"""
def __init__(self, name):
"""
:param str name: Name of the module level variable.
"""
super(_global_context_on, self).__init__(name, True)
class _global_context_off(_global_context):
"""
This is a metaclass for context handlers working by
setting a module level variable to `False`.
"""
def __init__(self, name):
"""
:param str name: Name of the module level variable.
"""
super(_global_context_off, self).__init__(name, False)
class cache_on(_global_context_on):
"""
This is a context handler to turn on pypath.curl.Curl() cache.
As most of the methods use cache as their default behaviour,
probably it won't change anything.
Behind the scenes it sets the value of the `pypath.curl.CACHE`
module level variable to `True` (by default it is `None`).
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
print('`curl.CACHE` is ', curl.CACHE)
with curl.cache_on():
print('`curl.CACHE` is ', curl.CACHE)
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(cache_on, self).__init__('CACHE')
class cache_off(_global_context_off):
"""
This is a context handler to turn off pypath.curl.Curl() cache.
Data will be downloaded even if it exists in cache.
Behind the scenes it sets the value of the `pypath.curl.CACHE`
module level variable to `False` (by default it is `None`).
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
print('`curl.CACHE` is ', curl.CACHE)
with curl.cache_on():
print('`curl.CACHE` is ', curl.CACHE)
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(cache_off, self).__init__('CACHE')
class cache_print_on(_global_context_on):
"""
This is a context handler which makes pypath.curl.Curl() print
verbose messages about its cache.
Behind the scenes it sets the value of the `pypath.curl.CACHEPRINT`
module level variable to `True` (by default it is `False`).
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
with curl.cache_print_on():
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(cache_print_on, self).__init__('CACHEPRINT')
class cache_print_off(_global_context_off):
"""
This is a context handler which stops pypath.curl.Curl() to print
verbose messages about its cache.
Behind the scenes it sets the value of the `pypath.curl.CACHEPRINT`
module level variable to `False`. As by default it is `False`, this
context won't modify the default behaviour.
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
with curl.cache_print_off():
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(cache_print_off, self).__init__('CACHEPRINT')
class cache_delete_on(_global_context_on):
"""
This is a context handler which results pypath.curl.Curl() deleting the
cache files instead of reading it. Then it downloads the data again,
or does nothing if the `DRYRUN` context is turned on. Upon deleting
cache files console messages will let you know which files have been
deleted.
Behind the scenes it sets the value of the `pypath.curl.CACHEDEL`
module level variable to `True` (by default it is `False`).
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
with curl.cache_delete_on():
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(cache_delete_on, self).__init__('CACHEDEL')
class cache_delete_off(_global_context_off):
"""
This is a context handler which stops pypath.curl.Curl() deleting the
cache files. This is the default behaviour, so this context won't
change anything by default.
Behind the scenes it sets the value of the `pypath.curl.CACHEDEL`
module level variable to `False`.
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
with curl.cache_delete_off():
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(cache_delete_off, self).__init__('CACHEDEL')
class dryrun_on(_global_context_on):
"""
This is a context handler which results pypath.curl.Curl() to do all
setup steps, but do not perform download or cache read.
Behind the scenes it sets the value of the `pypath.curl.DRYRUN`
module level variable to `True` (by default it is `False`).
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
with curl.cache_dryrun_on():
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(dryrun_on, self).__init__('DRYRUN')
class dryrun_off(_global_context_off):
"""
This is a context handler which results pypath.curl.Curl() to
perform download or cache read. This is the default behaviour,
so applying this context restores the default.
Behind the scenes it sets the value of the `pypath.curl.DRYRUN`
module level variable to `False`.
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
with curl.cache_dryrun_off():
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(dryrun_off, self).__init__('DRYRUN')
class preserve_on(_global_context_on):
"""
This is a context handler which results pypath.curl.Curl() to make
a reference to itself in the module level variable `LASTCURL`. This
is useful if you have some issue with `Curl`, and you want to access
the instance for debugging.
Behind the scenes it sets the value of the `pypath.curl.PRESERVE`
module level variable to `True` (by default it is `False`).
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
with curl.cache_preserve_on():
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(preserve_on, self).__init__('PRESERVE')
class preserve_off(_global_context_off):
"""
This is a context handler which avoids pypath.curl.Curl() to make
a reference to itself in the module level variable `LASTCURL`. By
default it does not do this, so this context only restores the
default.
Behind the scenes it sets the value of the `pypath.curl.PRESERVE`
module level variable to `False`.
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
with curl.cache_preserve_off():
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(preserve_off, self).__init__('PRESERVE')
class debug_on(_global_context_on):
"""
This is a context handler which results pypath.curl.Curl() to print
debug information.
This is useful if you have some issue with `Curl`, and you want to
see what`s going on.
Behind the scenes it sets the value of the `pypath.curl.DEBUG`
module level variable to `True` (by default it is `False`).
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
with curl.cache_debug_on():
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(debug_on, self).__init__('DEBUG')
class debug_off(_global_context_off):
"""
This is a context handler which avoids pypath.curl.Curl() to print
debug information.
By default it does not do this, so this context only restores the
default.
Behind the scenes it sets the value of the `pypath.curl.DEBUG`
module level variable to `False`.
Example: ::
import pypath
from pypath import curl, data_formats
pa = pypath.PyPath()
with curl.cache_debug_off():
pa.load_resources({'signor': data_formats.pathway['signor']})
"""
def __init__(self):
super(debug_off, self).__init__('DEBUG')
class RemoteFile(object):
def __init__(self,
filename,
user,
host,
passwd,
port = 22,
sep = '\t',
header = True,
rownames = True):
for key, val in iteritems(locals()):
setattr(self, key, val)
self.conf = fabric.config.Config()
env.keepalive = 60
env.connection_attempts = 5
env.password = self.passwd
def wcl(self):
with closing(
connect(self.user, self.host, self.port, HostConnectionCache(
))) as ssh:
stdin, stdout, stderr = ssh.exec_command('wc -l %s' %
self.filename)
return int(stdout.readlines()[0].split()[0]) - (1 if self.header
else 0)
def rowns(self):
with closing(
connect(self.user, self.host, self.port, HostConnectionCache(
))) as ssh:
stdin, stdout, stderr = ssh.exec_command(
'awk \'BEGIN{FS = "%s"}{print $1}\' %s%s' %
(self.sep, self.filename, ''
if not self.header else ' | tail -n +2'))
return [x.strip() for x in stdout.readlines()]
def open(self, return_header = True):
with closing(
connect(self.user, self.host, self.port, HostConnectionCache(
))) as ssh:
with closing(ssh.open_sftp()) as sftp:
with closing(sftp.open(self.filename)) as f:
if not return_header:
line = f.readline()
for line in f:
yield line
class FileOpener(session_mod.Logger):
"""
This class opens a file, extracts it in case it is a
gzip, tar.gz, tar.bz2 or zip archive, selects the requested
files if you only need certain files from a multifile archive,
reads the data from the file, or returns the file pointer,
as you request. It examines the file type and size.
"""
FORBIDDEN_CHARS = re.compile(r'[/\\<>:"\?\*\|]')
def __init__(
self,
file_param,
compr = None,
extract = True,
_open = True,
set_fileobj = True,
files_needed = None,
large = True,
default_mode = 'r',
encoding = 'utf-8',
):
if not hasattr(self, '_logger'):
session_mod.Logger.__init__(self, name = 'file')
if not hasattr(self, 'encoding') or not self.encoding:
self.encoding = encoding
if not hasattr(self, 'default_mode'):
self.default_mode = default_mode
if not hasattr(self, 'compr'):
self.compr = compr
if not hasattr(self, 'files_needed'):
self.files_needed = files_needed
if not hasattr(self, 'large'):
self.large = large
self.fname = file_param \
if type(file_param) in _const.CHAR_TYPES else file_param.name
self.fileobj = None \
if type(file_param) in _const.CHAR_TYPES else file_param
if not hasattr(self, 'type'):
self.get_type()
if _open:
self.open()
if extract:
self.extract()
def open(self):
"""
Opens the file if exists.
"""
if self.fileobj is None and os.path.exists(self.fname):
if self.encoding and self.type == 'plain':
self.fileobj = open(
self.fname,
self.default_mode,
encoding = (
None if self.default_mode == 'rb' else self.encoding
),
)
else:
self.fileobj = open(self.fname, 'rb')
def extract(self):
"""
Calls the extracting method for compressed files.
"""
getattr(self, 'open_%s' % self.type)()
def open_tgz(self):
"""
Extracts files from tar gz.
"""
self._log('Opening tar.gz file `%s`.' % self.fileobj.name)
self.files_multipart = {}
self.sizes = {}
self.tarfile = tarfile.open(fileobj = self.fileobj, mode = 'r:gz')
self.members = self.tarfile.getmembers()
for m in self.members:
if (self.files_needed is None or m.name in self.files_needed) \
and m.size != 0:
# m.size is 0 for dierctories
this_file = self.tarfile.extractfile(m)
self.sizes[m.name] = m.size
if self.large:
self.files_multipart[m.name] = this_file
else:
self._log(
'Reading contents of file '
'from archive: `%s`.' % m.name
)
self.files_multipart[m.name] = this_file.read()
this_file.close()
if not self.large:
self.tarfile.close()
self._log('File closed: `%s`.' % self.fileobj.name)
self.result = self.files_multipart
def open_gz(self):
self._log('Opening gzip file `%s`.' % self.fileobj.name)
self.fileobj.seek(-4, 2)
self.size = struct.unpack('I', self.fileobj.read(4))[0]
self.fileobj.seek(0)
self.gzfile = gzip.GzipFile(fileobj = self.fileobj)
if self.large:
io.DEFAULT_BUFFER_SIZE = 4096
self._gzfile_mode_r = io.TextIOWrapper(
self.gzfile,
encoding = self.encoding,
)
self.result = self.iterfile(
self.gzfile
if self.default_mode == 'rb' else
self._gzfile_mode_r
)
self._log(
'Result is an iterator over the '
'lines of `%s`.' % self.fileobj.name
)
else:
self.result = self.gzfile.read()
self.gzfile.close()
self._log(
'Data has been read from gzip file `%s`. '
'The file has been closed' % self.fileobj.name
)
def open_zip(self):
self._log('Opening zip file `%s`.' % self.fileobj.name)
self.files_multipart = {}
self.sizes = {}
self.fileobj.seek(0)
self.zipfile = zipfile.ZipFile(self.fileobj, 'r')
self.members = self.zipfile.namelist()
for i, m in enumerate(self.members):
self.sizes[m] = self.zipfile.filelist[i].file_size
if self.files_needed is None or m in self.files_needed:
this_file = self.zipfile.open(m)
if self.large:
if self.default_mode == 'rb':
# keeping it in binary mode
self.files_multipart[m] = this_file
else:
# wrapping the file for decoding
self.files_multipart[m] = io.TextIOWrapper(
this_file, encoding=self.encoding
)
else:
self.files_multipart[m] = this_file.read()
this_file.close()
if not self.large:
self.zipfile.close()
self._log(
'Data has been read from zip file `%s`.'
'File has been closed' % self.fileobj.name
)
self.result = self.files_multipart
def open_plain(self):
self._log('Opening plain text file `%s`.' % self.fileobj.name)
self.size = os.path.getsize(self.fileobj.name)
if self.large:
self.result = self.iterfile(self.fileobj)
else:
self.result = self.fileobj.read()
self.fileobj.close()
self._log(
'Contents of `%s` has been read '
'and the file has been closed.' % self.fileobj.name
)
def get_type(self):
self.multifile = False
if self.fname[-3:].lower() == 'zip' or self.compr == 'zip':
self.type = 'zip'
self.multifile = True
elif self.fname[-3:].lower() == 'tgz' or \
self.fname[-6:].lower() == 'tar.gz' or \
self.compr == 'tgz' or self.compr == 'tar.gz':
self.type = 'tgz'
self.multifile = True
elif self.fname[-2:].lower() == 'gz' or self.compr == 'gz':
self.type = 'gz'
else:
self.type = 'plain'
@staticmethod
def iterfile(fileobj):
for line in fileobj:
yield line
class Curl(FileOpener):
"""
This class is a wrapper around pycurl.
You can set a vast amount of parameters.
In addition it has a caching functionality: using this downloads
of databases/resources is performed only once.
It handles HTTP, FTP, cookies, headers, GET and POST params,
multipart/form data, URL quoting, redirects, timeouts, retries,
encodings, debugging.
It returns either downloaded data, file pointer, files extracted
from archives (gzip, tar.gz, zip).
It is able to show a progress and status indicator on the console.
"""
def __init__(
self,
url,
silent = True,
get = None,
post = None,
req_headers = None,
cache = True,
debug = False,
outf = None,
compr = None,
encoding = None,
files_needed = None,
connect_timeout = None,
timeout = None,
ignore_content_length = False,
init_url = None,
init_fun = 'get_jsessionid',
init_use_cache = False,
follow = True,
large = False,
default_mode = 'r',
override_post = False,
init_headers = False,
return_headers = False,
compressed = False,
binary_data = None,
write_cache = True,
force_quote = False,
sftp_user = None,
sftp_passwd = None,
sftp_passwd_file = '.secrets',
sftp_port = 22,
sftp_host = None,
sftp_ask = None,
setup = True,
call = True,
process = True,
retries = None,
cache_dir = None,
bypass_url_encoding = False,
empty_attempt_again = True,
keep_failed = False,
alpn = True,
slow = False,
http2 = True,
):
if not hasattr(self, '_logger'):
session_mod.Logger.__init__(self, name = 'curl')
self.result = None
self.download_failed = False
self.status = 0
self.get = get
self.large = large
self.default_mode = default_mode
self.silent = silent
self.debug = debug or DEBUG
self.url = url
self.local_file = os.path.exists(self.url)
self.get = get
self.force_quote = force_quote
self.bypass_url_encoding = bypass_url_encoding
self.empty_attempt_again = empty_attempt_again
self.keep_failed = keep_failed
self.alpn = alpn
self.http2 = http2
self._log(
'Creating Curl object to retrieve '
'data from `%s`' % self.url[:200] # we just don't flood the log
# with super long URLs
)
if not self.local_file:
self.process_url()
self.url_fix()
self.set_get()
else:
self._log('The URL is a local file path.')
self.filename = os.path.split(self.url)[-1]
self.compr = compr
# self.get_type()
self.progress = None
self.encoding = encoding
self.files_needed = files_needed
self.follow_http_redirect = follow
self.timeout = (
settings.get('curl_extended_timeout')
if slow else
settings.get('curl_timeout')
)
self.connect_timeout = settings.get('curl_connect_timeout')
self.ignore_content_length = ignore_content_length
self.override_post = override_post
self.retries = max(retries or settings.get('curl_retries'), 1)
self.req_headers = req_headers
self._req_headers_list()
self.post = post
self.get = get
self.binary_data = binary_data
self.cache_dir = cache_dir
self.cache = cache
self.init_cache()
if self.local_file:
self.cache_file_name = self.url
self.use_cache = True
self.write_cache = write_cache
self.outfile = outf
self.init_url = init_url
self.init_fun = init_fun
self.init_use_cache = init_use_cache
self.sftp_host = sftp_host
self.sftp_ask = sftp_ask
self.sftp_port = sftp_port
self.sftp_passwd = sftp_passwd
self.sftp_user = sftp_user
self.sftp_passwd_file = sftp_passwd_file
if CACHEPRINT:
self.show_cache()
if CACHEDEL:
self.delete_cache_file()
self.init_cache()
if not self.use_cache and not DRYRUN:
self.title = None
self.set_title()
if self.sftp_host is not None:
self.sftp_url()
self.sftp_call()
else:
self.progress_setup()
if setup:
self.curl_setup()
if call:
self.curl_call()
elif not self.silent:
if self.local_file:
self._log('Loading data from local file `%s`' % self.url)
else:
self._log(
'Loading data from cache '
'previously downloaded from `%s`' % self.domain
)
if process and not self.download_failed and not DRYRUN:
self.process_file()
if DRYRUN:
self.print_debug_info('INFO', 'DRYRUN PERFORMED, RETURNING NONE')
if PRESERVE:
self.print_debug_info('INFO', 'PRESERVING Curl() INSTANCE '
'IN pypath.curl.LASTCURL')
setattr(sys.modules[__name__], 'LASTCURL', self)
def __del__(self):
fileattrs = ['tarfile', 'zipfile', 'gzfile', 'fileobj']
for fattr in fileattrs:
if hasattr(self, fattr):
f = getattr(self, fattr)
if hasattr(f, 'close') and sys.getrefcount(f) <= 1:
f.close()
def reload(self):
modname = self.__class__.__module__
mod = __import__(modname, fromlist = [modname.split('.')[0]])
imp.reload(mod)
new = getattr(mod, self.__class__.__name__)
setattr(self, '__class__', new)
def print_debug_info(self, typ, msg):
msg = self._bytes_to_unicode(msg)
self._log('CURL DEBUG INFO: %s' % typ)
self._log(msg)
def process_url(self):
self.domain = (
self.url.replace('https://', '').replace('http://', '').\