How Python Developers Can Simulate AWS S3 Locally with MinIO

December 2, 2024

Software Development

Read in minutes

Introduction

As a Python developer, I often need to work with cloud services like AWS S3. However, relying on third-party services during development can introduce several challenges, such as the need to setup a cloud environment, associated costs, latency, and dependency on internet access. To address these issues, I tried MinIO, a powerful object storage solution that mimics the S3 API, enabling to simulate an S3 environment locally. In this article, I’ll walk through how to a quick set up MinIO with Python to try out the tool and then I’ll cover what MinIO is capable of.

Why Simulate S3 Locally?

Using a local S3 simulation (like MinIO) offers several benefits:

  • Eliminate External Dependencies: By simulating S3 locally, you remove the need to rely on external cloud services during development, ensuring that your workflow is unaffected by internet issues or AWS outages.
  • Reduce Costs: Running your own local S3 instance means you won’t incur costs for data storage or transfer on AWS, which is especially useful during the development and testing phases.
  • Ease Development Cycles: Local simulation reduces network latency (due to local network or big files transfer), making your development cycle quicker as you no longer have to have to reach distant servers.

Prerequisites

  1. Python 3.7+
  2. MinIO (we’ll guide you through the installation)
  3. boto3 (the AWS SDK for Python, installable via pip install boto3)

Step 1: Installing and Configuring MinIO

1. Installing MinIO Locally

If you have already a working Python environment, using Docker is one of the easiest ways to get MinIO up and running. Here’s the command to do so:

docker run -p 9000:9000 -p 9001:9001 --name minio \
  -e "MINIO_ROOT_USER=admin" \
  -e "MINIO_ROOT_PASSWORD=password" \
  minio/minio server /data --console-address ":9001"

This command starts a MinIO instance on your local machine, accessible at http://localhost:9000 for object storage and http://localhost:9001 for the admin console.

If you don’t, or if you want to have a dedicated environment to try out the content of this article, you can also use docker-compose to setup a complete container solution:

version: "3.9"

