Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions flask_file_upload_mvc/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.env

/uploads/
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
29 changes: 29 additions & 0 deletions flask_file_upload_mvc/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import os
import logging
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import Config
from extensions import db
# Initialize Flask app
app = Flask(__name__)
app.config.from_object(Config)

# Initialize database
db.init_app(app)

# Configure logging
os.makedirs(app.config['LOG_FOLDER'], exist_ok=True)
logging.basicConfig(
filename=os.path.join(app.config['LOG_FOLDER'], 'app.log'),
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s'
)

# Register blueprints AFTER db is initialized
with app.app_context():
from controllers.file_controller import file_bp
app.register_blueprint(file_bp)
db.create_all()

if __name__ == '__main__':
app.run(debug=True)
14 changes: 14 additions & 0 deletions flask_file_upload_mvc/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import os
from dotenv import load_dotenv

load_dotenv()

class Config:
SQLALCHEMY_DATABASE_URI = (
f"mysql+pymysql://{os.getenv('DB_USER')}:{os.getenv('DB_PASSWORD')}@"
f"{os.getenv('DB_HOST')}:{os.getenv('DB_PORT')}/{os.getenv('DB_NAME')}"
)
SQLALCHEMY_TRACK_MODIFICATIONS = False
UPLOAD_FOLDER = os.getenv('UPLOAD_FOLDER', 'uploads')
LOG_FOLDER = 'logs'
DEBUG = True
Binary file not shown.
68 changes: 68 additions & 0 deletions flask_file_upload_mvc/controllers/file_controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
from flask import Blueprint, current_app, request, jsonify, send_file
from services.file_service import save_file, update_file, delete_file
from models.uploaded_file import UploadedFile
import uuid
import logging

file_bp = Blueprint('file_bp', __name__)

# POST - Upload file
@file_bp.route('/upload', methods=['POST'])
def upload_file():
try:
if 'file' not in request.files:
return jsonify({'message': 'No file uploaded'}), 400

file = request.files['file']
folder = f"{current_app.config['UPLOAD_FOLDER']}/{uuid.uuid4().hex}" # new folder per request
uploaded = save_file(file, folder)

return jsonify({
'message': 'Upload successful',
'id': uploaded.id,
'path': uploaded.file_path
}), 201
except Exception as e:
logging.error(f"Upload error: {e}")
return jsonify({'message': str(e)}), 400

# GET - Retrieve file info or download
@file_bp.route('/file/<int:file_id>', methods=['GET'])
def get_file(file_id):
try:
file = UploadedFile.query.get(file_id)
if not file:
return jsonify({'message': 'File not found'}), 404

return send_file(file.file_path, as_attachment=True)
except Exception as e:
logging.error(f"Get error: {e}")
return jsonify({'message': str(e)}), 400

# PUT - Update file
@file_bp.route('/file/<int:file_id>', methods=['PUT'])
def update_existing_file(file_id):
try:
if 'file' not in request.files:
return jsonify({'message': 'No file provided'}), 400

file = request.files['file']
updated = update_file(file_id, file, current_app.config['UPLOAD_FOLDER'])

return jsonify({
'message': 'File updated successfully',
'path': updated.file_path
}), 200
except Exception as e:
logging.error(f"Update error: {e}")
return jsonify({'message': str(e)}), 400

