main.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from flask import Flask, render_template, url_for, redirect
  2. from flask_bootstrap import Bootstrap
  3. import csv
  4. from addform import CafeForm
  5. app = Flask(__name__)
  6. app.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'
  7. Bootstrap(app)
  8. # all Flask routes below
  9. @app.route("/")
  10. def home():
  11. return render_template("index.html")
  12. @app.route('/add', methods=['GET', 'POST'])
  13. def add():
  14. form = CafeForm()
  15. if form.validate_on_submit():
  16. print(form.data)
  17. with open('cafe-data.csv', 'a') as csv_file:
  18. csv_file.write(f"\n{form.cafe.data},"
  19. f"{form.location.data},"
  20. f"{form.open.data},"
  21. f"{form.close.data},"
  22. f"{form.coffee_rating.data},"
  23. f"{form.wifi_rating.data},"
  24. f"{form.power_rating.data}")
  25. return redirect(url_for('cafes'))
  26. # Exercise:
  27. # Make the form write a new row into cafe-data.csv
  28. # with if form.validate_on_submit()
  29. return render_template('add.html', form=form)
  30. @app.route('/cafes')
  31. def cafes():
  32. with open('cafe-data.csv', newline='') as csv_file:
  33. csv_data = csv.reader(csv_file, delimiter=',')
  34. list_of_rows = []
  35. for row in csv_data:
  36. list_of_rows.append(row)
  37. return render_template('cafes.html', cafes=list_of_rows)
  38. if __name__ == '__main__':
  39. app.run(debug=True)