|
| 1 | +from flask import Flask, render_template |
| 2 | +from flask_bootstrap import Bootstrap |
| 3 | +from flask_wtf import FlaskForm |
| 4 | +from wtforms import StringField, SubmitField,SelectField,URLField |
| 5 | +from wtforms.validators import DataRequired,URL |
| 6 | +import csv |
| 7 | + |
| 8 | + |
| 9 | +app = Flask(__name__) |
| 10 | +app.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b' |
| 11 | +Bootstrap(app) |
| 12 | + |
| 13 | + |
| 14 | +class CafeForm(FlaskForm): |
| 15 | + cafe = StringField('Cafe name', validators=[DataRequired()]) |
| 16 | + location = URLField('Cafe Location On Google Map', validators=[URL(require_tld=True, message="Not A Valid URL")]) |
| 17 | + opening = StringField('Opening Time', validators=[DataRequired()]) |
| 18 | + closing = StringField('Closing Time', validators=[DataRequired()]) |
| 19 | + coffe_rating = SelectField('Coffee Rating', choices=['☕','☕☕','☕☕☕','☕☕☕☕','☕☕☕☕☕'],validators=[DataRequired()]) |
| 20 | + wifi_rating = SelectField('Wifi Strength', choices=['💪', '💪💪', '💪💪💪', '💪💪💪💪', '💪💪💪💪💪'], validators=[DataRequired()]) |
| 21 | + power = SelectField('Power Socket Availability', choices=['🔌','🔌🔌','🔌🔌🔌','🔌🔌🔌🔌','🔌🔌🔌🔌🔌'],validators=[DataRequired()]) |
| 22 | + submit = SubmitField('Submit') |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | +# all Flask routes below |
| 28 | +@app.route("/") |
| 29 | +def home(): |
| 30 | + return render_template("index.html") |
| 31 | + |
| 32 | + |
| 33 | +@app.route('/add',methods=["GET","POST"]) |
| 34 | +def add_cafe(): |
| 35 | + form = CafeForm() |
| 36 | + if form.validate_on_submit(): |
| 37 | + with open('cafe-data.csv',mode='a') as file: |
| 38 | + file.write('\n') |
| 39 | + for key in form.data : |
| 40 | + if key=='csrf_token' or key=="submit": |
| 41 | + continue |
| 42 | + file.write(f"{form.data[key]},") |
| 43 | + return cafes() |
| 44 | + # Exercise: |
| 45 | + # Make the form write a new row into cafe-data.csv |
| 46 | + # with if form.validate_on_submit() |
| 47 | + return render_template('add.html', form=form) |
| 48 | + |
| 49 | + |
| 50 | +@app.route('/cafes') |
| 51 | +def cafes(): |
| 52 | + with open('cafe-data.csv', newline='') as csv_file: |
| 53 | + csv_data = csv.reader(csv_file, delimiter=',') |
| 54 | + list_of_rows = [] |
| 55 | + for row in csv_data: |
| 56 | + list_of_rows.append(row) |
| 57 | + return render_template('cafes.html', cafes=list_of_rows) |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + app.run(debug=True,port=8081) |
0 commit comments