# DELETE - Delete file
@file_bp.route('/file/<int:file_id>', methods=['DELETE'])
def delete_existing_file(file_id):
try:
delete_file(file_id)
return jsonify({'message': 'File deleted successfully'}), 200
except Exception as e:
logging.error(f"Delete error: {e}")
return jsonify({'message': str(e)}), 400
3 changes: 3 additions & 0 deletions flask_file_upload_mvc/extensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
89 changes: 89 additions & 0 deletions flask_file_upload_mvc/logs/app.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
2025-10-19 19:02:36,047 [INFO] WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
2025-10-19 19:02:36,047 [INFO] Press CTRL+C to quit
2025-10-19 19:02:36,048 [INFO] * Restarting with stat
2025-10-19 19:02:36,529 [WARNING] * Debugger is active!
2025-10-19 19:02:36,531 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:04:04,348 [INFO] 127.0.0.1 - - [19/Oct/2025 19:04:04] "GET /upload HTTP/1.1" 405 -
2025-10-19 19:05:01,747 [ERROR] Upload error: module 'flask.app' has no attribute 'config'
2025-10-19 19:05:01,748 [INFO] 127.0.0.1 - - [19/Oct/2025 19:05:01] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:06:16,772 [INFO] * Detected change in 'C:\\Users\\jac23\\Desktop\\FileUploadFlask\\file-upload\\flask_file_upload_mvc\\controllers\\file_controller.py', reloading
2025-10-19 19:06:16,860 [INFO] * Restarting with stat
2025-10-19 19:06:17,438 [WARNING] * Debugger is active!
2025-10-19 19:06:17,440 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:06:35,549 [INFO] * Detected change in 'C:\\Users\\jac23\\Desktop\\FileUploadFlask\\file-upload\\flask_file_upload_mvc\\controllers\\file_controller.py', reloading
2025-10-19 19:06:35,646 [INFO] * Restarting with stat
2025-10-19 19:06:36,148 [WARNING] * Debugger is active!
2025-10-19 19:06:36,150 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:06:49,020 [INFO] WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
2025-10-19 19:06:49,020 [INFO] Press CTRL+C to quit
2025-10-19 19:06:49,021 [INFO] * Restarting with stat
2025-10-19 19:06:49,493 [WARNING] * Debugger is active!
2025-10-19 19:06:49,495 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:06:52,723 [ERROR] Upload error: The current Flask app is not registered with this 'SQLAlchemy' instance. Did you forget to call 'init_app', or did you create multiple 'SQLAlchemy' instances?
2025-10-19 19:06:52,723 [INFO] 127.0.0.1 - - [19/Oct/2025 19:06:52] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:06:53,605 [ERROR] Upload error: The current Flask app is not registered with this 'SQLAlchemy' instance. Did you forget to call 'init_app', or did you create multiple 'SQLAlchemy' instances?
2025-10-19 19:06:53,605 [INFO] 127.0.0.1 - - [19/Oct/2025 19:06:53] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:07:21,219 [ERROR] Upload error: The current Flask app is not registered with this 'SQLAlchemy' instance. Did you forget to call 'init_app', or did you create multiple 'SQLAlchemy' instances?
2025-10-19 19:07:21,219 [INFO] 127.0.0.1 - - [19/Oct/2025 19:07:21] "POST /upload?file= HTTP/1.1" 400 -
2025-10-19 19:08:09,972 [INFO] * Detected change in 'C:\\Users\\jac23\\Desktop\\FileUploadFlask\\file-upload\\flask_file_upload_mvc\\models\\uploaded_file.py', reloading
2025-10-19 19:08:10,064 [INFO] * Restarting with stat
2025-10-19 19:09:10,245 [INFO] WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
2025-10-19 19:09:10,245 [INFO] Press CTRL+C to quit
2025-10-19 19:09:10,246 [INFO] * Restarting with stat
2025-10-19 19:09:10,722 [WARNING] * Debugger is active!
2025-10-19 19:09:10,723 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:09:28,337 [INFO] 127.0.0.1 - - [19/Oct/2025 19:09:28] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:09:35,428 [INFO] 127.0.0.1 - - [19/Oct/2025 19:09:35] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:11:12,434 [INFO] * Detected change in 'C:\\Users\\jac23\\Desktop\\FileUploadFlask\\file-upload\\flask_file_upload_mvc\\controllers\\file_controller.py', reloading
2025-10-19 19:11:12,529 [INFO] * Restarting with stat
2025-10-19 19:11:13,076 [WARNING] * Debugger is active!
2025-10-19 19:11:13,078 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:11:23,462 [INFO] WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
2025-10-19 19:11:23,463 [INFO] Press CTRL+C to quit
2025-10-19 19:11:23,464 [INFO] * Restarting with stat
2025-10-19 19:11:23,998 [WARNING] * Debugger is active!
2025-10-19 19:11:24,000 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:11:37,529 [INFO] 127.0.0.1 - - [19/Oct/2025 19:11:37] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:11:54,450 [INFO] 127.0.0.1 - - [19/Oct/2025 19:11:54] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:11:55,229 [INFO] 127.0.0.1 - - [19/Oct/2025 19:11:55] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:11:55,687 [INFO] 127.0.0.1 - - [19/Oct/2025 19:11:55] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:11:56,070 [INFO] 127.0.0.1 - - [19/Oct/2025 19:11:56] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:11:56,387 [INFO] 127.0.0.1 - - [19/Oct/2025 19:11:56] "POST /upload HTTP/1.1" 400 -
2025-10-19 19:14:45,256 [ERROR] Upload error: The current Flask app is not registered with this 'SQLAlchemy' instance. Did you forget to call 'init_app', or did you create multiple 'SQLAlchemy' instances?
2025-10-19 19:14:45,256 [INFO] 127.0.0.1 - - [19/Oct/2025 19:14:45] "POST /upload?file= HTTP/1.1" 400 -
2025-10-19 19:15:28,149 [INFO] WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
2025-10-19 19:15:28,149 [INFO] Press CTRL+C to quit
2025-10-19 19:15:28,150 [INFO] * Restarting with stat
2025-10-19 19:15:28,681 [WARNING] * Debugger is active!
2025-10-19 19:15:28,683 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:15:44,421 [ERROR] Upload error: The current Flask app is not registered with this 'SQLAlchemy' instance. Did you forget to call 'init_app', or did you create multiple 'SQLAlchemy' instances?
2025-10-19 19:15:44,422 [INFO] 127.0.0.1 - - [19/Oct/2025 19:15:44] "POST /upload?file HTTP/1.1" 400 -
2025-10-19 19:17:26,379 [INFO] * Detected change in 'C:\\Users\\jac23\\Desktop\\FileUploadFlask\\file-upload\\flask_file_upload_mvc\\app.py', reloading
2025-10-19 19:17:26,464 [INFO] * Restarting with stat
2025-10-19 19:17:27,076 [WARNING] * Debugger is active!
2025-10-19 19:17:27,078 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:17:34,140 [INFO] * Detected change in 'C:\\Users\\jac23\\Desktop\\FileUploadFlask\\file-upload\\flask_file_upload_mvc\\app.py', reloading
2025-10-19 19:17:34,236 [INFO] * Restarting with stat
2025-10-19 19:17:38,566 [INFO] WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
2025-10-19 19:17:38,566 [INFO] Press CTRL+C to quit
2025-10-19 19:17:38,567 [INFO] * Restarting with stat
2025-10-19 19:17:39,047 [WARNING] * Debugger is active!
2025-10-19 19:17:39,049 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:17:54,080 [ERROR] Upload error: The current Flask app is not registered with this 'SQLAlchemy' instance. Did you forget to call 'init_app', or did you create multiple 'SQLAlchemy' instances?
2025-10-19 19:17:54,081 [INFO] 127.0.0.1 - - [19/Oct/2025 19:17:54] "POST /upload?file HTTP/1.1" 400 -
2025-10-19 19:18:59,550 [INFO] * Detected change in 'C:\\Users\\jac23\\Desktop\\FileUploadFlask\\file-upload\\flask_file_upload_mvc\\app.py', reloading
2025-10-19 19:18:59,666 [INFO] * Restarting with stat
2025-10-19 19:19:07,180 [INFO] WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
2025-10-19 19:19:07,181 [INFO] Press CTRL+C to quit
2025-10-19 19:19:07,181 [INFO] * Restarting with stat
2025-10-19 19:19:07,770 [WARNING] * Debugger is active!
2025-10-19 19:19:07,772 [INFO] * Debugger PIN: 134-261-731
2025-10-19 19:19:26,790 [INFO] File saved: uploads/c543263cbc4e4783944f6fad9d2b2596\01f55afa347545b4b564e5be8d596494_Screenshot_2025-10-03_223338.png
2025-10-19 19:19:26,794 [INFO] 127.0.0.1 - - [19/Oct/2025 19:19:26] "POST /upload?file HTTP/1.1" 201 -
Binary file not shown.
6 changes: 6 additions & 0 deletions flask_file_upload_mvc/models/uploaded_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from extensions import db

