from flask import Flask, render_template, request, redirect, url_for from pymongo import MongoClient from bson.objectid import ObjectId import os from datetime import datetime import pytz from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Connect to MongoDB using a secure environment variable MONGO_URI = os.getenv('MONGO_URI') app = Flask(__name__) client = MongoClient(MONGO_URI) # Select the database and collection db = client.todo_database todos_collection = db.aiml_todos @app.route('/', methods=['GET', 'POST']) def index(): todos = list(todos_collection.find(sort=[('_id', -1)])) # Fetch all todos sorted by newest first # send total count of todos to the template total_todos = len(todos) return render_template('index.html', todos=todos, total_todos=total_todos) @app.route('/add', methods=['POST']) def add(): task = request.form.get('task') image = request.files.get('image') ist = pytz.timezone("Asia/Kolkata") task_time = datetime.now(ist).strftime("%d-%m-%Y %I:%M %p") image_filename = None # Create uploads folder if not exists upload_folder = os.path.join('static', 'uploads') os.makedirs(upload_folder, exist_ok=True) # Save uploaded image if image and image.filename != '': # Secure filename filename = image.filename # Optional unique filename timestamp = datetime.now().strftime('%Y%m%d%H%M%S') filename = f"{timestamp}_{filename}" file_path = os.path.join(upload_folder, filename) image.save(file_path) image_filename = filename # Insert into MongoDB if task: todos_collection.insert_one({ 'task': task, 'task_time': task_time, 'image': image_filename }) return redirect(url_for('index')) @app.route('/delete/') def delete(id): todos_collection.delete_one({'_id': ObjectId(id)}) return redirect(url_for('index')) @app.route('/update/', methods=['GET', 'POST']) def update(id): todo = todos_collection.find_one({ '_id': ObjectId(id) }) if request.method == 'POST': new_task = request.form.get('new_task') current_time = datetime.now(pytz.utc) ist = pytz.timezone('Asia/Kolkata') task_time = current_time.astimezone(ist) if new_task: todos_collection.update_one( {'_id': ObjectId(id)}, { '$set': { 'task': new_task, 'task_time': task_time } } ) # Redirect after successful update return redirect(url_for('index')) return render_template( 'update.html', todo=todo ) if __name__ == '__main__': # Hugging Face Spaces requires apps to run on port 7860 app.run(host='0.0.0.0', port=7860, debug=False)