1
0
forked from orson/bachemap
bachemap/app.py
2024-08-21 13:38:01 -06:00

79 lines
2.9 KiB
Python

from flask import Flask, render_template, request, redirect, url_for, flash, send_from_directory
from flask_pymongo import PyMongo
from werkzeug.utils import secure_filename
from datetime import datetime
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)
#form = PinForm()
from flask_wtf import FlaskForm
from wtforms import StringField, FileField, SubmitField, DateTimeField, SelectField
from wtforms.validators import DataRequired
class PinForm(FlaskForm):
description = StringField('Description', validators=[DataRequired()])
photo = FileField('Evidencia fotogénica', validators=[DataRequired()])
timedate = DateTimeField(default=datetime.now())
typeofpin = SelectField('Tipo de cosa', choices=['bache', 'coladera', 'obra sin terminar', 'escombro', 'robo-asalto'])
submit = SubmitField('Agregar')
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
form = PinForm()
pins = mongo.db.pins.find()
return render_template('index.html', pins=pins, form=form)
else:
#@app.route('/add_pin')
#def add_pin():
form = request.form
# if form.validate_on_submit():
#description = form.description.data
try:
photo = request.files["photo"]
except Exception as e:
print(e)
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,
'time': datetime.now(),
'photo': filepath,
'lat': request.form['lat'],
'lng': request.form['lng'],
'typeofpin': request.form['typeofpin'],
}
mongo.db.pins.insert_one(pin)
flash('¡Gracias por tu aportación!')
return redirect(url_for('index'))
else:
return allowed_file(photo.filename), 404
#render_template('index.html', pins=pins, form=form)
#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('index.html', form=form)
@app.route('/uploads/<name>')
def download_file(name):
return send_from_directory(app.config["UPLOAD_FOLDER"], name)
if __name__ == '__main__':
app.run(debug=True)