Skip to content

Instantly share code, notes, and snippets.

@rounakdatta
Created June 7, 2019 09:21
Show Gist options
  • Save rounakdatta/e845421486e204c9db27489a821adc12 to your computer and use it in GitHub Desktop.
Save rounakdatta/e845421486e204c9db27489a821adc12 to your computer and use it in GitHub Desktop.
List, create and push to buckets in S3 using boto3
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import boto3"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"# low level connector\n",
"s3_client = boto3.client('s3')\n",
"\n",
"# high level connector\n",
"s3_resource = boto3.resource('s3')"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"allBuckets = s3_resource.buckets.all()"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"# programmatic bucket creation\n",
"def createBucket(bucketName):\n",
" s3_resource.create_bucket(Bucket=bucketName, CreateBucketConfiguration={\n",
" 'LocationConstraint': 'ap-south-1'\n",
" })"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"# programmatic deletion of bucket\n",
"def deleteBucket(bucketName):\n",
" s3_resource.Bucket(bucketName).objects.all().delete()"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"318\n"
]
}
],
"source": [
"# how many buckets are there\n",
"nBuckets = sum(1 for _ in allBuckets)\n",
"print(nBuckets)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"# creating new files in S3 bucket\n",
"def writeFileToS3(bucketName, prefix, fileName):\n",
" # prefix should be like 'sub-folder/'\n",
" s3_resource.Object(bucketName, prefix + fileName).put(Body=\"hello*hotstar\")"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"writeFileToS3('rounak-test', 'temp-dir/', 'watchme')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment