Build a Python Flask CRUD App with Azure File Storage


This guide walks you through building a CRUD application using Python Flask and Azure File Storage from scratch. You'll learn how to connect Flask with Azure Blob Storage, handle file uploads, list files, and delete files seamlessly.

1. Prerequisites

  • Python installed (Python 3.7+ recommended).
  • An Azure account.
  • Azure Storage Account created. Create one here if needed.
  • Install the required Python packages:
    pip install flask azure-storage-file-share python-dotenv

2. Setting up Azure File Storage

  1. Create a Storage Account:

    • Go to the Azure portal and create a Storage Account.
    • Note down the Storage Account Name and Access Key.
  2. Create a File Share:

    • Inside your Storage Account, navigate to File Shares.
    • Create a new file share and note its Name.

3. Project Structure

Create the following directory structure for your project:

flask-azure-file-storage/ ├── app.py ├── .env ├── requirements.txt └── templates/ ├── index.html ├── upload.html └── files.html

4. Installing Dependencies

Add the following to your requirements.txt file:

Flask==2.2.2
azure-storage-file-share==12.14.1
python-dotenv==1.0.0

Install the dependencies:

pip install -r requirements.txt

5. Configure Environment Variables

Create a .env file to securely store your Azure credentials:

AZURE_STORAGE_ACCOUNT_NAME=<your-storage-account-name>
AZURE_STORAGE_ACCOUNT_KEY=<your-storage-account-key>
AZURE_FILE_SHARE_NAME=<your-file-share-name>

6. Flask Application Code

app.py

This is the main application code to interact with Azure File Storage.

from flask import Flask, render_template, request, redirect, url_for, flash
from azure.storage.fileshare import ShareServiceClient
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

app = Flask(__name__)
app.secret_key = "your_secret_key"

# Azure Storage configurations
STORAGE_ACCOUNT_NAME = os.getenv("AZURE_STORAGE_ACCOUNT_NAME")
STORAGE_ACCOUNT_KEY = os.getenv("AZURE_STORAGE_ACCOUNT_KEY")
FILE_SHARE_NAME = os.getenv("AZURE_FILE_SHARE_NAME")

# Initialize Azure File Share Service Client
file_service = ShareServiceClient(
    account_url=f"https://{STORAGE_ACCOUNT_NAME}.file.core.windows.net",
    credential=STORAGE_ACCOUNT_KEY,
)
file_share_client = file_service.get_share_client(FILE_SHARE_NAME)


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/upload", methods=["GET", "POST"])
def upload_file():
    if request.method == "POST":
        file = request.files.get("file")
        if file:
            try:
                # Upload file to Azure File Share
                file_client = file_share_client.get_file_client(file.filename)
                file_client.upload_file(file)
                flash("File uploaded successfully!", "success")
            except Exception as e:
                flash(f"An error occurred: {e}", "danger")
        return redirect(url_for("list_files"))
    return render_template("upload.html")


@app.route("/files")
def list_files():
    try:
        # List files in Azure File Share
        directory_client = file_share_client.get_directory_client("")
        files = [file.name for file in directory_client.list_directories_and_files()]
    except Exception as e:
        flash(f"An error occurred: {e}", "danger")
        files = []
    return render_template("files.html", files=files)


@app.route("/delete/<filename>")
def delete_file(filename):
    try:
        # Delete file from Azure File Share
        file_client = file_share_client.get_file_client(filename)
        file_client.delete_file()
        flash("File deleted successfully!", "success")
    except Exception as e:
        flash(f"An error occurred: {e}", "danger")
    return redirect(url_for("list_files"))


if __name__ == "__main__":
    app.run(debug=True)

7. HTML Templates

templates/index.html

<!DOCTYPE html>
<html>
<head>
    <title>Flask Azure CRUD</title>
</head>
<body>
    <h1>Welcome to Flask Azure File Storage CRUD</h1>
    <ul>
        <li><a href="/upload">Upload File</a></li>
        <li><a href="/files">View Files</a></li>
    </ul>
</body>
</html>

templates/upload.html

<!DOCTYPE html>
<html>
<head>
    <title>Upload File</title>
</head>
<body>
    <h1>Upload a File</h1>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="file" required />
        <button type="submit">Upload</button>
    </form>
    <a href="/">Back</a>
</body>
</html>

templates/files.html

<!DOCTYPE html>
<html>
<head>
    <title>File List</title>
</head>
<body>
    <h1>Files in Azure File Storage</h1>
    <ul>
        {% for file in files %}
        <li>
            {{ file }}
            <a href="/delete/{{ file }}">Delete</a>
        </li>
        {% endfor %}
    </ul>
    <a href="/">Back</a>
</body>
</html>

8. Running the Application

  1. Start the Flask server:
    python app.py
  2. Open your browser and navigate to http://127.0.0.1:5000.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete