{
"cells": [
{
"cell_type": "markdown",
"source": [
"# S3 Read API"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
},
"execution_count": 0
},
{
"cell_type": "raw",
"source": [
".. article-info::\n",
" :avatar-outline: muted\n",
" :author: Sanhe\n",
" :date: Apr 20, 2023\n",
" :read-time: 15 min read\n",
" :class-container: sd-p-2 sd-outline-muted sd-rounded-1"
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"## What is S3 Read API\n",
"\n",
"AWS S3 provides [wide range of APIs](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html), but some of these functions only retrieve information from the server without changing the state of the S3 bucket (e.g. no files are moved, changed, or deleted). Unlike Write API functions, using Read API functions improperly **will NOT** cause any negative impact. Therefore, it is recommended to start by exploring the Read API functions before diving into the Write API.\n",
"\n",
"## Configure the AWS Context object"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "raw",
"source": [
"Before you can run any AWS API, you must first authenticate. The :class:`~s3pathlib.aws.Context` is a singleton object that manages authenticated sessions.\n",
"\n",
"To get started, it's necessary to configure `AWS CLI `_ credentials on your local machine. If you're unsure how to do this, you can follow `this official guide `_ provided by AWS.\n",
"\n",
"Once it's done, you can run the following command to test your authentication."
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 4,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{\r\n",
" \"UserId\": \"ABCDEFABCDEFABCDEFABC\",\r\n",
" \"Account\": \"111122223333\",\r\n",
" \"Arn\": \"arn:aws:iam::111122223333:user/johndoe\"\r\n",
"}\r\n"
]
}
],
"source": [
"!aws sts get-caller-identity"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"The ``Context`` object stores a pre-authenticated [boto session](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/session.html), which is created using your default credentials (if available). However, you can also configure a custom boto session yourself and attach it to the context."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": 2,
"outputs": [],
"source": [
"import boto3\n",
"from s3pathlib import context\n",
"\n",
"context.attach_boto_session(\n",
" boto3.session.Session(\n",
" region_name=\"us-east-1\",\n",
" profile_name=\"my_aws_profile\",\n",
" )\n",
")"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"When ``s3pathlib`` making AWS API calls, it prioritize to use the boto session stored in the Context object. However, you can always explicitly pass in a custom boto session to the API call if needed."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": 10,
"outputs": [],
"source": [
"from s3pathlib import S3Path\n",
"from boto_session_manager import BotoSesManager\n",
"\n",
"bsm = BotoSesManager(\n",
" region_name=\"us-east-1\",\n",
" profile_name=\"my_aws_profile\",\n",
")\n",
"s3path = S3Path(\"s3://my-bucket/test.txt\")\n",
"_ = s3path.write_text(\"hello world\", bsm=bsm) # explicit pass the boto session"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"If you are running the code from Cloud machine like AWS EC2 or AWS Lambda, follow [this official guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html) to grant your computational machine proper AWS S3 access."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"## Get S3 Object Metadata"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "raw",
"source": [
"An object consists of data and its `descriptive metadata `_. ``s3pathlib`` provides a user-friendly interface for accessing object metadata without needing to explicitly invoke the API. Additionally, it automatically caches the underlying `head_object `_ API response for improved performance.\n",
"\n",
"- :attr:`~s3pathlib.core.metadata.MetadataAPIMixin.etag`\n",
"- :attr:`~s3pathlib.core.metadata.MetadataAPIMixin.last_modified_at`\n",
"- :attr:`~s3pathlib.core.metadata.MetadataAPIMixin.size`\n",
"- :attr:`~s3pathlib.core.metadata.MetadataAPIMixin.size_for_human`\n",
"- :attr:`~s3pathlib.core.metadata.MetadataAPIMixin.version_id`\n",
"- :attr:`~s3pathlib.core.metadata.MetadataAPIMixin.expire_at`"
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 5,
"outputs": [
{
"data": {
"text/plain": "S3Path('s3://s3pathlib/test.txt')"
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3path = S3Path(\"s3://s3pathlib/test.txt\")\n",
"s3path.write_text(\"hello world\" * 1000) # create a test object"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 14,
"outputs": [
{
"data": {
"text/plain": "'4d5d1cba9eb18884a5410f4b83bc6951'"
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3path.etag"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 15,
"outputs": [
{
"data": {
"text/plain": "datetime.datetime(2023, 4, 20, 7, 1, 13, tzinfo=tzutc())"
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3path.last_modified_at"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 16,
"outputs": [
{
"data": {
"text/plain": "11000"
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3path.size"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 17,
"outputs": [
{
"data": {
"text/plain": "'10.74 KB'"
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3path.size_for_human"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 18,
"outputs": [
{
"data": {
"text/plain": "'null'"
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3path.version_id"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 23,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"print(s3path.expire_at)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "raw",
"source": [
".. note::\n",
"\n",
" Metadata is cached only once, either when it's first accessed or when the `get_object `_ API is called. The cache is not automatically refreshed and cannot detect server-side changes. To obtain the latest server-side metadata value, you can use the :meth:`~s3pathlib.core.metadata.MetadataAPIMixin.clear_cache` method to clear the cache. The latest data will be retrieved on the next attempt to access the metadata.\n",
"\n",
" please see the following example."
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 26,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"11\n",
"{'creator': 's3pathlib'}\n"
]
}
],
"source": [
"# Create a test file\n",
"s3path = S3Path(\"s3://s3pathlib/file-with-metadata.txt\")\n",
"s3path.write_text(\"hello world\", metadata={\"creator\": \"s3pathlib\"})\n",
"print(s3path.size)\n",
"print(s3path.metadata)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 27,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"11\n",
"{'creator': 's3pathlib'}\n"
]
}
],
"source": [
"# The server side data is changed\n",
"s3path.write_text(\"hello charlice\", metadata={\"creator\": \"charlice\"})\n",
"# You still see the old data\n",
"print(s3path.size)\n",
"print(s3path.metadata)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 28,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"14\n",
"{'creator': 'charlice'}\n"
]
}
],
"source": [
"# After you clear the cache, you got the latest data\n",
"s3path.clear_cache()\n",
"print(s3path.size)\n",
"print(s3path.metadata)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"## Check if Object or Directory Exists\n",
"\n",
"### Check the Existence Of An Object"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "raw",
"source": [
"You can check if an S3 bucket exists using the :meth:`~s3pathlib.core.exists.ExistsAPIMixin.exists` method."
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 32,
"outputs": [
{
"data": {
"text/plain": "True"
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"S3Path(\"s3pathlib\").exists()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 33,
"outputs": [
{
"data": {
"text/plain": "False"
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"S3Path(\"a-bucket-never-exists\").exists()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"You can check if an S3 object exists also."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": 34,
"outputs": [
{
"data": {
"text/plain": "False"
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"S3Path(\"s3://s3pathlib/a-file-never-exists.txt\").exists()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 35,
"outputs": [
{
"data": {
"text/plain": "True"
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3path = S3Path(\"s3://s3pathlib/test.txt\")\n",
"s3path.write_text(\"hello world\")\n",
"s3path.exists()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"[S3 Versioning](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html) is a feature to preserve, retrieve, and restore every version of every object stored in your buckets. ``s3pathlib`` Also support checking existence of \"an object (the latest version)\" or \"a specific version\".\n",
"\n"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": 40,
"outputs": [
{
"data": {
"text/plain": "S3Path('s3://s3pathlib-versioning-enabled/test.txt')"
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# the s3pathlib-versioning-enabled bucket enabled versioning\n",
"s3path = S3Path(\"s3://s3pathlib-versioning-enabled/test.txt\")\n",
"# prepare some test data\n",
"v1 = s3path.write_text(\"v1\").version_id # add v1\n",
"v2 = s3path.write_text(\"v2\").version_id # add v2\n",
"s3path.delete() # add a delete marker on v2"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 41,
"outputs": [
{
"data": {
"text/plain": "False"
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# the object (latest) is considered as \"not exists\" since the latest version is marked as \"deleted\"\n",
"s3path.exists()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 42,
"outputs": [
{
"data": {
"text/plain": "True"
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3path.exists(version_id=v1) # but the older version is considered as exists"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 43,
"outputs": [
{
"data": {
"text/plain": "'v1'"
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3path.read_text(version_id=v1) # verify that it is really the older version"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"### Check The Existence of A Directory\n",
"\n",
"As an S3 directory is a logical concept and often doesn't physically exist, its ``exists()`` method will return ``True`` only if there is at least one object within the directory or if the directory is a hard folder (an empty object with a trailing \"/\")."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": 44,
"outputs": [
{
"data": {
"text/plain": "False"
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# at begin, the folder not exists because there's no file in it\n",
"s3dir = S3Path(\"s3://s3pathlib/soft-folder/\")\n",
"s3dir.exists()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 45,
"outputs": [
{
"data": {
"text/plain": "True"
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# after creating a file in it, even though it is not a hard folder, it is still considered as \"exists\"\n",
"s3dir.joinpath(\"file.txt\").write_text(\"hello world\")\n",
"s3dir.exists()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 46,
"outputs": [
{
"data": {
"text/plain": "False"
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# at begin, the hard folder not exists, because we haven't created it yet\n",
"s3dir = S3Path(\"s3://s3pathlib/hard-folder/\")\n",
"s3dir.exists()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 48,
"outputs": [
{
"data": {
"text/plain": "True"
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# after creating a hard folder, now it exists\n",
"s3dir.mkdir(exist_ok=True)\n",
"s3dir.exists()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 50,
"outputs": [
{
"data": {
"text/plain": "''"
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# and you can see that the hard folder is just an empty object with trailing \"/\" in the S3 key\n",
"s3dir.read_text()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 49,
"outputs": [
{
"data": {
"text/plain": "0"
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# and there is no object in it\n",
"s3dir.count_objects()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"You cannot check existence for Void path and Relative path, because they are logical concepts."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"## Count Number of Objects and Total Size in a Directory"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "raw",
"source": [
"AWS Console has a button \"Calculate Total Size\" tells you how many objects and the total size in a S3 folder. :meth:`~s3pathlib.core.iter_objects.IterObjectsAPIMixin.calculate_total_size` and :meth:`~s3pathlib.core.iter_objects.IterObjectsAPIMixin.count_objects` can do that too.\n",
"\n",
".. image:: ./_static/images/calculate-total-size.png\n"
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 62,
"outputs": [
{
"data": {
"text/plain": "S3Path('s3://s3pathlib/calculate-total-zie/file3.txt')"
},
"execution_count": 62,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3dir = S3Path(\"s3://s3pathlib/calculate-total-zie/\")\n",
"s3dir.mkdir(exist_ok=True) # this is a hard folder and actually exists\n",
"s3dir.joinpath(\"file1.txt\").write_text(\"Hello Alice\\n\" * 1000)\n",
"s3dir.joinpath(\"file2.txt\").write_text(\"Hello Bob\\n\" * 1000)\n",
"s3dir.joinpath(\"file3.txt\").write_text(\"Hello Cathy\\n\" * 1000)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 63,
"outputs": [
{
"data": {
"text/plain": "(3, 34000)"
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3dir.calculate_total_size()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 64,
"outputs": [
{
"data": {
"text/plain": "(3, '33.20 KB')"
},
"execution_count": 64,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3dir.calculate_total_size(for_human=True)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "raw",
"source": [
".. note::\n",
"\n",
" In the AWS S3 console, when you click the \"Create Folder\" button, an empty object with a trailing ``/`` is created to represent the logical folder. Although invisible to humans, the empty object actually exists and counts as an object in the native AWS boto3 API.\n",
"\n",
" As humans, we don't necessarily care about \"logical folders\" and typically only want to see the number of objects we expect. Therefore, **by default**, ``s3pathlib`` **doesn't count logical folders** and doesn't include them in the :meth:``~s3pathlib.core.iter_objects.IterObjectsAPIMixin.iter_objects`` API.\n",
"\n",
" If you want to include logical folders, you can use the ``include_folder=True`` argument.\n",
"\n",
" For more information on logical folders, see the official AWS documentation on `Using Folder `_."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 66,
"outputs": [
{
"data": {
"text/plain": "4"
},
"execution_count": 66,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# since we \"include folder\", so it returns 4 (one hard folder and three objects)\n",
"s3dir.count_objects(include_folder=True)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"## List and Filter Objects\n",
"\n",
"In a file system, it is very common to:\n",
"\n",
"- list all sub-folders and files in the current directory, not recursively.\n",
"- recursively travel through all sub-folders and files.\n",
"- filter folder and files by user-defined criteria.\n",
"\n",
"S3Pathlib provides a user-friendly interface to do so.\n",
"\n",
"### List Objects"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "raw",
"source": [
"The :meth:`~s3pathlib.core.iter_objects.IterObjectsAPIMixin.iter_objects` method is the core API for listing and filtering S3 objects (not directories). It supports the following arguments:\n",
"\n",
"- ``batch_size``: an integer, the number of S3 objects returned per API call. Internally, it makes pagination API calls to iterate through all S3 objects. A large batch size can reduce the total number of API calls and improve performance.\n",
"- ``limit``: an integer, limits the number of objects you want to return.\n",
"- ``recursive``: default to ``True``, and goes through subfolders as well. However, you can set it to ``False`` to only iterate through the top-level folder.\n",
"- it go through sub folder too. But you can set to ``False`` to go through top level folder only\n",
"- ``include_folder``: defaults to ``False``. If set to ``True``, it also returns empty S3 objects that end with a trailing ``/``, which are considered as folders in the S3 console."
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 92,
"outputs": [
{
"data": {
"text/plain": "7"
},
"execution_count": 92,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# first, let's prepare some test data\n",
"s3dir = S3Path(\"s3://s3pathlib/list-objects/\")\n",
"s3dir.joinpath(\"README.txt\").write_text(\"read me please\") # 1\n",
"s3dir.joinpath(\"logo.png\").write_bytes(b\"01010101\" * 1000) # 2\n",
"s3dir.joinpath(\"folder/data1.json\").write_text('{\"name\": \"alice\"}') # 3\n",
"s3dir.joinpath(\"folder/data2.json\").write_text('{\"name\": \"bob\"}') # 4\n",
"s3dir.joinpath(\"folder/subfolder/config.ini\").write_text('this is a config file') # 5\n",
"s3dir.joinpath(\"folder/logs/day1.txt\").write_text(\"Hello Alice\\n\" * 1000) # 6\n",
"s3dir.joinpath(\"folder/logs/day2.txt\").write_text(\"Hello Bob\\n\" * 1000) # 7\n",
"s3dir.count_objects()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 93,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/README.txt')\n",
"S3Path('s3://s3pathlib/list-objects/folder/data1.json')\n",
"S3Path('s3://s3pathlib/list-objects/folder/data2.json')\n",
"S3Path('s3://s3pathlib/list-objects/folder/logs/day1.txt')\n",
"S3Path('s3://s3pathlib/list-objects/folder/logs/day2.txt')\n",
"S3Path('s3://s3pathlib/list-objects/folder/subfolder/config.ini')\n",
"S3Path('s3://s3pathlib/list-objects/logo.png')\n"
]
}
],
"source": [
"for s3path in s3dir.iter_objects():\n",
" print(s3path)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 94,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/README.txt')\n",
"S3Path('s3://s3pathlib/list-objects/logo.png')\n"
]
}
],
"source": [
"for s3path in s3dir.iter_objects(recursive=False):\n",
" print(s3path)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "raw",
"source": [
"The :meth:`~s3pathlib.core.iter_objects.IterObjectsAPIMixin.iter_objects` actually returns a :class:`~s3pathlib.core.iter_objects.S3PathIterProxy` object. This is a user-friendly iterable Python object that allows you to iterate over a subset of the returned data instead of loading everything into memory in one shot. It also provides additional features such as pagination, skipping, getting one or none, and custom filtering."
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 95,
"outputs": [],
"source": [
"# Create proxy\n",
"proxy = s3dir.iter_objects()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 96,
"outputs": [
{
"data": {
"text/plain": "S3Path('s3://s3pathlib/list-objects/README.txt')"
},
"execution_count": 96,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get one item\n",
"proxy.one()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 97,
"outputs": [
{
"data": {
"text/plain": "[S3Path('s3://s3pathlib/list-objects/folder/data1.json'),\n S3Path('s3://s3pathlib/list-objects/folder/data2.json')]"
},
"execution_count": 97,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get many items\n",
"proxy.many(2)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 98,
"outputs": [
{
"data": {
"text/plain": "S3Path('s3://s3pathlib/list-objects/folder/logs/day2.txt')"
},
"execution_count": 98,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Skip some items\n",
"proxy.skip(1) # s3://s3pathlib/list-objects/folder/data1.json is skipped\n",
"proxy.one()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 99,
"outputs": [
{
"data": {
"text/plain": "[S3Path('s3://s3pathlib/list-objects/folder/subfolder/config.ini'),\n S3Path('s3://s3pathlib/list-objects/logo.png')]"
},
"execution_count": 99,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get the rest of items\n",
"proxy.all()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 100,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"# Get one item or none\n",
"print(proxy.one_or_none())"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 101,
"outputs": [
{
"data": {
"text/plain": "[S3Path('s3://s3pathlib/list-objects/README.txt'),\n S3Path('s3://s3pathlib/list-objects/folder/data1.json'),\n S3Path('s3://s3pathlib/list-objects/folder/data2.json'),\n S3Path('s3://s3pathlib/list-objects/folder/logs/day1.txt'),\n S3Path('s3://s3pathlib/list-objects/folder/logs/day2.txt'),\n S3Path('s3://s3pathlib/list-objects/folder/subfolder/config.ini'),\n S3Path('s3://s3pathlib/list-objects/logo.png')]"
},
"execution_count": 101,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Load everything into a list in one shot\n",
"s3dir.iter_objects().all()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"### Filter Objects\n",
"\n",
"#### Filtering by Attributes\n",
"\n",
"``s3pathlib`` provides a SQL liked interface that allows you to filter the object by their attributes.\n",
"Below is the full list of built-in attributes can be used for filtering:\n",
"\n",
"- ``S3Path.bucket: str``\n",
"- ``S3Path.key: str``\n",
"- ``S3Path.uri: str``\n",
"- ``S3Path.arn: str``\n",
"- ``S3Path.parts: list[str]``\n",
"- ``S3Path.basename: str``\n",
"- ``S3Path.fname: str``\n",
"- ``S3Path.ext: str``\n",
"- ``S3Path.dirname: str``\n",
"- ``S3Path.dirpath: str``\n",
"- ``S3Path.abspath: str``\n",
"- ``S3Path.etag: str``\n",
"- ``S3Path.size: int``\n",
"- ``S3Path.last_modified_at: datetime``\n",
"- ``S3Path.version_id: str``\n",
"- ``S3Path.expire_at: datetime``"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": 102,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/folder/data1.json')\n",
"S3Path('s3://s3pathlib/list-objects/folder/data2.json')\n"
]
}
],
"source": [
"# filter by file extension\n",
"for s3path in s3dir.iter_objects().filter(S3Path.ext == \".json\"):\n",
" print(s3path)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 118,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/folder/logs/day1.txt') 12000\n",
"S3Path('s3://s3pathlib/list-objects/folder/logs/day2.txt') 10000\n",
"S3Path('s3://s3pathlib/list-objects/logo.png') 8000\n"
]
}
],
"source": [
"# filter by file extension\n",
"for s3path in s3dir.iter_objects().filter(S3Path.size >= 1000):\n",
" print(s3path, s3path.size)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"#### Filtering by Comparator\n",
"\n",
"Comparator is just a function to construct the filtering criteria for you."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": 117,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/folder/logs/day1.txt') 12000\n",
"S3Path('s3://s3pathlib/list-objects/folder/logs/day2.txt') 10000\n",
"S3Path('s3://s3pathlib/list-objects/logo.png') 8000\n"
]
}
],
"source": [
"for s3path in s3dir.iter_objects().filter(S3Path.size.between(1_000, 1_000_1000)):\n",
" print(s3path, s3path.size)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 121,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/folder/data1.json')\n",
"S3Path('s3://s3pathlib/list-objects/folder/data2.json')\n"
]
}
],
"source": [
"for s3path in s3dir.iter_objects().filter(S3Path.basename.startswith(\"data\")):\n",
" print(s3path)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 122,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/folder/subfolder/config.ini')\n"
]
}
],
"source": [
"for s3path in s3dir.iter_objects().filter(S3Path.abspath.contains(\"subfolder\")):\n",
" print(s3path)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "raw",
"source": [
".. seealso::\n",
"\n",
" Below is the full list of built-in comparators:\n",
"\n",
" - :meth:`~s3pathlib.core.filterable_property.FilterableProperty.equal_to`\n",
" - :meth:`~s3pathlib.core.filterable_property.FilterableProperty.not_equal_to`\n",
" - :meth:`~s3pathlib.core.filterable_property.FilterableProperty.greater`\n",
" - :meth:`~s3pathlib.core.filterable_property.FilterableProperty.less`\n",
" - :meth:`~s3pathlib.core.filterable_property.FilterableProperty.greater_equal`\n",
" - :meth:`~s3pathlib.core.filterable_property.FilterableProperty.less_equal`\n",
" - :meth:`~s3pathlib.core.filterable_property.FilterableProperty.between`\n",
" - :meth:`~s3pathlib.core.filterable_property.FilterableProperty.startswith`\n",
" - :meth:`~s3pathlib.core.filterable_property.FilterableProperty.endswith`\n",
" - :meth:`~s3pathlib.core.filterable_property.FilterableProperty.contains`"
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"#### Logical Operator\n",
"\n",
"If you want to use multiple criteria, the ``filter()`` method takes multiple positioning arguments and join them with logic AND automatically."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": 108,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/folder/logs/day1.txt')\n",
"S3Path('s3://s3pathlib/list-objects/folder/logs/day2.txt')\n"
]
}
],
"source": [
"for s3path in s3dir.iter_objects().filter(S3Path.ext == \".txt\", S3Path.size >= 1000):\n",
" print(s3path)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"The ``filter()`` method also can be chained, all chained filters will be joined with logic AND. It uses lazy load technique to evaluate the criteria when the data is returned."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": 110,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/folder/logs/day1.txt')\n",
"S3Path('s3://s3pathlib/list-objects/folder/logs/day2.txt')\n"
]
}
],
"source": [
"for s3path in (\n",
" s3dir.iter_objects()\n",
" .filter(S3Path.ext == \".txt\")\n",
" .filter(S3Path.size >= 1000)\n",
"):\n",
" print(s3path)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"The ``and_``, ``or_``, ``not_`` helper functions can define complicated filtering logics."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": 113,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/folder/data1.json')\n",
"S3Path('s3://s3pathlib/list-objects/folder/data2.json')\n",
"S3Path('s3://s3pathlib/list-objects/folder/subfolder/config.ini')\n"
]
}
],
"source": [
"from s3pathlib import and_, or_, not_\n",
"\n",
"for s3path in s3dir.iter_objects().filter(not_(or_(S3Path.ext == \".txt\", S3Path.ext == \".png\"))):\n",
" print(s3path)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"#### Custom Filter Function"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "raw",
"source": [
"You can define your own custom filter function. A filter function is simply a callable function that takes only one argument, a :class:`~s3pathlib.core.s3path.S3Path` object, and returns a boolean value to indicate whether we want to keep this object. If it returns False, the ``S3Path`` object will not be returned. You can define arbitrary criteria in your filter function."
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 114,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"S3Path('s3://s3pathlib/list-objects/folder/data1.json') 17\n",
"S3Path('s3://s3pathlib/list-objects/folder/data2.json') 15\n",
"S3Path('s3://s3pathlib/list-objects/folder/subfolder/config.ini') 21\n"
]
}
],
"source": [
"# the size in bytes is odd number\n",
"def size_is_odd(s3path: S3Path) -> bool:\n",
" return s3path.size % 2\n",
"\n",
"for s3path in s3dir.iter_objects().filter(size_is_odd):\n",
" print(s3path, s3path.size)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "raw",
"source": [
".. note::\n",
"\n",
" When using filter with ``limit`` argument. The iterator yield ``limit`` number of items first, then apply filter to the results afterwards. In conclusion, the final number of matched items is usually SMALLER than ``limit``."
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"## Iter Directory"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "raw",
"source": [
"The ``iter_objects`` method only returns objects. If you want to iterate folders and objects all together, you can use the :meth:`~s3pathlib.core.iter_objects.IterObjectsAPIMixin.iterdir` method."
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 126,
"outputs": [
{
"data": {
"text/plain": "[S3Path('s3://s3pathlib/list-objects/folder/'),\n S3Path('s3://s3pathlib/list-objects/README.txt'),\n S3Path('s3://s3pathlib/list-objects/logo.png')]"
},
"execution_count": 126,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3dir.iterdir().all()"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"## List Object Versions"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "raw",
"source": [
"On versioning enabled bucket, you can list all versions of an object by calling the :meth:`~s3pathlib.core.iter_object_versions.IterObjectVersionsAPIMixin.list_object_versions` method. It will return versions in reverse chronological order. The :meth:`~s3pathlib.core.is_test.IsTestAPIMixin.is_delete_marker` method can be used to check if the version is a delete marker."
],
"metadata": {
"collapsed": false,
"raw_mimetype": "text/restructuredtext",
"pycharm": {
"name": "#%% raw\n"
}
}
},