from flask import Flask, render_template, request, redirect, url_for, flash from flask_pymongo import PyMongo from werkzeug.utils import secure_filename import os app = Flask(__name__) app.config["MONGO_URI"] = "mongodb://localhost:27017/mapPinsDB" app.config['UPLOAD_FOLDER'] = 'uploads' app.config['SECRET_KEY'] = 'supersecretkey' app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg', 'gif'} mongo = PyMongo(app) from flask_wtf import FlaskForm from wtforms import StringField, FileField, SubmitField from wtforms.validators import DataRequired class PinForm(FlaskForm): description = StringField('Description', validators=[DataRequired()]) photo = FileField('Photo', validators=[DataRequired()]) submit = SubmitField('Add Pin') def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS'] @app.route('/') def index(): pins = mongo.db.pins.find() return render_template('index.html', pins=pins) @app.route('/add_pin', methods=['GET', 'POST']) def add_pin(): form = PinForm() if form.validate_on_submit(): description = form.description.data photo = form.photo.data if photo and allowed_file(photo.filename): try: filename = secure_filename(photo.filename) filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) photo.save(filepath) pin = { 'description': description, 'photo': filepath, 'lat': request.form['lat'], 'lng': request.form['lng'] } mongo.db.pins.insert_one(pin) return redirect(url_for('index')) except Exception as e: flash(f'An error occurred: {e}') return redirect(url_for('add_pin')) else: flash('Invalid file type. Only images are allowed.') return render_template('add_pin.html', form=form) if __name__ == '__main__': app.run(debug=True)