Connect to S4 with Python (Boto3)
Boto3 is the official AWS SDK for Python. To connect to S4, you only need to change the endpoint, region, and keys. The code below can be placed in a single file and run in order.
Prerequisites
- Create a bucket in the console;
- Create a sub-user and AccessKey, and grant the sub-user access to this bucket. A new sub-user has no permissions;
- Put the keys in environment variables instead of writing them in code:
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"Install
pip install boto3The examples on this page were tested on Python 3.13 and boto3 1.44.10.
Connect to S4
import os
import boto3
from botocore.config import Config
s3 = boto3.client(
"s3",
endpoint_url="https://s3.bitiful.net",
region_name="cn-east-1",
aws_access_key_id=os.environ["S4_ACCESS_KEY"],
aws_secret_access_key=os.environ["S4_SECRET_KEY"],
config=Config(
signature_version="s3v4",
s3={"addressing_style": "virtual"},
retries={"max_attempts": 5, "mode": "standard"},
),
)
BUCKET = "my-bucket"retries makes the SDK retry automatically on network errors and 5xx responses. Multiple threads can share the same client.
Upload files
An object with the same name is overwritten directly. If ContentType is left empty, S4 detects it automatically.
# Upload a text string
s3.put_object(
Bucket=BUCKET,
Key="docs/hello.txt",
Body="你好,S4".encode("utf-8"),
ContentType="text/plain; charset=utf-8",
)
# Upload a local file, setting cache time and custom metadata
with open("photo.jpg", "rb") as f:
s3.put_object(
Bucket=BUCKET,
Key="images/photo.jpg",
Body=f,
ContentType="image/jpeg",
CacheControl="max-age=86400",
Metadata={"author": "bitiful"},
)Upload large files
Use multipart upload for files larger than 100 MB: parts can upload concurrently, and a failed part is the only one you need to retry. Each part is 5 MiB to 20 GiB, with up to 10000 parts.
import threading
from boto3.s3.transfer import TransferConfig
class Progress:
def __init__(self, path: str):
self.total = os.path.getsize(path)
self.sent = 0
self.lock = threading.Lock()
def __call__(self, n: int):
with self.lock:
self.sent += n
print(f"\r{self.sent * 100 / self.total:.1f}%", end="", flush=True)
# Split automatically above 16 MiB, 16 MiB per part, 4 parts uploaded at a time
s3.upload_file(
"video.mp4",
BUCKET,
"videos/video.mp4",
ExtraArgs={"ContentType": "video/mp4"},
Config=TransferConfig(
multipart_threshold=16 * 1024 * 1024,
multipart_chunksize=16 * 1024 * 1024,
max_concurrency=4,
),
Callback=Progress("video.mp4"),
)Download files
Download private files with your secret key. To read only part of a file, use Range instead of downloading the whole file.
# Read into memory
text = s3.get_object(Bucket=BUCKET, Key="docs/hello.txt")["Body"].read().decode("utf-8")
print(text)
# Save to a file (large files are downloaded in concurrent segments automatically)
s3.download_file(BUCKET, "videos/video.mp4", "video-copy.mp4")
# Read only the first 1 KiB
part = s3.get_object(Bucket=BUCKET, Key="videos/video.mp4", Range="bytes=0-1023")
print(part["ContentRange"], len(part["Body"].read()))List files
Each page returns 100 entries by default and 1000 at most; always use a paginator to page through results. Delimiter supports only /.
# List all objects under a prefix, paging automatically
for page in s3.get_paginator("list_objects_v2").paginate(Bucket=BUCKET, Prefix="images/"):
for obj in page.get("Contents", []):
print(obj["Key"], obj["Size"], obj["LastModified"])
# List only the top-level directories
page = s3.list_objects_v2(Bucket=BUCKET, Delimiter="/")
for p in page.get("CommonPrefixes", []):
print("Directory", p["Prefix"])Get file information
Retrieve metadata without downloading the content. You can also use this to check whether an object exists.
from botocore.exceptions import ClientError
def exists(key: str) -> bool:
try:
s3.head_object(Bucket=BUCKET, Key=key)
return True
except ClientError as e:
if e.response["ResponseMetadata"]["HTTPStatusCode"] == 404:
return False
raise
info = s3.head_object(Bucket=BUCKET, Key="images/photo.jpg")
print(info["ContentType"], info["ContentLength"], info["ETag"], info["Metadata"])
print(exists("images/none.jpg"))Copy and move
Copying is done server-side, so data does not pass through your machine. Move is an S4 extension: append ?move=true to CopySource. It only changes the location without copying data, regardless of file size. See Move and rename objects.
# Copy
s3.copy_object(
Bucket=BUCKET,
Key="images/photo-copy.jpg",
CopySource={"Bucket": BUCKET, "Key": "images/photo.jpg"},
)# Move / rename: S4 extension, no data copied
s3.copy_object(
Bucket=BUCKET,
Key="archive/photo.jpg",
CopySource=f"{BUCKET}/images/photo-copy.jpg?move=true",
)Delete files
Deleted objects cannot be recovered. A batch delete handles up to 1000 keys at a time; if you lack write permission on any one key, the whole batch returns 403.
# Delete one object
s3.delete_object(Bucket=BUCKET, Key="docs/hello.txt")
# Batch delete, up to 1000 objects at a time
keys = ["images/a.jpg", "images/b.jpg"]
result = s3.delete_objects(
Bucket=BUCKET,
Delete={"Objects": [{"Key": k} for k in keys], "Quiet": True},
)
for err in result.get("Errors", []):
print(err["Key"], err["Code"], err["Message"])Presigned URLs
A presigned URL embeds the authorization in the link, so the holder can upload or download without a secret key. It is valid for up to 7 days. If you sign Content-Type for an upload, the client must send exactly the same value.
# Download URL, valid for 1 hour, with a specified file name
url = s3.generate_presigned_url(
"get_object",
Params={
"Bucket": BUCKET,
"Key": "images/photo.jpg",
"ResponseContentDisposition": 'attachment; filename="photo.jpg"',
},
ExpiresIn=3600,
)
print(url)
# Upload URL, valid for 10 minutes; the client sends a PUT to it
put_url = s3.generate_presigned_url(
"put_object",
Params={"Bucket": BUCKET, "Key": "uploads/avatar.jpg", "ContentType": "image/jpeg"},
ExpiresIn=600,
)
print(put_url)Presigned URLs with extension parameters
Extension parameters such as CoreIX processing parameters, rate limits, and request limits must be added before signing. Appending them after signing returns SignatureDoesNotMatch.
from urllib.parse import urlencode
def presign_with(operation: str, params: dict, extra: dict, expires: int = 3600) -> str:
"""Generate a presigned URL with S4 extension parameters; they are included in the signature."""
def add_query(request, **_):
request.url += ("&" if "?" in request.url else "?") + urlencode(extra)
event = "before-sign.s3." + {"get_object": "GetObject", "put_object": "PutObject"}[operation]
s3.meta.events.register(event, add_query)
try:
return s3.generate_presigned_url(operation, Params=params, ExpiresIn=expires)
finally:
s3.meta.events.unregister(event, add_query)
target = {"Bucket": BUCKET, "Key": "images/photo.jpg"}
# CoreIX: 500 px wide, convert to WebP
print(presign_with("get_object", target, {"w": "500", "fmt": "webp"}))
# Per-connection rate limit of 1 MiB/s
print(presign_with("get_object", target, {"x-bitiful-limit-rate": "1048576"}))
# At most 3 accesses
print(presign_with("get_object", target, {"x-bitiful-max-requests": "3"}))
# The upload URL can be used only once
print(presign_with("put_object", target, {"x-bitiful-max-requests": "1"}, 600))Conditional writes
Conditional writes prevent concurrent overwrites. When the condition is not met, S4 returns 412. See Conditional requests.
try:
# Write only if the object does not exist, to prevent overwriting
s3.put_object(Bucket=BUCKET, Key="locks/job", Body=b"me", IfNoneMatch="*")
except ClientError as e:
if e.response["Error"]["Code"] == "PreconditionFailed":
print("Object already exists")
else:
raiseHandle errors
For the meaning of each error code, see Error codes and troubleshooting. Rate limiting returns 429 TooManyRequest; catch it and retry with backoff.
from botocore.exceptions import ClientError, EndpointConnectionError
try:
s3.get_object(Bucket=BUCKET, Key="not-exists.txt")
except ClientError as e:
err = e.response["Error"]
meta = e.response["ResponseMetadata"]
print(meta["HTTPStatusCode"], err["Code"], err["Message"], meta.get("RequestId"))
except EndpointConnectionError as e:
print("Network unreachable: ", e)FAQ
Using it in Django or Flask
Create one client at process startup and reuse it instead of creating a new one for every request. When deploying with multiple processes, such as gunicorn, create one client in each process.
How do I write a direct upload from a web page
Have your backend use the put_object presigned URL above and let the frontend PUT directly. For a complete example, see Upload files securely from the client.
Returns 403 AccessDenied
The sub-user has no permission on this bucket or directory. See Sub-user permissions. Creating and deleting buckets can only be done in the console.
Returns SignatureDoesNotMatch
The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the checklist.
Download speed is low
Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a CDN to serve visitors.
Related documentation
Full reference for request limits, rate limits, Simul-Transfer, and other parameters.
Checklists for 403, SignatureDoesNotMatch, and other issues.
Support status and differences for each operation.
Recommended practices for direct uploads from browsers and apps.