services:
  python-app:
    image: python:3.11-slim

  local-s3-storage:
    image: minio/minio
    environment:
      MINIO_ROOT_USER: "admin"
      MINIO_ROOT_PASSWORD: "password"
    ports:
        - "9000:9000"
        - "9001:9001"
    volumes:
      - minio_data:/data
    command: server /data --console-address ":9001"

  create-bucket:
    image: minio/mc
    depends_on:
      - local-s3-storage
    entrypoint: >
      /bin/sh -c "
      until (/usr/bin/mc alias set myminio http://minio:9000 admin password) do sleep 5; done &&
      /usr/bin/mc mb myminio/transcribovox-videos
      "
volumes:
  minio_data: {}

NB: this is not production-ready, using unsafe credentials is on purpose for educational sake.

2. Accessing MinIO’s Web Interface

After starting MinIO, navigate to http://localhost:9000 in your web browser. Use the credentials (admin and password) you provided in the Docker command to log in. From here, you can create buckets to store your objects, just as you would with AWS S3.

Step 2: Integrating MinIO with Python

Now that MinIO is set up locally, we’ll configure a Python script to interact with it using the boto3 SDK, which is commonly used to interact with AWS services.

1. Setting Up a Python Script

Create a Python file, minio_example.py, and add the following code to interact with your local MinIO instance:

from boto3.session import Session
import boto3
from botocore.exceptions import NoCredentialsError
# MinIO configuration
MINIO_URL = "http://localhost:9000"
MINIO_ACCESS_KEY = "admin"
MINIO_SECRET_KEY = "password"
BUCKET_NAME = "my-bucket"
# Create a boto3 session
session = Session(
    aws_access_key_id=MINIO_ACCESS_KEY,
    aws_secret_access_key=MINIO_SECRET_KEY,
)
# S3 client
s3 = session.resource('s3', endpoint_url=MINIO_URL)
def upload_file(file_path, file_name):
    try:
        # Upload the file to MinIO
        s3.Bucket(BUCKET_NAME).put_object(Key=file_name, Body=open(file_path, 'rb'))
        print(f"File {file_name} uploaded successfully to {BUCKET_NAME}.")
    except NoCredentialsError:
        print("Error: Invalid credentials.")
def download_file(file_name, download_path):
    try:
        # Download the file from MinIO
        obj = s3.Bucket(BUCKET_NAME).Object(file_name).get()
        with open(download_path, 'wb') as f:
            f.write(obj['Body'].read())
        print(f"File {file_name} downloaded successfully to {download_path}.")
    except s3.meta.client.exceptions.NoSuchKey:
        print("Error: File not found.")
if __name__ == "__main__":
    # Example usage
    upload_file('path/to/your/local/file.txt', 'file.txt')
    download_file('file.txt', 'path/to/download/location/file.txt')

This script will allow you to upload files to and download files from your local MinIO instance, mimicking how you would interact with AWS S3.

2. Running the Script

You can run the script using the command:

python minio_example.py

Upon running the script, it will:

  1. Upload a file from your local system to the MinIO bucket.
  2. Download a file from MinIO to a specified local path.

This provides a seamless experience, as if you were interacting with an actual S3 bucket on AWS, but without the need for a network connection or AWS account.

What are MinIO capabilities?

S3 API Compatibility: If you’re already working with AWS S3, you’ll feel right at home with MinIO. It implements the same API, so your existing code and tools will work seamlessly. This means no vendor lock-in and easy integration with your current workflows.

SDKs and CLI: MinIO provides SDKs for popular languages like Python, Java, Go, and JavaScript, making it easy to interact with the server programmatically. The mc command-line tool offers a convenient way to manage buckets, objects, and configurations.

Cloud-Native Design: MinIO is designed to run anywhere – on your laptop, in a container, on Kubernetes, or in the cloud. Its lightweight and containerized architecture makes it easy to deploy and scale.

Performance and Scalability: MinIO is optimized for high throughput and low latency, crucial for demanding applications. It can scale horizontally to handle massive datasets and high request volumes.

Data Protection: MinIO offers features like erasure coding and bitrot protection to ensure data durability. Encryption options are available for data at rest and in transit to meet your security requirements.

MinIO can be used in a production-ready solution with such uses cases in mind:

Microservices: Use MinIO as a persistent storage layer for your microservices architecture.

Machine Learning: Store and manage large datasets for training and deploying machine learning models.

Application Data: Store images, videos, logs, and other unstructured data generated by your applications.

DevOps and CI/CD: Integrate MinIO into your CI/CD pipelines for artifact storage and deployment.

Author : Michael LACROIX, Principal Consultant

SHARE ON :


Related articles

July 1, 2024

Read in minutes

From Code Critic to Craftsman

My journey Throughout my IT career, a relentless pursuit of software quality has been my guiding principle. Early in my career design patterns, those reusable s...

March 25, 2024

Read in 4 minutes

Coding Camp Python

Continuous learning is part of AKABI’s DNA. Every year, all the collaborators have the opportunity to register for some training. At the start of the year...

September 16, 2022

Read in minutes

Blazor – Telerik UI Components

The Blazor framework by Microsoft allows you to create rich web UIs by using .NET and C#. The Telerik® UI for Blazor components facilitate the front-...


comments

From Code Critic to Craftsman

July 1, 2024

Software Development

Read in minutes

My journey

Throughout my IT career, a relentless pursuit of software quality has been my guiding principle. Early in my career design patterns, those reusable solutions to common programming challenges, became my initial toolkit for building robust and well-structured code.

As my skills matured, I expanded my focus to architectural patterns – the bigger picture of software design.

This shift allowed me to consider the overall structure and organization of an application, ensuring its scalability and maintainability.

Throughout my journey, code reviews played a crucial role in sharpening my skills.

These collaborative sessions offered insights into diverse approaches, best practices, and sometimes, not-so-great practices. It was a constant feedback loop, improving my own coding abilities.

This naturally led me to pay it forward. When I write code, I strive to share the knowledge I’ve gained. Clean, well-designed code became not just a personal preference, but a commitment to quality. And code review became the channel to spread it through the collaborators.

For a while, I felt alone in my meticulous approach. But then I discovered the software craftsmanship. A whole community dedicated to the same principles I held dear: a focus on quality, continuous learning, and a deep respect for the craft of coding.

Software craftsmanship isn’t just about writing clean code; it’s about a mindset. It’s about taking pride in your work, constantly seeking improvement, and sharing your knowledge to elevate the entire profession. It’s about being not just a coder, but a true craftsman.

My favorite toy 🧸

While going deeper into software craftsmanship concepts is a worthy pursuit, I prefer to share my favorite tool within my arsenal: the hexagonal architecture.

A good way to visualize this architecture is to imagine a hexagon. Inside it sits your application’s core, focused purely on business logic. Outside the hexagon are all the external things your app interacts with, like databases, other services and UIs. The core doesn’t talk directly to these. Instead, it communicates through defined ports, like an interface contract. Specific adapters implement these ports, handling the details of talking to the specific technology. This keeps the core clean and adaptable, as you can swap out adapters for different technologies without changing the core itself.

The beauty of the hexagonal architecture lies in its simplicity. It promotes a clear separation of concerns within the codebase, reflected in a well-organized folder structure. This immediately creates an environment of readability and maintainability.

Furthermore, by isolating the core domain logic from external dependencies (represented by ports and adapters), the hexagonal architecture naturally introduces key concepts of Domain-Driven Design (DDD). This focus on the domain encourages collaboration – forcing product owners, analysts, and developers to have a shared understanding of the core business functionalities. This establishes a unified language, fostering smoother collaboration across teams.

The defined ports and adapters also serve as excellent entry points for writing clean and testable code. Coupled with dependency injection (a highly recommended practice), hexagonal architecture makes testing effortless.

Finally, the modular nature of adapters empowers you to adapt to future changes. Technological advancements or evolving business needs won’t be postponed by legacy code. Legacy code, in this context, doesn’t mean bad choices, but rather decisions made within that specific previous context. The hexagonal architecture allows you to gracefully evolve the application without being shackled by the past since the core of the application will not be impacted by new implementations of a port.

Fun fact: Even before discovering this formal pattern, I found myself instinctively trying to achieve a similar separation. I’d naturally isolate my domain logic from input concerns like API validation and output concerns like database access. While my homebrew approach wasn’t as elegant as the official hexagonal architecture, it demonstrates the power of prioritizing quality. Having the right tools is important in this changing world.

Sharing our craft for the apprentices

The world of software craftsmanship extends far beyond just writing clean code. It’s about fostering a vibrant community, a modern-day guild where experienced developers take on the role of mentors, passing their knowledge on to the next generation. Throughout my career, I’ve amassed a wealth of experience that not only benefits our clients but also holds immense value for my fellow developers.

In today’s customer-centric world, it’s easy to solely focus on the end product. However, I believe creating software that we can all be proud of, offers a significant short-term benefit for developers themselves. When we prioritize craftsmanship, we elevate the overall quality of the codebase, making it more maintainable, readable, and ultimately more enjoyable to work with. This translates directly into increased developer motivation and happiness – a win for both the individual and the long-term success of the product.

Sharing knowledge and fostering a culture of craftsmanship is what truly excites me. In my next post, I’ll delve into the various collaborative sessions I’ve found effective. If you’re interested in learning how to spread knowledge within your team, stay tuned!

Author: Simon OLBREGTS, Software Craftsmanship Practice Leader at AKABI

SHARE ON :


Related articles

December 2, 2024

Read in minutes

How Python Developers Can Simulate AWS S3 Locally with MinIO

Introduction As a Python developer, I often need to work with cloud services like AWS S3. However, relying on third-party services during development can introd...

March 25, 2024

Read in 4 minutes

Coding Camp Python

Continuous learning is part of AKABI’s DNA. Every year, all the collaborators have the opportunity to register for some training. At the start of the year...

September 16, 2022

Read in minutes

Blazor – Telerik UI Components

The Blazor framework by Microsoft allows you to create rich web UIs by using .NET and C#. The Telerik® UI for Blazor components facilitate the front-...


comments

Coding Camp Python

March 25, 2024

Software Development

Read in 4 minutes

Continuous learning is part of AKABI’s DNA. Every year, all the collaborators have the opportunity to register for some training.

At the start of the year, I had the privilege of guiding my colleagues in the wonderful world of Python.

My challenge was the profile variety. From developers to data analysts. From Python beginner to veteran. But ultimately, Python’s versatility retains its greatest strength, and this training day was filled with exchanges of points of view.

The beginning of the journey

We began with an immersion into the fundamentals of the Python language, exploring its elegant and simple syntax. Then we explored the different data types and some of the greatest built-in tools provided by this language. We continued with some more advanced concepts like the generators and the decorators. The latter has attracted a lot of attention.

We also discussed several automated tools to improve the code quality and avoid issues due to the dynamic typing of Python. First, the duo iSort/Black reformat all the files with the same rules across the developers. Then the famous PyLint for static analysis. Of course, I had to talk about Ruff who does the same but much faster! The last tool presented was MyPy which, thanks to the annotations, allows us to have a type checking (I know it’s a bit against the DuckTyping but it can save your production environment).

We ended this introduction with an introspection exercise. A practical case where we must be able to retrieve a catalog of error classes to automatically generate documentation. This exercise has helped the consultant to understand the limitations of an interpreted language.

“Testing is doubting” but not for developers

After a short break, we dived into the fascinating world of testing. There, we were out of the comfort zone of the data analyst. We start with the well-known unit-test framework. It was brief since I don’t like its approach (more like Java than Python). Then I explain, in detail, the power of Pytest, its simple syntax and the flexibility provided by the fixtures.

Then I was able to share my enthusiasm about the Locust framework that I recently discovered. This tool is so great for perf-testing APIs. And best, we can write our scenario in Python.

Some web frameworks

After lunch and a small recap of the morning, I introduced some frameworks largely used to build APIs.

We start with the validation of user inputs with both Schemas and Pydantic.

With this new knowledge, we were able to discover Flask. The simplicity and easiness of implementing a web service have surprised our .Net developers.

In order to introduce the FastAPI framework, we talked about the GIL. The Global Interpreter Lock allows only one thread to execute code at a time, even on multi-core CPUs. This limits true parallelism. The discussion was mainly focused on how to deal with this limitation thanks to the asynchronous paradigm. We coded some examples of code with Asyncio to better understand this less-known paradigm. Thanks to these foundations, we were able to explore the main functions of FastAPI. Its elegant approach seduced some of the audience.

Data exploration

To end our journey, we explored the world of data analysis. We obviously discussed the famous Numpy and Pandas which are essential tools.

To improve the visualization of our analysis, we used the essential MatPlotLib. And for the first time, we leave the IDE for the data scientist IDE, aka Jupiter notebook.

After this busy day, we were able to discuss our different needs specific to our profiles. Some were even interested in a sequel in the form of a hackathon.

Testimonials

I am very happy to have attended this Python coding camp. I went there to expand my knowledge and refresh my Python skills a bit, but I found it very interesting.
The fact that we reviewed all the most commonly used Python libraries makes this training a real asset for my future projects.
If a Python project were ever to be proposed to me, I now have a better understanding to navigate towards one solution or another.
— Valentin Gesquiere

I had the opportunity to attend Simon’s Python course.
As a data engineer using data-oriented Python, I was looking forward to learning more about the language and its many uses.
After a quick refresher on the basics of the language, Simon went through the many uses of Python, including web frameworks, unit-test frameworks, libraries used in the data domain, and pre-commit tools to improve code quality.
It was really interesting to have an expert able to answer our many questions and show live examples.
I’ve come away from this course with lots of ideas for projects to try out.
— Pierre-Yves Richer

Author: Simon OLBREGTS, Software Craftmanship Practice Leader at AKABI

SHARE ON :


Related articles

December 2, 2024

Read in minutes

How Python Developers Can Simulate AWS S3 Locally with MinIO

Introduction As a Python developer, I often need to work with cloud services like AWS S3. However, relying on third-party services during development can introd...

July 1, 2024

Read in minutes

From Code Critic to Craftsman

My journey Throughout my IT career, a relentless pursuit of software quality has been my guiding principle. Early in my career design patterns, those reusable s...

September 16, 2022

Read in minutes

Blazor – Telerik UI Components

The Blazor framework by Microsoft allows you to create rich web UIs by using .NET and C#. The Telerik® UI for Blazor components facilitate the front-...


comments

Blazor – Telerik UI Components

September 16, 2022

Software Development

Read in minutes

The Blazor framework by Microsoft allows you to create rich web UIs by using .NET and C#. The Telerik® UI for Blazor components facilitate the front-end development by providing ready-made UI components.

Gather information and code snippets to help you develop, test and publish your applications:

Documentation

Here is some summary of all useful information and code snippets to help develop, test and publish your applications:

1.   Product Documentation: The Telerik UI for Blazor documentation hub includes detailed information about each control, theme, tag helpers and more.

2.   Virtual Classroom: This on-demand and hands-on training program will help you hit the ground running with Telerik UI for Blazor. You’ll learn valuable skills while building a sample application in easy-to-digest modules. The Virtual Classroom is only available to trial and licensed users, so take advantage today.

3.   Theme Builder: Easily customize the predefined themes or build a new one based on your business need using Telerik SAAS Theme Builder.

4.   Video Tutorials: A hands-on tutorial of working with Blazor with the help of Telerik UI for Blazor, delivered by a true pro: Ed Charbeneau, three-time Microsoft MVP.

5.   Knowledge Base: The place to find answers to frequently and not-so-frequently asked questions

6.   Product Support:

o    Looking for an answer on specific technical topic – visit the Telerik UI for Blazor support forums.

o    Need some help – 30-day trial also comes with unlimited outstanding technical support delivered by the team that build the components. Just go to our customer support page and file a ticket. Not sure how to file a ticket – blog on that

8.   Social Media:  Facebook or Twitter to stay up to date on the latest developments.

Example: checkbox in grid via a template

SHARE ON :


Related articles

December 2, 2024

Read in minutes

How Python Developers Can Simulate AWS S3 Locally with MinIO

Introduction As a Python developer, I often need to work with cloud services like AWS S3. However, relying on third-party services during development can introd...

July 1, 2024

Read in minutes

From Code Critic to Craftsman

My journey Throughout my IT career, a relentless pursuit of software quality has been my guiding principle. Early in my career design patterns, those reusable s...

March 25, 2024

Read in 4 minutes

Coding Camp Python

Continuous learning is part of AKABI’s DNA. Every year, all the collaborators have the opportunity to register for some training. At the start of the year...


comments