AWSimple
(pronounced A-W-Simple)
Simple API for basic AWS services such as S3 (Simple Storage Service), DynamoDB (a NoSQL database), SNS (Simple Notification Service),
and SQS (Simple Queuing Service).
Project featured on PythonBytes Podcast Episode #224.
Full documentation available at jamesabel.github.io/awsimple.
Features:
-
Simple Object-Oriented API on top of boto3.
- Eliminates the need to worry about
clients, resources, sessions, and pagination.
-
Locally cached S3 accesses. Reduces network traffic, AWS costs, and can speed up access.
-
pubsub functionality (via SNS topics and SQS queues).
-
DynamoDB full table scans (with local cache option that only rescans if the table has changed).
-
Convert back and forth between DynamoDB items and Python dictionaries automatically. Converts many common data types to DynamoDB compatible types,
including nested structures, sets, images (PIL), and Enum/StrEnum.
-
File-based hashes for S3 objects: a full-object checksum (CRC64NVME) and the SHA-512 of the contents, whatever way the file was
uploaded (S3's etag is not a true file hash). The length and checksum of every S3 transfer are checked.
-
List an S3 bucket without a request per object, and bring a local directory up to date with a bucket (like aws s3 sync,
without the AWS CLI).
-
Supports moto mock. Handy for testing and CI.
-
Supports free-threaded Python (the builds without the GIL, e.g. python3.14t): the test suite runs on it, and nothing awsimple imports
turns the GIL back on.
-
Automatic S3 retries.
-
One-line S3 file write, read, and delete.
-
DynamoDB secondary indexes.
-
Built-in pagination (e.g. for DynamoDB table scans and queries). Always get everything you asked for.
-
Can automatically set SQS timeouts based on runtime data (can also be user-specified).
Usage
pip install awsimple
Examples
The example folder has several examples you can customize and run. Instructions are available in examples
S3
# print string contents of an existing S3 object
s = S3Access("testawsimple", profile_name="testawsimple").read_string("helloworld.txt")
print(s)
DynamoDB
dynamodb_access = DynamoDBAccess("testawsimple", profile_name="testawsimple")
# put an item into DynamoDB
dynamodb_access.put_item({"id": "batman", "city": "Gotham"})
# now get it back
item = dynamodb_access.get_item("id", "batman")
print(item["city"]) # Gotham
Introduction
awsimple is a simple interface into basic AWS services such as S3 (Simple Storage Service) and
DynamoDB (a simple NoSQL database). It has a set of higher level default settings and behavior
that should cover many basic usage models.
Discussion
AWS's "serverless" resources offer many benefits. You only pay for what you use, easily scale,
and generally have high performance and availability.
While AWS has many varied services with extensive flexibility, using it for more straight-forward
applications is sometimes a daunting task. There are access modes that are probably not required
and some default behaviors are not best for common usages. awsimple aims to create a higher
level API to AWS services (such as S3, DynamoDB, SNS, and SQS) to improve programmer productivity.
S3
awsimple's hashes are hashes of the whole file. They are the same whether a file was uploaded in one part or in several, so
an application does not have to know or care how a transfer was done.
awsimple uses S3's native full-object checksums to test for file equivalency (e.g. to avoid re-uploading
unchanged files). Uploads use CRC64NVME - the algorithm S3 itself defaults to, and the only one S3 computes
as a full-object value for both single-part and multipart uploads - and S3 validates the data against the
checksum server-side before storing. Objects written by other tools with a native full-object SHA-512
checksum are also recognized and compared. Objects without any recognizable full-object hash fall back to
modification-time and file-size comparison.
An S3 object has one native checksum, so awsimple also writes the SHA-512 of the contents as object metadata
(awsimple-sha512) on every object it writes (S3ObjectMetadata.metadata_sha512). A matching CRC64NVME alone does not skip an upload: the length and
the SHA-512 must match too. An object that has the metadata SHA-512 but no native
checksum (e.g. written by an older awsimple version) is always re-uploaded, so it gains the native checksum, and
an object that has a CRC64NVME but no SHA-512 is re-uploaded, so it gains its SHA-512.
Every S3 access checks the length and the CRC64NVME (when the object has one) of what was transferred: after a
write, the S3 object is compared with what was written, and after a read or download, what was received is compared
with the S3 object. A mismatch raises AWSimpleException (a download is tried again first).
S3Access.list_objects() lists a bucket (or a prefix) with the size, modification time, ETag and storage class of
each object, using only the bucket listing: it makes no request per object, unlike S3Access.dir().
When the destination of a download is a directory, the S3 key becomes a path under that directory with
s3_key_to_local_path(): empty key components are dropped (as aws s3 sync does), so a key such as /temp//a.txt
is temp/a.txt under the directory, and a key that can not be a file under the directory (e.g. one with a ..
component) raises AWSimpleException. S3Access.download() also takes the object's metadata when the caller already
has it, and a callback that reports the bytes transferred.
S3Access.sync_to_directory() brings a local directory up to date with a bucket (or a prefix), like aws s3 sync from
a bucket to a directory, without the AWS CLI:
result = S3Access("testawsimple", profile_name="testawsimple").sync_to_directory(Path("backup"))
print(result.get_count(S3SyncOutcome.downloaded), result.get_size(S3SyncOutcome.downloaded))
for sync_object in result.get_objects(S3SyncOutcome.failed):
print(sync_object.key, sync_object.reason)
The bucket is listed once, and an object is downloaded when its local file is missing, has a different size, or is
older than the S3 object (size_only=True does not compare times). Only a downloaded object takes a metadata request
(one), which the length and CRC64NVME of what was downloaded are checked against before it replaces the local file.
Local files are never deleted. The prefix is not part of the local paths. The result has the outcome of every listed
object: folder markers (keys that end with /), GLACIER and DEEP_ARCHIVE objects, and keys that can not all be
local files (keys that are the same local file, e.g. a/b and a//b, or a key that is a file where other keys need
a directory) are skipped with the reason, and a failure of one object is reported without stopping the others. There
is a dry run, an event to request a stop, and a callback per object.
S3Access.verify_directory() verifies the files of a local directory against a bucket (or a prefix), e.g. what a sync brought
up to date. It changes nothing:
s3_access = S3Access("testawsimple", profile_name="testawsimple")
sync_result = s3_access.sync_to_directory(Path("backup"))
verify_result = s3_access.verify_directory(Path("backup"), sync_result=sync_result)
for verify_object in verify_result.get_objects(S3VerifyOutcome.differs):
print(verify_object.key, verify_object.reason)
Every local file of an S3 object is compared with the metadata of the S3 object: its size, a hash of its contents and its
modification time (to within mtime_abs_tol, 10 seconds by default). The hash is the strongest hash of the whole contents
that S3 has for the object: its SHA-512 (S3's native one, or the one awsimple writes as object metadata), otherwise S3's
native full-object SHA-256, SHA-1, CRC64NVME, CRC32C or CRC32 checksum (CRC32C needs awscrt, which is installed with
awsimple). An object that S3 has no hash of the whole contents for is verified by size and modification time. Unlike a
sync, a verification makes a metadata request per object and reads every local file. A local file that is missing or whose
size or hash is not the S3 object's differs, one with the contents but not the modification time of the S3 object has the
outcome mtime_differs, and an object that could not be verified is failed without stopping the others. With the result
of a sync, what that sync downloaded or found up to date is verified, without listing the bucket again. Without it, the
bucket is listed. There is an event to request a stop, and a callback per object.
What an S3Access used of S3
AWS charges for S3 requests, at a price that depends on the kind of request and on the storage class of the object, and for
the bytes of the objects that are read. An S3Access counts both, as its usage (an S3Usage):
s3_access = S3Access("testawsimple", profile_name="testawsimple")
s3_access.verify_directory(Path("backup"))
print(s3_access.usage.get_request_counts()) # e.g. {("ListObjectsV2", "STANDARD"): 1, ("HeadObject", "STANDARD"): 950, ("HeadObject", "GLACIER_IR"): 50}
print(s3_access.usage.get_tier_counts()) # e.g. {(S3RequestTier.tier1, "STANDARD"): 1, (S3RequestTier.tier2, "STANDARD"): 950, (S3RequestTier.tier2, "GLACIER_IR"): 50}
print(s3_access.usage.get_download_sizes()) # the bytes S3 sent, by storage class
Every S3 API call of the instance is counted, including the ones of a download in parts and the ones the caller makes with
S3Access.client: by its operation name and by the storage class of its object (STANDARD for a request that is not
for one object, such as a bucket listing). get_tier_counts() has them as the request tiers of an AWS bill: tier 1 (PUT,
COPY, POST, LIST), tier 2 (GET, HEAD and the others) and the requests that are free (DELETE). A request that S3 refuses is
counted, as AWS charges for it, and a request that botocore retried is counted once. awsimple has no prices: they
differ by region and change, so what the usage costs is up to the caller (the AWS Price List has them). A verification of
a directory is a metadata request per object, which for objects in a storage class such as Glacier Instant Retrieval is
charged at many times the price of a request for a STANDARD object.
Caching
S3 objects and DynamoDB tables can be cached locally to reduce network traffic, minimize AWS costs,
and potentially offer a speedup.
DynamoDB cached table scans are particularly useful for tables that are infrequently updated.
The S3 cache is based on the SHA-512 of an object's contents: cached contents are in a file named with their SHA-512.
The SHA-512 of an S3 object (S3's native full-object SHA-512, or the awsimple-sha512 object metadata) is the SHA-512
of its contents, so it is what finds the object in the cache, and S3 objects with the same contents are one cache file.
Downloaded contents are only cached once their calculated SHA-512 matches, and a cache file is only used if it has the
length of the S3 object and the SHA-512 it is named with (otherwise the object is downloaded and the file is written
again). Every cached access makes one request for the S3 object's metadata, so a changed object is never served from
the cache (a download, cached or not, makes that one metadata request and no other). awsimple never updates an S3 object's metadata on a read. When an S3 object has no
SHA-512, it is instead checked against its native CRC64NVME, key, size and modification time: a SHA-512 of these
(with the bucket, version and ETag) is mapped by a local index to the SHA-512 calculated when the contents were
downloaded. The key is only hashed, never used as a cache file name, so file system path irregularities do not
matter. A CRC alone is never a cache key, since a CRC is not collision resistant.
The cache has a maximum size (cache_max_absolute, 1 GB by default, and cache_max_of_free, 5% of the free disk space
by default). When a new file does not fit, the least recently used files are evicted. An object that is larger than
the maximum is not cached. The index file of an object that has no SHA-512 is part of the cache and of its size.
What is in the S3 cache directory (cache_dir, by default aws/s3 in awsimple's directory in the user's cache directory, for all buckets):
| In the cache directory |
What it is |
| files named with 128 hex digits |
The cached contents, each in a file named with the SHA-512 of its contents. |
index sub-directory |
Only made when an S3 object that has no SHA-512 is cached (an object that was not written by awsimple). It has one small file per such object, named with the SHA-512 of the object's identity (see above), that holds the SHA-512 of the contents: the name of the cache file. |
files that end with .tmp |
A file that is being written. It is moved into place in one step when it is complete, and is never read as a cache file. |
The cache directory can be deleted at any time: the contents are downloaded again when they are next needed.
What awsimple Is Not
-
awsimple is not necessarily the most memory and CPU efficient
-
awsimple does not provide cost monitoring hooks
-
awsimple does not provide all the options and features that the regular AWS API (e.g. boto3) does
Updates/Releases
9.5.0 - Typing: the public API is exported explicitly (__all__) and every function is annotated, so an application that is checked with
mypy --strict or pyright can use awsimple as it is. New in S3Access: write_bytes() and read_bytes(), overwrite=False for write_bytes(),
write_string() and write_lines() (the object is only written if there is none with its key, otherwise S3ObjectAlreadyExists), and start_after
for list_objects(), keys() and dir(). A bucket listing is one request (no HeadBucket first). create_bucket() works in us-east-1.
from awsimple import * binds the public API only, and no longer awsimple's submodules (e.g. s3).
9.4.0 - An S3Access counts what it used of S3 that AWS charges for, as its usage (S3Usage): the requests, by S3 API operation and by the storage
class of the object (and as the request tiers AWS prices them by), and the bytes of the objects S3 sent, by storage class. New in the API: S3Usage,
S3RequestTier, get_s3_request_tier() and standard_storage_class.
9.3.2 - When sync_to_directory() fails an object because what was downloaded is not the S3 object, the reason of the failed object says what differs:
the two lengths, or the two CRC64NVMEs. It said only that the length and CRC64NVME were not the S3 object's, and the values were in the log alone.
9.3.1 - The HTTP connection pool of an S3Access holds 20 connections (it was botocore's default of 10), which is what sync_to_directory() can use
at the same time when an object is downloaded in parts. With the smaller pool, connections were opened for one request and discarded, and urllib3 logged
"Connection pool is full, discarding connection".