-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.py
More file actions
77 lines (59 loc) · 2.09 KB
/
application.py
File metadata and controls
77 lines (59 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from flask import Flask, render_template, jsonify, request
from models import *
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
@app.route("/")
def index():
flights = Flight.query.all()
return render_template("index.html", flights=flights)
@app.route("/book", methods=["POST"])
def book():
"""Book a flight."""
# Get form information.
name = request.form.get("name")
try:
flight_id = int(request.form.get("flight_id"))
except ValueError:
return render_template("error.html", message="Invalid flight number.")
# Make sure the flight exists.
flight = Flight.query.get(flight_id)
if not flight:
return render_template("error.html", message="No such flight with that id.")
# Add passenger.
flight.add_passenger(name)
return render_template("success.html")
@app.route("/flights")
def flights():
"""List all flights."""
flights = Flight.query.all()
return render_template("flights.html", flights=flights)
@app.route("/flights/<int:flight_id>")
def flight(flight_id):
"""List details about a single flight."""
# Make sure flight exists.
flight = Flight.query.get(flight_id)
if flight is None:
return render_template("error.html", message="No such flight.")
# Get all passengers.
passengers = flight.passengers
return render_template("flight.html", flight=flight, passengers=passengers)
@app.route("/api/flights/<int:flight_id>")
def flight_api(flight_id):
"""Return details about a single flight."""
# Make sure flight exists.
flight = Flight.query.get(flight_id)
if flight is None:
return jsonify({"error": "Invalid flight_id"}), 422
# Get all passengers.
passengers = flight.passengers
names = []
for passenger in passengers:
names.append(passenger.name)
return jsonify({
"origin": flight.origin,
"destination": flight.destination,
"duration": flight.duration,
"passengers": names
})