This microservice is built with Flask and serves random images from a specified directory.
-
Install the required Python packages:
pip install -r requirements.txt
-
Edit the
config.txtfile with the directory for your images. The default is set to theimagesfolder in this repository.
The microservice uses Flask's send_file function to serve the file. You can read more about this function here.
To get a random image, send a GET request to the following URL:
http://127.0.0.1:5000/random_image
This will return a random image from the directory specified in your config.txt file.
An example using a request to get a random image can be seen here
<script>
const imageElement = document.getElementById('random-image');
function getRandomImage() {
fetch('http://127.0.0.1:5000/random_image')
.then(response => response.blob())
.then(blob => {
const imageUrl = URL.createObjectURL(blob);
imageElement.src = imageUrl;
})
.catch(error => {
console.error('Error fetching image:', error);
});
}
getRandomImage();
</script>
You can run the microservice locally using the following command:
python random_image_from_directory.py
Replace the image directory in the config file with the path to the directory containing your images before running.
