How to display image in S3 bucket using python

In this tutorial will learn about Display image and files in s3 bucket using python.


What is AWS S3 bucket

It is providers object storage which is actually built for storing and retrieve the data from anywhere over the internet.


Example of Display Image, Files in S3 Bucket


Get Your Access Key ID, Access Secret Key and Bucket Name

Access Key ID, Access Secret Key and Buckent Name will be required for programming if you don't have these details then just you need to generate Access Key, Access Secret and Buckent name from AWS Management Console.

Install boto3

If you are using python version 2.x .then use the below code

pip install boto3

If you are using python version 3.x . then use the below code

pip3 install boto3

Python code for Display Image or files


import boto3 from botocore.client import Config from django.http import HttpResponse ACCESS_KEY_ID = 'XXXXXXXXXXXXXXXXXXXXXX' ACCESS_SECRET_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' BUCKET_NAME = 'XXXXXXXX' def s3bucket_getfile(file_path): s3 = boto3.resource('s3', aws_access_key_id=ACCESS_KEY_ID, aws_secret_access_key=ACCESS_SECRET_KEY) obj = s3.Object(BUCKET_NAME,file_path) try: file_stream = obj.get()['Body'].read() if "pdf" in file_path: response = HttpResponse(file_stream, content_type='application/pdf') if "jpg" in file_path: response = HttpResponse(file_stream,content_type="image/jpeg") if "jpeg" in file_path: response = HttpResponse(file_stream,content_type="image/jpeg") response['Content-Disposition'] = 'filename=%s' % file_path return response except: return False s3bucket_getfile(file_path)

NOTE : If you get error of content_type then use mimetype instead of content_type


Hope you like it , please comment if you have any doubt .



How to upload file in S3 bucket in python
Free live cricket score API for python

Post a Comment

0 Comments