|
| 1 | +import os |
| 2 | + |
| 3 | +from flask import Flask, render_template, request |
| 4 | +from sqlalchemy import create_engine |
| 5 | +from sqlalchemy.orm import scoped_session, sessionmaker |
| 6 | + |
| 7 | +app = Flask(__name__) |
| 8 | + |
| 9 | +engine = create_engine(os.getenv("DATABASE_URL")) |
| 10 | +db = scoped_session(sessionmaker(bind=engine)) |
| 11 | + |
| 12 | + |
| 13 | +@app.route("/") |
| 14 | +def index(): |
| 15 | + flights = db.execute("SELECT * FROM flights").fetchall() |
| 16 | + return render_template("index.html", flights=flights) |
| 17 | + |
| 18 | + |
| 19 | +@app.route("/book", methods=["POST"]) |
| 20 | +def book(): |
| 21 | + """Book a flight.""" |
| 22 | + |
| 23 | + # Get form information. |
| 24 | + name = request.form.get("name") |
| 25 | + try: |
| 26 | + flight_id = int(request.form.get("flight_id")) |
| 27 | + except ValueError: |
| 28 | + return render_template("error.html", message="Invalid flight number.") |
| 29 | + |
| 30 | + # Make sure flight exists. |
| 31 | + if db.execute("SELECT * FROM flights WHERE id = :id", {"id": flight_id}).rowcount == 0: |
| 32 | + return render_template("error.html", message="No such flight with that id.") |
| 33 | + db.execute("INSERT INTO passengers (name, flight_id) VALUES (:name, :flight_id)", |
| 34 | + {"name": name, "flight_id": flight_id}) |
| 35 | + db.commit() |
| 36 | + return render_template("success.html") |
| 37 | + |
| 38 | + |
| 39 | +@app.route("/flights") |
| 40 | +def flights(): |
| 41 | + """List all flights.""" |
| 42 | + flights = db.execute("SELECT * FROM flights").fetchall() |
| 43 | + return render_template("flights.html", flights=flights) |
| 44 | + |
| 45 | + |
| 46 | +@app.route("/flights/<int:flight_id>") |
| 47 | +def flight(flight_id): |
| 48 | + """List details about a single flight.""" |
| 49 | + |
| 50 | + # Make sure flight exists. |
| 51 | + flight = db.execute("SELECT * FROM flights WHERE id = :id", {"id": flight_id}).fetchone() |
| 52 | + if flight is None: |
| 53 | + return render_template("error.html", message="No such flight.") |
| 54 | + |
| 55 | + # Get all passengers. |
| 56 | + passengers = db.execute("SELECT name FROM passengers WHERE flight_id = :flight_id", |
| 57 | + {"flight_id": flight_id}).fetchall() |
| 58 | + return render_template("flight.html", flight=flight, passengers=passengers) |
0 commit comments