├── requirements.txt ├── MANIFEST.in ├── setup.py ├── LICENSE ├── README.rst ├── s3file.py └── tests.py /requirements.txt: -------------------------------------------------------------------------------- 1 | boto==2.24.0 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE *.py *.rst *.txt -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | from s3file import __version__ 3 | 4 | long_description = open('README.rst').read() 5 | 6 | setup( 7 | name="python-s3file", 8 | version=__version__, 9 | description="Read and write to Amazon S3 using a file-like object", 10 | author="Jeremy Carbaugh", 11 | author_email = "jcarbaugh@gmail.com", 12 | license='BSD', 13 | url="http://github.com/jcarbaugh/python-s3file/", 14 | long_description=long_description, 15 | py_modules=["s3file"], 16 | install_requires=['boto==2.24.0'], 17 | platforms=["any"], 18 | classifiers=[ 19 | "Development Status :: 4 - Beta", 20 | "Intended Audience :: Developers", 21 | "License :: OSI Approved :: BSD License", 22 | "Natural Language :: English", 23 | "Operating System :: OS Independent", 24 | "Programming Language :: Python", 25 | "Topic :: Software Development :: Libraries :: Python Modules", 26 | ], 27 | ) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014, Jeremy Carbaugh 2 | 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without modification, 6 | are permitted provided that the following conditions are met: 7 | 8 | * Redistributions of source code must retain the above copyright notice, 9 | this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | * Neither the name of python-s3file nor the names of its contributors 14 | may be used to endorse or promote products derived from this software 15 | without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 21 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 22 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 23 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 24 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 25 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 26 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============= 2 | python-s3file 3 | ============= 4 | 5 | Read and write files to S3 using a file-like object. Refer to S3 buckets and keys using full URLs. 6 | 7 | The underlying mechanism is a lazy read and write using ``cStringIO`` as the file emulation. This is an in memory buffer so is not suitable for large files (larger than your memory). 8 | 9 | As S3 only supports reads and writes of the whole key, the S3 key will be read in its entirety and written on ``close``. Starting from release 1.2 this read and write are deferred until required and the key is only read from if the file is read from or written within and only updated if a write operation has been carried out on the buffer contents. 10 | 11 | 12 | More tests and docs are needed. 13 | 14 | Requirements 15 | ============ 16 | 17 | boto 18 | 19 | Usage 20 | ===== 21 | 22 | Basic usage:: 23 | 24 | from s3file import s3open 25 | 26 | f = s3open("http://mybucket.s3.amazonaws.com/myfile.txt") 27 | f.write("Lorem ipsum dolor sit amet...") 28 | f.close() 29 | 30 | ``with`` statement:: 31 | 32 | with s3open(path) as remote_file: 33 | remote_file.write("blah blah blah") 34 | 35 | S3 authentication key and secret may be passed into the ``s3open`` method or stored in the `boto config file `_.:: 36 | 37 | f = s3open("http://mybucket.s3.amazonaws.com/myfile.txt", key, secret) 38 | 39 | Other parameters to s3open include: 40 | 41 | expiration_days 42 | Sets the number of days that the remote file should be cached by clients. Default is 0, not cached. 43 | 44 | private 45 | If True, sets the file to be private. Defaults to False, publicly readable. 46 | 47 | content_type 48 | The content_type of the file will be guessed from the URL, but you can explicitly set it by passing a content_type value. 49 | 50 | create 51 | **New in version 1.1** If False, assume bucket exists and bypass validation. Riskier, but can speed up writing. Defaults to True. 52 | -------------------------------------------------------------------------------- /s3file.py: -------------------------------------------------------------------------------- 1 | from urlparse import urlparse 2 | import cStringIO 3 | import mimetypes 4 | import os 5 | import datetime 6 | 7 | __version__ = '1.3' 8 | 9 | def s3open(*args, **kwargs): 10 | """ Convenience method for creating S3File object. 11 | """ 12 | return S3File(*args, **kwargs) 13 | 14 | 15 | class S3File(object): 16 | 17 | def __init__(self, url, key=None, secret=None, expiration_days=0, private=False, content_type=None, create=True): 18 | from boto.s3.connection import S3Connection 19 | from boto.s3.key import Key 20 | 21 | self.url = urlparse(url) 22 | self.expiration_days = expiration_days 23 | self.buffer = cStringIO.StringIO() 24 | 25 | self.private = private 26 | self.closed = False 27 | self._readreq = True 28 | self._writereq = False 29 | self.content_type = content_type or mimetypes.guess_type(self.url.path)[0] 30 | 31 | bucket = self.url.netloc 32 | if bucket.endswith('.s3.amazonaws.com'): 33 | bucket = bucket[:-17] 34 | 35 | self.client = S3Connection(key, secret) 36 | 37 | self.name = "s3://" + bucket + self.url.path 38 | 39 | if create: 40 | self.bucket = self.client.create_bucket(bucket) 41 | else: 42 | self.bucket = self.client.get_bucket(bucket, validate=False) 43 | 44 | self.key = Key(self.bucket) 45 | self.key.key = self.url.path.lstrip("/") 46 | self.buffer.truncate(0) 47 | 48 | def __enter__(self): 49 | return self 50 | 51 | def __exit__(self, type, value, traceback): 52 | self.close() 53 | 54 | def _remote_read(self): 55 | """ Read S3 contents into internal file buffer. 56 | Once only 57 | """ 58 | if self._readreq: 59 | self.buffer.truncate(0) 60 | if self.key.exists(): 61 | self.key.get_contents_to_file(self.buffer) 62 | self.buffer.seek(0) 63 | self._readreq = False 64 | 65 | def _remote_write(self): 66 | """ Write file contents to S3 from internal buffer. 67 | """ 68 | if self._writereq: 69 | self.truncate(self.tell()) 70 | 71 | headers = { 72 | "x-amz-acl": "private" if self.private else "public-read" 73 | } 74 | 75 | if self.content_type: 76 | headers["Content-Type"] = self.content_type 77 | 78 | if self.expiration_days: 79 | now = datetime.datetime.utcnow() 80 | then = now + datetime.timedelta(self.expiration_days) 81 | headers["Expires"] = then.strftime("%a, %d %b %Y %H:%M:%S GMT") 82 | headers["Cache-Control"] = 'max-age=%d' % (self.expiration_days * 24 * 3600,) 83 | 84 | self.key.set_contents_from_file(self.buffer, headers=headers, rewind=True) 85 | 86 | def close(self): 87 | """ Close the file and write contents to S3. 88 | """ 89 | self._remote_write() 90 | self.buffer.close() 91 | self.closed = True 92 | 93 | # pass-through methods 94 | 95 | def flush(self): 96 | self._remote_write() 97 | 98 | def next(self): 99 | self._remote_read() 100 | return self.buffer.next() 101 | 102 | def read(self, size=-1): 103 | self._remote_read() 104 | return self.buffer.read(size) 105 | 106 | def readline(self, size=-1): 107 | self._remote_read() 108 | return self.buffer.readline(size) 109 | 110 | def readlines(self, sizehint=-1): 111 | self._remote_read() 112 | return self.buffer.readlines(sizehint) 113 | 114 | def xreadlines(self): 115 | self._remote_read() 116 | return self.buffer 117 | 118 | def seek(self, offset, whence=os.SEEK_SET): 119 | self.buffer.seek(offset, whence) 120 | # if it looks like we are moving in the file and we have not written 121 | # anything then we probably should read the contents 122 | if self.tell() != 0 and self._readreq and not self._writereq: 123 | self._remote_read() 124 | self.buffer.seek(offset, whence) 125 | 126 | def tell(self): 127 | return self.buffer.tell() 128 | 129 | def truncate(self, size=None): 130 | self._writereq = True 131 | self.buffer.truncate(size or self.tell()) 132 | 133 | def write(self, s): 134 | self._writereq = True 135 | self.buffer.write(s) 136 | 137 | def writelines(self, sequence): 138 | self._writereq = True 139 | self.buffer.writelines(sequence) 140 | -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | from boto.s3.connection import S3Connection 2 | from boto.s3.key import Key 3 | from optparse import OptionParser 4 | from s3file import s3open 5 | import random 6 | import unittest 7 | 8 | LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit." 9 | 10 | 11 | class TestS3File(unittest.TestCase): 12 | 13 | def __init__(self, testname, key=None, secret=None): 14 | super(TestS3File, self).__init__(testname) 15 | self.key = key 16 | self.secret = secret 17 | 18 | def setUp(self): 19 | conn = S3Connection(self.key, self.secret) 20 | session_id = "%06d" % random.randint(0, 999999) 21 | session_key = self.key.lower() if self.key else session_id 22 | self.bucket = conn.create_bucket("s3file_%s_%s" % (session_id, session_key)) 23 | 24 | def get_url(self, path): 25 | url_fmt = "http://%s.s3.amazonaws.com/%s" 26 | return url_fmt % (self.bucket.name, path.lstrip("/")) 27 | 28 | def test_context_manager(self): 29 | path = 'test_write_cm.txt' 30 | 31 | with s3open(self.get_url(path), key=self.key, secret=self.secret) as f: 32 | f.write(LOREM) 33 | 34 | k = Key(self.bucket, path) 35 | self.assertEqual(k.get_contents_as_string(), LOREM) 36 | 37 | def test_write(self): 38 | path = 'test_write.txt' 39 | 40 | # write using s3file 41 | f = s3open(self.get_url(path), key=self.key, secret=self.secret) 42 | f.write(LOREM) 43 | f.close() 44 | 45 | # check contents using boto 46 | k = Key(self.bucket, path) 47 | self.assertEqual(k.get_contents_as_string(), LOREM) 48 | 49 | def test_read(self): 50 | path = 'test_read.txt' 51 | 52 | # write using boto 53 | k = Key(self.bucket, path) 54 | k.set_contents_from_string(LOREM) 55 | 56 | # check contents using s3file 57 | f = s3open(self.get_url(path), key=self.key, secret=self.secret) 58 | self.assertEqual(f.read(), LOREM) 59 | f.close() 60 | 61 | def test_tell(self): 62 | url = self.get_url('test_tell.txt') 63 | f = s3open(url, key=self.key, secret=self.secret) 64 | f.write(LOREM) 65 | f.close() 66 | 67 | f = s3open(url, key=self.key, secret=self.secret) 68 | self.assertEqual(f.read(8), LOREM[:8]) 69 | self.assertEqual(f.tell(), 8) 70 | 71 | def lorem_est(self): 72 | lor = LOREM + "\n" 73 | lines = [lor, lor[1:]+lor[:1], lor[2:]+lor[:2], lor[3:]+lor[:3], 74 | lor[4:]+lor[:4], lor[5:]+lor[:5], lor[6:]+lor[:6]] 75 | return lines 76 | 77 | def test_readlines(self): 78 | path = 'test_readlines.txt' 79 | url = self.get_url(path) 80 | lines = self.lorem_est() 81 | res = "".join(lines) 82 | k = Key(self.bucket, path) 83 | k.set_contents_from_string(res) 84 | f = s3open(url, key=self.key, secret=self.secret) 85 | rlines = f.readlines() 86 | rres = "".join(rlines) 87 | f.close() 88 | self.assertEqual(res, rres) 89 | 90 | def test_writelines(self): 91 | path = "test_writelines.txt" 92 | url = self.get_url(path) 93 | f = s3open(url, key=self.key, secret=self.secret) 94 | lines = self.lorem_est() 95 | res = "".join(lines) 96 | f.writelines(lines) 97 | f.close() 98 | k = Key(self.bucket, path) 99 | self.assertEqual(k.get_contents_as_string(), res) 100 | 101 | def test_readline(self): 102 | path = 'test_readline.txt' 103 | url = self.get_url(path) 104 | lines = self.lorem_est() 105 | res = "".join(lines) 106 | k = Key(self.bucket, path) 107 | k.set_contents_from_string(res) 108 | f = s3open(url, key=self.key, secret=self.secret) 109 | rline = f.readline() 110 | f.close() 111 | self.assertEqual(rline, LOREM + '\n') 112 | 113 | def test_closed(self): 114 | path = 'test_closed.txt' 115 | url = self.get_url(path) 116 | f = s3open(url, key=self.key, secret=self.secret) 117 | self.assertEqual(False, f.closed) 118 | f.close() 119 | self.assertEqual(True, f.closed) 120 | 121 | def test_name(self): 122 | path = 'test_name.txt' 123 | url = self.get_url(path) 124 | f = s3open(url, key=self.key, secret=self.secret) 125 | self.assertEqual("s3://" + self.bucket.name + "/" + path, f.name) 126 | f.close() 127 | 128 | def test_flush(self): 129 | path = 'test_flush.txt' 130 | url = self.get_url(path) 131 | fl = LOREM + "\n" + LOREM + "\n" 132 | fl2 = fl + fl 133 | f = s3open(url, key=self.key, secret=self.secret) 134 | f.write(fl) 135 | f.flush() 136 | k = Key(self.bucket, path) 137 | self.assertEqual(k.get_contents_as_string(), fl) 138 | f.write(fl) 139 | f.close() 140 | self.assertEqual(k.get_contents_as_string(), fl2) 141 | 142 | def test_xreadlines(self): 143 | path = 'test_xreadlines.txt' 144 | url = self.get_url(path) 145 | lines = self.lorem_est() 146 | res = "".join(lines) 147 | k = Key(self.bucket, path) 148 | k.set_contents_from_string(res) 149 | f = s3open(url, key=self.key, secret=self.secret) 150 | rres = "" 151 | for lin in f.xreadlines(): 152 | rres += lin 153 | f.close() 154 | self.assertEqual(res, rres) 155 | 156 | def test_seek(self): 157 | # needs start, relative, end 158 | path = 'test_seek.txt' 159 | url = self.get_url(path) 160 | lines = self.lorem_est() 161 | res = "".join(lines) 162 | k = Key(self.bucket, path) 163 | k.set_contents_from_string(res) 164 | f = s3open(url, key=self.key, secret=self.secret) 165 | f.seek(2,0) 166 | self.assertEqual(f.read(8), res[2:10]) 167 | f.seek(1) 168 | self.assertEqual(f.read(8), res[1:9]) 169 | f.seek(-1,1) 170 | self.assertEqual(f.read(9), res[8:17]) 171 | f.seek(-10,2) 172 | self.assertEqual(f.read(10), res[-10:]) 173 | f.close() 174 | 175 | def test_truncate(self): 176 | path = 'test_truncate.txt' 177 | url = self.get_url(path) 178 | lines = self.lorem_est() 179 | res = "".join(lines) 180 | k = Key(self.bucket, path) 181 | k.set_contents_from_string(res) 182 | f = s3open(url, key=self.key, secret=self.secret) 183 | dummy = f.read() # not convinced we should do this but down to the trucate in the write 184 | f.truncate(3) 185 | f.close() 186 | 187 | t = s3open(url, key=self.key, secret=self.secret) 188 | self.assertEqual(t.read(), res[:3]) 189 | t.seek(1,0) 190 | t.truncate() 191 | t.close() 192 | 193 | f = s3open(url, key=self.key, secret=self.secret) 194 | self.assertEqual(f.read(), res[:1]) 195 | f.close() 196 | 197 | def _bin_str(self): 198 | bs = "" 199 | for i in xrange(0,256): 200 | bs += chr(i) 201 | return bs 202 | 203 | def test_binary_write(self): 204 | path = 'test_binary_write.txt' 205 | bs = self._bin_str() 206 | f = s3open(self.get_url(path), key=self.key, secret=self.secret) 207 | f.write(bs) 208 | f.close() 209 | k = Key(self.bucket, path) 210 | self.assertEqual(k.get_contents_as_string(), bs) 211 | 212 | def test_large_binary_write(self): 213 | path = 'test_large_binary_write.txt' 214 | bs = self._bin_str() 215 | for i in xrange(0, 10): 216 | bs += bs 217 | f = s3open(self.get_url(path), key=self.key, secret=self.secret) 218 | f.write(bs) 219 | f.close() 220 | k = Key(self.bucket, path) 221 | self.assertEqual(k.get_contents_as_string(), bs) 222 | 223 | def test_binary_read(self): 224 | path = 'test_binary_read.txt' 225 | bs = self._bin_str() 226 | k = Key(self.bucket, path) 227 | k.set_contents_from_string(bs) 228 | f = s3open(self.get_url(path), key=self.key, secret=self.secret) 229 | self.assertEqual(f.read(), bs) 230 | f.close() 231 | 232 | def test_large_binary_read(self): 233 | path = 'test_large_binary_read.txt' 234 | bs = self._bin_str() 235 | for i in xrange(0, 10): 236 | bs += bs 237 | k = Key(self.bucket, path) 238 | k.set_contents_from_string(bs) 239 | f = s3open(self.get_url(path), key=self.key, secret=self.secret) 240 | self.assertEqual(f.read(), bs) 241 | f.close() 242 | 243 | def tearDown(self): 244 | for key in self.bucket: 245 | key.delete() 246 | self.bucket.delete() 247 | 248 | 249 | if __name__ == '__main__': 250 | 251 | op = OptionParser() 252 | op.add_option("-k", "--key", dest="key", help="AWS key (optional if boto config exists)", metavar="KEY") 253 | op.add_option("-s", "--secret", dest="secret", help="AWS secret key (optional if boto config exists)", metavar="SECRET") 254 | 255 | (options, args) = op.parse_args() 256 | 257 | suite = unittest.TestSuite() 258 | suite.addTest(TestS3File("test_write", options.key, options.secret)) 259 | suite.addTest(TestS3File("test_read", options.key, options.secret)) 260 | suite.addTest(TestS3File("test_tell", options.key, options.secret)) 261 | suite.addTest(TestS3File("test_context_manager", options.key, options.secret)) 262 | suite.addTest(TestS3File("test_readlines", options.key, options.secret)) 263 | suite.addTest(TestS3File("test_writelines", options.key, options.secret)) 264 | suite.addTest(TestS3File("test_readline", options.key, options.secret)) 265 | suite.addTest(TestS3File("test_closed", options.key, options.secret)) 266 | suite.addTest(TestS3File("test_name", options.key, options.secret)) 267 | suite.addTest(TestS3File("test_flush", options.key, options.secret)) 268 | suite.addTest(TestS3File("test_xreadlines", options.key, options.secret)) 269 | suite.addTest(TestS3File("test_seek", options.key, options.secret)) 270 | suite.addTest(TestS3File("test_truncate", options.key, options.secret)) 271 | suite.addTest(TestS3File("test_binary_write", options.key, options.secret)) 272 | suite.addTest(TestS3File("test_large_binary_write", options.key, options.secret)) 273 | suite.addTest(TestS3File("test_binary_read", options.key, options.secret)) 274 | suite.addTest(TestS3File("test_large_binary_read", options.key, options.secret)) 275 | 276 | unittest.TextTestRunner().run(suite) 277 | --------------------------------------------------------------------------------