Is it possible to run a script every time an image uploaded

Hi everyone,
I have a python script and strapi app in my linux server. I want analyze every picture with python and send this data to my strapi database. Is it possible to run this script with strapi? After image upload completed, can we execute a python file or script ?
Thans for help

System Information
  • Strapi Version: v4
  • Operating System: Ubuntu 23.10 x64
  • Database: sqlite
  • Node Version: v18.13.0
  • NPM Version: 9.2.0
  • Yarn Version: 1.22.22

Hello,

Certainly! You can integrate your Python script with Strapi to analyze images and store the data in your Strapi database. Let’s break down the steps:

Uploading Images to Strapi:
First, you’ll need to upload the images to Strapi. You can do this by sending a POST request to the /upload endpoint. Make sure to include the image file in the request body as a form-data field named files.
Here’s an example using Python’s requests library:

import requests

url = 'http://localhost:1337/upload'
headers = {'Authorization': 'Bearer your_jwt'}
files = {'files': ('filename.jpeg', open('filename.jpeg', 'rb'), 'image/jpeg')}
response = requests.post(url, files=files, headers=headers)

The response.text will contain the ID of the uploaded image in the Strapi Media Library.

Creating Entries with Image References:
Once you have the image ID, you can create an entry in your collection type (e.g., logs) and reference the image using its ID.
For example:

payload = {
    "Type": 'info',
    "Message": 'lorem ipsum beep bop',
    "Screenshot": 1,  # Replace with the actual image ID
}
response = requests.post('http://localhost:1337/logs', json=payload)

Running Python Script on Image Upload:
Strapi itself does not directly execute Python scripts upon image upload. However, you can set up a separate process (e.g., a cron job or a separate server) that monitors the Strapi database for new image uploads.
When a new image is uploaded, your external process can invoke your Python script to analyze the image and update the relevant Strapi entry.

1 Like

Thank you so much grahamrodrigue.
That helps me in my project and I thinks solves all my problems.
:ok_hand: :pray: