In a flask app, I was trying to iterate through objects in a S3 Bucket and trying to print the key/ filename but my_bucket.objects.all()
returns only the first object in the bucket. It’s not returning the all the objects. The output is [001.pdf]
instead of [001, 002, 003, 004, 005]
JavaScript
x
44
44
1
from flask import Flask, jsonify, Response, request
2
from flask_cors import CORS, cross_origin
3
from config import S3_BUCKET, S3_ACCESS_KEY, S3_SECRET_ACCESS_KEY
4
5
import boto3
6
import csv
7
import re
8
9
10
s3 = boto3.client(
11
's3',
12
aws_access_key_id=S3_ACCESS_KEY,
13
aws_secret_access_key=S3_SECRET_ACCESS_KEY
14
)
15
16
app = Flask(__name__)
17
CORS(app, supports_credentials=True)
18
19
20
@app.route('/')
21
def health():
22
return jsonify({"message": "app is working"})
23
24
25
@app.route('/files')
26
def list_of_files():
27
s3_resource = boto3.resource('s3')
28
my_bucket = s3_resource.Bucket(S3_BUCKET)
29
summaries = my_bucket.objects.all()
30
files = []
31
for file in summaries:
32
# this prints the bucket object
33
print("Object: {}".format(summaries))
34
files.append(file.key)
35
# file.key is supposed to return the names of the list of objects
36
# print(file.key)
37
return jsonify({"files":"{}".format(file.key)})
38
39
40
41
42
if __name__ == "__main__":
43
app.run()
44
Advertisement
Answer
You are exiting the loop by returning too early.
JavaScript
1
9
1
def list_of_files():
2
s3_resource = boto3.resource('s3')
3
my_bucket = s3_resource.Bucket(S3_BUCKET)
4
summaries = my_bucket.objects.all()
5
files = []
6
for file in summaries:
7
files.append(file.key)
8
return jsonify({"files": files})
9