Build a basic Flask app.
This is a basic Python HTTP server to track flight tickets and their prices. Your interviewer will explain the question to you; this README just contains usage hints.
The main libraries used in this server are Flask, an HTTP web framework, and psycopg2, a PostgreSQL client.
Getting started:
- Start the database with:
bin/start_db.sh - In a separate window, install dependencies, run migrations, and start the server:
source bin/install_deps.sh./migrate.py./app.py
- The server starts by default on
localhost:8080. - To test further changes, you can use:
curl localhost:8080/flights/1 - Finally, you can get a PostgreSQL shell with:
bin/attach_db.sh
Migrations are run via the yoyo package. You can add new migrations in the migrations directory with a number.name.sql filename, and you can run migrations with the ./migrate.py command.
Implement a basic Flask app with:
- A ping endpoint that returns a JSON object with
message: pong. - A single flight endpoint at
/flights/<int:id>. - Fetch the flight object from the database using
flights.getFlight(db, id). - If an exception occurs, log it and return a 500 response.
- If the flight is not found, return a 404 response with a JSON message.
- If found, return the flight data as JSON.
- Start the app by listening on the configured server port.
这道题是一个基础的 Flask 后端实现题,核心是把数据库中的航班信息通过 HTTP 接口暴露出来。题目通常要求实现两个接口:一个健康检查的 ping 接口,返回 pong;另一个是带参数的单航班查询接口 /flights/<int:id>,需要调用现有的数据访问函数从 PostgreSQL 中取出对应航班。如果查询过程中发生异常,要返回 500;如果航班不存在,则返回 404;如果成功找到,就把航班对象序列化成 JSON 返回。解题重点在于 Flask 路由、异常处理、HTTP 状态码以及数据库结果的 JSON 返回。