forked from PDXPythonPirates/cs50w-lecture-sql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
passengers.py
40 lines (31 loc) · 1.26 KB
/
passengers.py
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
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
conn_args = {}
if 'pg8000' in os.getenv('DATABASE_URL'):
conn_args = {'ssl': True}
engine = create_engine(os.getenv("DATABASE_URL"), connect_args=conn_args)
db = scoped_session(sessionmaker(bind=engine))
def main():
# List all flights.
flights = db.execute("SELECT id, origin, destination, duration FROM flights").fetchall()
for flight in flights:
print(f"Flight {flight.id}: {flight.origin} to {flight.destination}, {flight.duration} minutes.")
# Prompt user to choose a flight.
flight_id = int(input("\nFlight ID: "))
flight = db.execute("SELECT origin, destination, duration FROM flights WHERE id = :id",
{"id": flight_id}).fetchone()
# Make sure flight is valid.
if flight is None:
print("Error: No such flight.")
return
# List passengers.
passengers = db.execute("SELECT name FROM passengers WHERE flight_id = :flight_id",
{"flight_id": flight_id}).fetchall()
print("\nPassengers:")
for passenger in passengers:
print(passenger.name)
if len(passengers) == 0:
print("No passengers.")
if __name__ == "__main__":
main()