class UploadedFile(db.Model):
id = db.Column(db.Integer, primary_key = True)
filename = db.Column(db.String(255), nullable = False)
file_path = db.Column(db.String(255), nullable = False)
Binary file added flask_file_upload_mvc/requirements.txt
Binary file not shown.
Binary file not shown.
65 changes: 65 additions & 0 deletions flask_file_upload_mvc/services/file_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import os
import uuid
from werkzeug.utils import secure_filename
from models.uploaded_file import UploadedFile
from models.uploaded_file import db
import logging

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'pdf', 'txt'}

def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def save_file(file, base_folder):
if not allowed_file(file.filename):
raise ValueError('File type not allowed')

os.makedirs(base_folder, exist_ok=True)
filename = secure_filename(file.filename)
unique_name = f"{uuid.uuid4().hex}_{filename}"
save_path = os.path.join(base_folder, unique_name)
file.save(save_path)

new_file = UploadedFile(filename=unique_name, file_path=save_path)
db.session.add(new_file)
db.session.commit()

logging.info(f"File saved: {save_path}")
return new_file

# Update service reuse the existing folder and remove the bug where after updating it gets added again in the database
def update_file(file_id, new_file, _):
existing = UploadedFile.query.get(file_id)
if not existing:
raise ValueError('File not found')

if os.path.exists(existing.file_path):
os.remove(existing.file_path)

existing_folder = os.path.dirname(existing.file_path)
os.makedirs(existing_folder, exist_ok=True)
filename = secure_filename(new_file.filename)
unique_name = f"{uuid.uuid4().hex}_{filename}"
save_path = os.path.join(existing_folder, unique_name)

new_file.save(save_path)

existing.filename = unique_name
existing.file_path = save_path
db.session.commit()

logging.info(f"File updated: ID={file_id}")
return existing


def delete_file(file_id):
file_record = UploadedFile.query.get(file_id)
if not file_record:
raise ValueError('File not found')
if os.path.exists(file_record.file_path):
os.remove(file_record.file_path)
logging.info(f"File deleted from storage: {file_record.file_path}")

db.session.delete(file_record)
db.session.commit()
logging.info(f"Record deleted: ID={file_id}")