Create unique download links in Raspberry Pi using Flask

Posted by:

|

On:

|

I try to implement an automatic link generation and file download process using Flask instead of Apache. Flask is a lightweight web framework for Python that allows you to set up a web server and handle file downloads efficiently.

For all package download and installation, I will do that under virtual environment to manage dependencies without affecting the system Python installation. The detail of creating a virtual environment can be found in my previous blog

https://cs-student.com/virtual-environment-in-raspberry-pi/

To install flask in my Raspberry Pi, I run following commands in terminal :

pip install flask
pip install requests
pip install session

The IP of my Rpi is 192.168.2.230 that can be found out by running following command in terminal:

hostname -I

Set up a Flask application named app.py that generates download links for files.

from flask import Flask, send_from_directory, session, redirect, url_for, render_template
import os
import random
import string

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # Change this to a random secret key
downloads_dir = 'downloads'  # Directory where your files are stored

# List of files with unique identifiers
files = {
    "file1.zip": "file1_unique_id",
    "file2.zip": "file2_unique_id",
    # Add more files if needed
}

def generate_random_string(length=8):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

@app.route('/')
def index():
    random_string = generate_random_string()
    file_name = random.choice(list(files.keys()))
    unique_id = files[file_name]

    # Store the unique ID in the session
    session[random_string] = unique_id

    download_link = url_for('download_file', random_string=random_string)
    return f'Your download link: <a href="{download_link}">http://192.168.2.230/{random_string}</a>'

@app.route('/download/<random_string>')
def download_file(random_string):
    if random_string in session:
        unique_id = session[random_string]
        original_file = next((name for name, uid in files.items() if uid == unique_id), None)

        if original_file and os.path.exists(os.path.join(downloads_dir, original_file)):
            return send_from_directory(downloads_dir, original_file, as_attachment=True)
        else:
            return "File not found.", 404
    else:
        return "Invalid download link.", 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)  # Change host and port as needed

Explanation of the Code

  1. Secret Key: Set a secret key for your Flask session. Make sure to change 'your_secret_key' to a random string.
  2. File List: The files dictionary maps file names to unique identifiers.
  3. Random String Generation: The generate_random_string function generates a random string to use as a session key.
  4. Index Route:
    • When you access the root URL, it generates a random string and selects a random file.
    • The unique ID is stored in the session, and a download link is generated.
  5. Download Route:
    • When a user clicks the download link, the app checks the session for the unique ID.
    • If valid, it sends the requested file for download using send_from_directory.

Running the Flask Application

  1. Create the Downloads Directory: Ensure you have a directory named downloads in the same folder as your Flask app, containing the files you want to serve.
  2. Run the Application: python app.py
  3. Access the Application: Open a web browser and go to http://192.168.2.230:5000/ to generate a download link.
  4. Then click the download link: the file will be downloaded to your computer.

Posted by

in