
{
"cell_type": "code",
"execution_count": 13,
"outputs": [],
"source": [
"# First, let's prepare some test data\n",
"import time\n",
"\n",
"s3path = S3Path(\"s3pathlib-versioning-enabled/file.txt\")\n",
"s3path.write_text(\"v1\")\n",
"time.sleep(1)\n",
"s3path.write_text(\"v2\")\n",
"time.sleep(1)\n",
"s3path.delete()\n",
"time.sleep(1)\n",
"s3path.write_text(\"v3\")\n",
"time.sleep(1)\n",
"s3path.write_text(\"v4\")\n",
"time.sleep(1)\n",
"s3path.delete()\n",
"time.sleep(1)\n",
"s3path.write_text(\"v5\")\n",
"time.sleep(1)"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "code",
"execution_count": 16,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"version_id = Fh4t9N2vUelLUa8Z8gSSJSDyKTVOMA19, is_delete_marker = False, content = v5\n",
"version_id = Hij7d8MKHqv_RaOimyHHTP3IbX9Dpcp8, is_delete_marker = True, content = it's a delete marker\n",
"version_id = 29rFPVkoeNj_SbW28yARvZ9rSps1Lr6P, is_delete_marker = False, content = v4\n",
"version_id = wJwrSJy36Wa5vJr4DhBw5T_MuQ3hMvMf, is_delete_marker = False, content = v3\n",
"version_id = 8ARcxb.AOTVBKPMjBXzhYX9uk5krGrIV, is_delete_marker = True, content = it's a delete marker\n",
"version_id = 36HjB5gG7oBzuS7Iiu7GixMyPKzkIEog, is_delete_marker = False, content = v2\n",
"version_id = nm2Zw.jv2yGywNmCVsR5wodrHwfPwTUX, is_delete_marker = False, content = v1\n"
]
}
],
"source": [
"for s3path_versioned in s3path.list_object_versions():\n",
" version_id = s3path_versioned.version_id\n",
" is_delete_marker = s3path_versioned.is_delete_marker()\n",
" try:\n",
" content = s3path_versioned.read_text(version_id=version_id)\n",
" except Exception as e:\n",
" content = \"it's a delete marker\"\n",
" print(f\"version_id = {version_id}, is_delete_marker = {is_delete_marker}, content = {content}\")"
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
},
{
"cell_type": "markdown",
"source": [
"## What's Next\n",
"\n",
"Now that we've learned some examples of using S3 read APIs, let's move on to the next section to learn how to use S3 write APIs."
],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%% md\n"
}
}
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [],
"metadata": {
"collapsed": false,
"pycharm": {
"name": "#%%\n"
}
}
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}