`from flask import Flask, render_template, request, abort
import requests
import os
from werkzeug.utils import secure_filename
app = Flask(name)
Create necessary directories
os.makedirs('static/images', exist_ok=True)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/fetch/path:image_url')
def fetch_image(image_url):
try:
# Fetch image from provided URL
response = requests.get(image_url, stream=True)
if response.status_code != 200:
return abort(404, "Could not fetch image from URL")
# Generate a secure filename for the image
filename = secure_filename(image_url.split('/')[-1])
if not filename.endswith('.png'):
filename = filename.split('.')[0] + '.png'
# Save the image
img_path = os.path.join('static/images', filename)
with open(img_path, 'wb') as f:
for chunk in response.iter_content(1024):
f.write(chunk)
# Store image info in a variable that will be passed to template
img1 = {
'filename': filename,
'path': f'images/{filename}',
'source_url': image_url
}
return render_template('image.html', img1=img1)
except Exception as e:
return abort(500, f"Error processing image: {str(e)}")
if name == 'main':
app.run(debug=True)`
Here’s a clean and clear explanation of the Flask code you’ve shared, with a focus on what each part does and how the image fetching works:
✅ Purpose of This App:
This Flask app takes an image URL as input, fetches the image from the internet, saves it locally in a static/images
folder, and displays it on a webpage.
🔍 Code Breakdown:
1. Imports
from flask import Flask, render_template, request, abort
import requests
import os
from werkzeug.utils import secure_filename
-
Flask
– creates the web application. -
render_template
– renders HTML templates. -
request
– handles incoming data (not directly used here, but useful if you plan to extend it). -
abort
– returns error codes like 404 or 500. -
requests
– used to fetch the image from a URL. -
os
– helps in creating folders and handling file paths. -
secure_filename
– safely formats the filename to avoid path traversal and other issues.
2. App Setup and Directory Creation
app = Flask(__name__)
os.makedirs('static/images', exist_ok=True)
-
Flask(__name__)
– starts the Flask app. -
os.makedirs(...)
– creates the folderstatic/images
if it doesn’t already exist.
3. Homepage Route
@app.route('/')
def index():
return render_template('index.html')
- Loads
index.html
when you open the root URL/
.
4. Image Fetching Route
@app.route('/fetch/')
def fetch_image(image_url):
- This route is triggered when the user goes to
/fetch/
. -
allows slashes in the image URL.
5. Fetch and Save the Image
response = requests.get(image_url, stream=True)
- Sends a GET request to fetch the image content.
if response.status_code != 200:
return abort(404, "Could not fetch image from URL")
- If the image is not available (status ≠ 200), return a 404 error.
6. Create a Safe Filename
filename = secure_filename(image_url.split('/')[-1])
- Extracts the last part of the URL (likely the filename) and secures it.
if not filename.endswith('.png'):
filename = filename.split('.')[0] + '.png'
- Ensures the file ends with
.png
for uniformity.
7. Save the Image Locally
img_path = os.path.join('static/images', filename)
with open(img_path, 'wb') as f:
for chunk in response.iter_content(1024):
f.write(chunk)
- Saves the image in chunks (1KB at a time) to
static/images
.
8. Prepare Image Info for Display
img1 = {
'filename': filename,
'path': f'images/{filename}',
'source_url': image_url
}
- A dictionary storing info about the saved image: filename, relative path, and original source URL.
9. Render the Image Page
return render_template('image.html', img1=img1)
- Passes the image info to
image.html
to display it.
10. Error Handling
except Exception as e:
return abort(500, f"Error processing image: {str(e)}")
- Handles unexpected errors (network issues, disk problems, etc.) and shows a 500 error.
11. Start the Flask App
if __name__ == '__main__':
app.run(debug=True)
- Starts the app in debug mode for easier development and error tracking.
🖼️ Folder Structure Assumed:
project_folder/
│
├── app.py
├── templates/
│ ├── index.html
│ └── image.html
└── static/
└── images/
✅ TL;DR:
-
What it does: Takes an image URL, fetches it, saves it as
.png
, and displays it. - Key features: Safe filename handling, local storage, error handling, and rendering via templates.
- Useful for: Image preview tools, downloaders, or web-based image processors.
Would you like me to give sample index.html
and image.html
code too, to complete this app?