PKzN4nondjango/__init__.py""" nondjango-storages - Because the API is great but dependency on Django is not. """ __version__ = '0.1.1' # Allows `nondjango.something` to be on another package in the future __path__ = __import__('pkgutil').extend_path(__path__, __name__) PKNtnondjango/storages/__init__.pyfrom .storages import * PKvzN)nondjango/storages/files.pyimport logging import io import codecs import difflib from tempfile import NamedTemporaryFile from contextlib import ContextDecorator from . import utils logger = logging.getLogger(__name__) __escape_decoder = codecs.getdecoder('unicode_escape') class File(ContextDecorator): def __init__(self, name, storage=None, mode='r', encoding='UTF-8'): self.name = name self.mode = mode if 'b' not in mode: self.encoding = encoding self._storage = storage self._stream = None def __enter__(self): return self def __exit__(self, *exc): self.close() return False @property def storage(self): if not self._storage: from .storages import FilesystemStorage self._storage = FilesystemStorage() return self._storage def read_into_stream(self, stream): self.storage.read_into_stream(self.name, stream=stream, mode=self.mode) def read(self): if 'r' not in self.mode and '+' not in self.mode: raise IOError('File not open for reading') content = self.storage.read_into_stream(self.name).read() if 'b' not in self.mode and isinstance(content, bytes): content = content.decode(self.encoding) return content def exists(self): if list(self.storage.list(self.name)): return True return False def md5(self, raise_if_not_exists=True): try: md5hash, _ = next(self.storage.list(self.name)) except StopIteration: if raise_if_not_exists: raise FileNotFoundError(self.name) else: md5hash = None return md5hash def write(self, data): if 'w' not in self.mode and 'a' not in self.mode and '+' not in self.mode: raise IOError('File not open for writing') if isinstance(data, str): data = data.encode('utf-8') if isinstance(data, bytes): self.storage._write(io.BytesIO(data), self.name) else: self.storage._write(data, self.name) def close(self): self.storage._close(self) PKNST..nondjango/storages/storages.pyimport os import logging import tempfile import boto3 import posixpath from botocore.exceptions import ClientError from io import BytesIO, StringIO from .utils import prepare_path, md5s3 from .files import File logger = logging.getLogger(__name__) class SuspiciousOperation(Exception): pass class Settings(dict): "TODO: Implement something nicer!" pass def force_text(base): return base.decode() if isinstance(base, bytes) else base def safe_join(base, *paths): """ A version of django.utils._os.safe_join for S3 paths. Joins one or more path components to the base path component intelligently. Returns a normalized version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised). Paths outside the base path indicate a possible security sensitive operation. """ starts_on_root = base.startswith('/') base_path = force_text(base) base_path = base_path.rstrip('/') paths = [force_text(p) for p in paths] final_path = base_path + '/' for path in paths: _final_path = posixpath.normpath(posixpath.join(final_path, path)) # posixpath.normpath() strips the trailing /. Add it back. if path.endswith('/') or _final_path + '/' == final_path: _final_path += '/' final_path = _final_path if final_path == base_path: final_path += '/' # Ensure final_path starts with base_path and that the next character after # the base path is /. base_path_len = len(base_path) if (not final_path.startswith(base_path) or final_path[base_path_len] != '/'): raise ValueError('the joined path is located outside of the base path' ' component') return final_path if starts_on_root else final_path.lstrip('/') def _strip_prefix(text, prefix): return text[len(prefix):] if text.startswith(prefix) else text def _strip_s3_path(path): assert path.startswith('s3://') bucket, _, path = _strip_prefix(path, 's3://').partition('/') return bucket, path class BaseStorage: file_class = File def __init__(self, workdir=None, settings=None): self._settings = settings or Settings() self._workdir = workdir or os.getcwd() def _normalize_name(self, name): """ Normalizes the name so that paths like /path/to/ignored/../something.txt work. We check to make sure that the path pointed to is not outside the directory specified by the LOCATION setting. """ try: return safe_join(self._workdir, name) except ValueError: raise SuspiciousOperation(f"Attempted access to '{name}' denied.") def get_valid_name(self, name): """ Return a filename, based on the provided filename, that's suitable for use in the target storage system. """ walked_path = os.path.relpath(name) if name else '' if walked_path.startswith('../'): raise SuspiciousOperation(f"Attempted access to '{name}' denied.") return walked_path def read_into_stream(self, file_path, stream=None, mode='r'): raise NotImplementedError() def open(self, file_name, mode='r') -> File: """Retrieve the specified file from storage.""" valid_name = self.get_valid_name(file_name) logger.debug('Opening %s', valid_name) return self.file_class(valid_name, storage=self, mode=mode) def _close(self, f): pass def delete(self, name): """ Delete the specified file from the storage system. """ raise NotImplementedError('subclasses of Storage must provide a delete() method') def _write(self, f, file_name): raise NotImplementedError() def listdir(self, path): """ List the contents of the specified path. Return a 2-tuple of lists: the first item being directories, the second item being files. """ raise NotImplementedError() def exists(self, name) -> bool: """ Return True if a file referenced by the given name already exists in the storage system, or False if the name is available for a new file. """ dirname, sep, filename = name.rpartition('/') dirnames, existing_files = self.listdir(dirname) if filename in existing_files: return True return False class S3Storage(BaseStorage): def __init__(self, settings=None, workdir='s3://s3storage/'): super(__class__, self).__init__(settings=settings) self._resource = None self._bucket_name, self._workdir = _strip_s3_path(workdir) self._workdir = os.path.relpath(self._workdir) if self._workdir else '' @property def s3(self): logger.debug('Getting S3 resource') # See how boto resolve credentials in # http://boto3.readthedocs.io/en/latest/guide/configuration.html#guide-configuration if not self._resource: logger.debug('Resource does not exist, creating a new one...') self._resource = boto3.resource( 's3', aws_access_key_id=self._settings.get('S3CONF_ACCESS_KEY_ID') or self._settings.get('AWS_ACCESS_KEY_ID'), aws_secret_access_key=self._settings.get('S3CONF_SECRET_ACCESS_KEY') or self._settings.get('AWS_SECRET_ACCESS_KEY'), aws_session_token=self._settings.get('S3CONF_SESSION_TOKEN') or self._settings.get('AWS_SESSION_TOKEN'), region_name=self._settings.get('S3CONF_S3_REGION_NAME') or self._settings.get('AWS_S3_REGION_NAME'), use_ssl=self._settings.get('S3CONF_S3_USE_SSL') or self._settings.get('AWS_S3_USE_SSL', True), endpoint_url=self._settings.get('S3CONF_S3_ENDPOINT_URL') or self._settings.get('AWS_S3_ENDPOINT_URL'), ) return self._resource def read_into_stream(self, file_path, stream=None): bucket_name, file_name = _strip_s3_path(file_path) assert bucket_name == self._bucket_name stream = stream or BytesIO() bucket = self.s3.Bucket(bucket_name) try: bucket.download_fileobj(file_name, stream) stream.seek(0) return stream except ClientError as e: if e.response['Error']['Code'] == '404': logger.debug('File %s in bucket %s does not exist', file_name, bucket) raise FileNotFoundError(f's3://{bucket_name}/{file_name}') else: raise def get_valid_name(self, name): valid_path = super(__class__, self).get_valid_name(name) return 's3://' + f'{self._bucket_name}/{self._workdir}/{valid_path}'.replace('//', '/') def _normalize_name(self, name): """ Normalizes the name so that paths like /path/to/ignored/../something.txt work. We check to make sure that the path pointed to is not outside the directory specified by the LOCATION setting. """ assert name.startswith(f's3://{self._bucket_name}/{self._workdir}/') assert '../' not in name in_bucket_path = name.replace(f's3://{self._bucket_name}/', '') return in_bucket_path @property def _bucket(self) -> 's3.Bucket': try: return self.s3.create_bucket(Bucket=self._bucket_name) except ClientError as e: if e.response['Error']['Code'] == 'BucketAlreadyExists': return self.s3.Bucket(self._bucket_name) else: raise e def _write(self, f, file_name): internal_name = self._normalize_name(file_name) logger.info('Writing to s3://%s/%s', self._bucket_name, internal_name) self._bucket.upload_fileobj(f, internal_name) def delete(self, name): internal_name = self.get_valid_name(name) # result = self._bucket.delete_objects(Delete={ # 'Objects': [{'Key': internal_name}], # }) s3_file = self.s3.Object(self._bucket_name, self._normalize_name(internal_name)) result = s3_file.delete() if 'Errors' in result or result['DeleteMarker'] != True: raise RuntimeError(f"Could not delete '{name}': {result}") return result def list(self, path): valid_name = self.get_valid_name(path) logger.debug('Listing %s', valid_name) bucket_name, path = _strip_s3_path(valid_name) bucket = self.s3.Bucket(bucket_name) try: for obj in bucket.objects.filter(Prefix=path): if not obj.key.endswith('/'): yield obj.e_tag, _strip_prefix(obj.key, path) except ClientError as e: if e.response['Error']['Code'] == 'NoSuchBucket': logger.warning('Bucket does not exist, list() returning empty.') else: raise def listdir(self, name): valid_name = self.get_valid_name(name) path = self._normalize_name(valid_name) # The path needs to end with a slash, but if the root is empty, leave # it. if path and not path.endswith('/'): path += '/' directories = [] files = [] paginator = self.s3.meta.client.get_paginator('list_objects') pages = paginator.paginate(Bucket=self._bucket_name, Delimiter='/', Prefix=path) for page in pages: for entry in page.get('CommonPrefixes', ()): directories.append(posixpath.relpath(entry['Prefix'], path)) for entry in page.get('Contents', ()): files.append(posixpath.relpath(entry['Key'], path)) return directories, files class FilesystemStorage(BaseStorage): def _validate_path(self, path): return True def get_valid_name(self, name): valid_path = super(__class__, self).get_valid_name(name) return os.path.join(self._workdir, valid_path).replace('//', '/') def read_into_stream(self, file_name, stream=None, mode='r'): self._validate_path(file_name) if not stream: stream = BytesIO() if 'b' in mode else StringIO() with open(file_name, mode) as f: stream.write(f.read()) stream.seek(0) return stream def _write(self, f, file_name): file_name = self._normalize_name(file_name) self._validate_path(file_name) prepare_path(file_name) open(file_name, 'wb').write(f.read()) def delete(self, name): return os.unlink(name) def save(self, name, content): path = self._normalize_name(name) open(path, 'wb').write(content) def listdir(self, path): self._validate_path(path) path = self._normalize_name(path) for _, dirnames, filenames in os.walk(path): break else: dirnames, filenames = [], [] return dirnames, filenames def list(self, path): self._validate_path(path) fixed_path = self._normalize_name(path) if os.path.isdir(fixed_path): for root, dirs, files in os.walk(fixed_path): for file in files: yield md5s3(open(file, 'rb')), _strip_prefix(os.path.join(root, file), fixed_path) else: # only yields if it exists if os.path.exists(fixed_path): # the relative path of a file to itself is empty # same behavior as in boto3 yield md5s3(open(fixed_path, 'rb')), '' class TemporaryFilesystemStorage(FilesystemStorage): """ Just a Django-less storage w/ partial Django Storage API implemented """ def __init__(self): self._tempdir = None @property def _workdir(self): if not self._tempdir: self._tempdir = tempfile.TemporaryDirectory() return self._tempdir.name PKNb nondjango/storages/utils.pyimport os import logging import hashlib logger = logging.getLogger(__name__) def prepare_path(file_target, is_folder=False): # as the path might not exist, we can not test if it is a dir beforehand # therefore, if it ends with a / it is considered a dir, otherwise, it is a regular file # and the following code works for both cases # if is_folder is explicitly provided, we append a '/' if it does not exist if is_folder and not file_target.endswith('/'): file_target += '/' os.makedirs(os.path.abspath(file_target.rpartition('/')[0]), exist_ok=True) # Function : md5sum # Purpose : Get the md5 hash of a file stored in S3 # Returns : Returns the md5 hash that will match the ETag in S3 # https://stackoverflow.com/questions/6591047/etag-definition-changed-in-amazon-s3/28877788#28877788 # https://github.com/boto/boto3/blob/0cc6042615fd44c6822bd5be5a4019d0901e5dd2/boto3/s3/transfer.py#L169 def md5s3(file_like, multipart_threshold=8 * 1024 * 1024, multipart_chunksize=8 * 1024 * 1024): md5hash = hashlib.md5() file_like.seek(0) filesize = 0 block_count = 0 md5string = b'' for block in iter(lambda: file_like.read(multipart_chunksize), b''): md5hash = hashlib.md5() md5hash.update(block) md5string += md5hash.digest() filesize += len(block) block_count += 1 if filesize > multipart_threshold: md5hash = hashlib.md5() md5hash.update(md5string) md5hash = md5hash.hexdigest() + "-" + str(block_count) else: md5hash = md5hash.hexdigest() file_like.seek(0) # https://github.com/aws/aws-sdk-net/issues/815 return '"{}"'.format(md5hash) PK'}N$##*nondjango_storages-0.1.1.dist-info/LICENSEApache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS PK!HMuSa(nondjango_storages-0.1.1.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UD"PK!Hb+nondjango_storages-0.1.1.dist-info/METADATAMO@ {~=Q)RAH.RhXgobAq:Ii6-N aW8R ]<{)dԧX]E|D! j1L @G\;ؼ'X['mS}}]>ٍiɅwU} Ոb:ƌ3~shPMfmC0OӆfyAJC7yʫqpN T3 %~h9a$n-TyRWPO=Z85Twфav{ׯn8\:/dw#O!ߘ %Yi r K<,oy0^kPK!HZ)nondjango_storages-0.1.1.dist-info/RECORD͹@἟-V &(YDŤ`(O?8c`ɍpܳ"deGg3pmdOxMNYǶ)IÕ'\ܝ5NI`/52m<(`WO{eH{+4++>Ts)SIHJ0Cֳl$q} 'Kq(XvLG4{yW.9n^3Ey^zFqQS:Mkw/̱Jb9NM0'ݡl;dY #QRu:fVIN*q݆Y`̀Il,#fC 8[Z|.ۦ}k%?|L}w prI*; q蹞zce3ElbNQw/>PKzN4nondjango/__init__.pyPKNt(nondjango/storages/__init__.pyPKvzN)|nondjango/storages/files.pyPKNST..= nondjango/storages/storages.pyPKNb 79nondjango/storages/utils.pyPK'}N$##*@nondjango_storages-0.1.1.dist-info/LICENSEPK!HMuSa(-dnondjango_storages-0.1.1.dist-info/WHEELPK!Hb+dnondjango_storages-0.1.1.dist-info/METADATAPK!HZ)qfnondjango_storages-0.1.1.dist-info/RECORDPK jh