Debian Codegraph @

petl/io/remotes.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3
4 import logging
5 import sys
6 from contextlib import contextmanager
7
8 from petl.compat import PY3
9 from petl.io.sources import register_reader, register_writer, get_reader, get_writer
10
11 logger = logging.getLogger(__name__)
12
13 # region RemoteSource
14
15
16 class RemoteSource(object):
17 """Read or write directly from files in remote filesystems.
18
19 This source handles many filesystems that are selected based on the
20 protocol passed in the `url` argument.
21
22 The url should be specified in `to..()` and `from...()` functions. E.g.::
23
24 >>> import petl as etl
25 >>>
26 >>> def example_s3():
27 ... url = 's3://mybucket/prefix/to/myfilename.csv'
28 ... data = b'foo,bar\\na,1\\nb,2\\nc,2\\n'
29 ...
30 ... etl.tocsv(data, url)
31 ... tbl = etl.fromcsv(url)
32 ...
33 >>> example_s3() # doctest: +SKIP
34 +-----+-----+
35 | foo | bar |
36 +=====+=====+
37 | 'a' | '1' |
38 +-----+-----+
39 | 'b' | '2' |
40 +-----+-----+
41 | 'c' | '2' |
42 +-----+-----+
43
44 This source uses `fsspec`_ to provide the data transfer with the remote
45 filesystem. Check the `Built-in Implementations <fs_builtin>`_ for available
46 remote implementations.
47
48 Some filesystem can use `URL chaining <fs_chain>`_ for compound I/O.
49
50 .. note::
51
52 For working this source require `fsspec`_ to be installed, e.g.::
53
54 $ pip install fsspec
55
56 Some remote filesystems require aditional packages to be installed.
57 Check `Known Implementations <fs_known>`_ for checking what packages
58 need to be installed, e.g.::
59
60 $ pip install s3fs # AWS S3
61 $ pip install gcsfs # Google Cloud Storage
62 $ pip install adlfs # Azure Blob service
63 $ pip install paramiko # SFTP
64 $ pip install requests # HTTP, github
65
66 .. versionadded:: 1.6.0
67
68 .. _fsspec: https://filesystem-spec.readthedocs.io/en/latest/
69 .. _fs_builtin: https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
70 .. _fs_known: https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
71 .. _fs_chain: https://filesystem-spec.readthedocs.io/en/latest/features.html#url-chaining
72 """
73
74 def __init__(self, url, **kwargs):
75 self.url = url
76 self.kwargs = kwargs
77
78 def open_file(self, mode="rb"):
79 import fsspec
80 # auto_mkdir=True can fail in some filesystems or without permission for full path
81 # E.g: s3fs tries to create a bucket when writing into a folder does not exists
82 fs = fsspec.open(self.url, mode=mode, compression='infer', auto_mkdir=False, **self.kwargs)
83 return fs
84
85 @contextmanager
86 def open(self, mode="rb"):
87 mode2 = mode[:1] + r"b" # python2
88 fs = self.open_file(mode=mode2)
89 with fs as source:
90 yield source
91
92
93 # registering filesystems with packages installed
94
95
96 def _register_filesystems(only_available=False):
97 """Register all known fsspec implementations as remote source."""
98 from fsspec.registry import known_implementations, registry
99 # https://filesystem-spec.readthedocs.io/en/latest/api.html#built-in-implementations
100 # https://filesystem-spec.readthedocs.io/en/latest/api.html#other-known-implementations
101 _register_filesystems_from(known_implementations, only_available)
102 # https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.registry.register_implementation
103 _register_filesystems_from(registry, only_available)
104
105
106 def _register_filesystems_from(fsspec_registry, only_available):
107 """Register each fsspec provider from this registry as remote source."""
108 for protocol, spec in fsspec_registry.items():
109 missing_deps = isinstance(spec, dict) and "err" in spec
110 if missing_deps and only_available:
111 # this could lead to only buit-in implementations available
112 # Other Known Implementations are reported with 'err' even even
113 # the package is installed
114 continue
115 # When missing a package for fsspec use the available source in petl
116 # E.g: fsspec requires `requests` package installed for handling http and https
117 # but petl has URLSource that can work with urlib
118 has_reader = get_reader(protocol)
119 if not missing_deps or has_reader is None:
120 register_reader(protocol, RemoteSource)
121 has_writer = get_writer(protocol)
122 if not missing_deps or has_writer is None:
123 register_writer(protocol, RemoteSource)
124
125
126 def _try_register_filesystems():
127 try:
128 import fsspec # noqa: F401
129 except ImportError:
130 logger.debug("# Missing fsspec package. Install with: pip install fsspec")
131 else:
132 try:
133 _register_filesystems()
134 except Exception as ex:
135 raise ImportError("# ERROR: failed to register fsspec filesystems", ex)
136
137
138 if PY3:
139 _try_register_filesystems()
140
141 # endregion
142
143 # region SMBSource
144
145
146 class SMBSource(object):
147 """Downloads or uploads to Windows and Samba network drives. E.g.::
148
149 >>> def example_smb():
150 ... import petl as etl
151 ... url = 'smb://user:password@server/share/folder/file.csv'
152 ... data = b'foo,bar\\na,1\\nb,2\\nc,2\\n'
153 ... etl.tocsv(data, url)
154 ... tbl = etl.fromcsv(url)
155 ...
156 >>> example_smb() # doctest: +SKIP
157 +-----+-----+
158 | foo | bar |
159 +=====+=====+
160 | 'a' | '1' |
161 +-----+-----+
162 | 'b' | '2' |
163 +-----+-----+
164 | 'c' | '2' |
165 +-----+-----+
166
167 The argument `url` (str) must have a URI with format:
168 `smb://workgroup;user:password@server:port/share/folder/file.csv`.
169
170 Note that you need to pass in a valid hostname or IP address for the host
171 component of the URL. Do not use the Windows/NetBIOS machine name for the
172 host component.
173
174 The first component of the path in the URL points to the name of the shared
175 folder. Subsequent path components will point to the directory/folder/file.
176
177 .. note::
178
179 For working this source require `smbprotocol`_ to be installed, e.g.::
180
181 $ pip install smbprotocol[kerberos]
182
183 .. versionadded:: 1.5.0
184
185 .. _smbprotocol: https://github.com/jborean93/smbprotocol#requirements
186 """
187
188 def __init__(self, url, **kwargs):
189 self.url = url
190 self.kwargs = kwargs
191
192 @contextmanager
193 def open(self, mode="rb"):
194 mode2 = mode[:1] + r"b" # python2
195 source = _open_file_smbprotocol(self.url, mode=mode2, **self.kwargs)
196 try:
197 yield source
198 finally:
199 source.close()
200
201
202 def _open_file_smbprotocol(url, mode="rb", **kwargs):
203
204 _domain, host, port, user, passwd, server_path = _parse_smb_url(url)
205 import smbclient
206
207 try:
208 # register the server with explicit credentials
209 if user:
210 smbclient.register_session(
211 host, username=user, password=passwd, port=port
212 )
213 # Read an existing file as bytes
214 mode2 = mode[:1] + r"b"
215 filehandle = smbclient.open_file(server_path, mode=mode2, **kwargs)
216 return filehandle
217
218 except Exception as ex:
219 raise ConnectionError("SMB error: %s" % ex).with_traceback(sys.exc_info()[2])
220
221
222 def _parse_smb_url(url):
223 e = "SMB url must be smb://workgroup;user:password@server:port/share/folder/file.txt: "
224
225 if not url:
226 raise ValueError("SMB error: no host given")
227 if not url.startswith("smb://"):
228 raise ValueError(e + url)
229
230 if PY3:
231 from urllib.parse import urlparse
232 else:
233 from urlparse import urlparse
234 parsed = urlparse(url)
235 if not parsed.path:
236 raise ValueError(e + url)
237
238 unc_path = parsed.path.replace("/", "\\")
239 server_path = "\\\\{}{}".format(parsed.hostname, unc_path)
240
241 if not parsed.username:
242 domain = None
243 username = None
244 elif ";" in parsed.username:
245 domain, username = parsed.username.split(";")
246 else:
247 domain, username = None, parsed.username
248 port = 445 if not parsed.port else int(parsed.port)
249 return domain, parsed.hostname, port, username, parsed.password, server_path
250
251
252 register_reader("smb", SMBSource)
253 register_writer("smb", SMBSource)
254
255 # endregion