尝试使用
curl -X GET -i localhost:5000/person/66c09925-589a-43b6-9a5d-d1601cf53287
卷曲此端点时
实施效果很好:
HTTP/1.1 200 OK
Server: Werkzeug/3.0.3 Python/3.12.3
Date: Fri, 28 Jun 2024 13:19:49 GMT
Content-Type: application/json
Content-Length: 294
Connection: close
{
"address": "637 Carey Pass",
"avatar": "http://dummyimage.com/174x100.png/ff4444/ffffff",
"city": "Gainesville",
"country": "United States",
"first_name": "Lilla",
"graduation_year": 1985,
"id": "66c09925-589a-43b6-9a5d-d1601cf53287",
"last_name": "Aupol",
"zip": "32627"
}
但是当我故意发出错误的请求时,服务器会返回 HTML 格式的错误而不是 JSON 格式的错误,就像我尝试在
/person
端点上实现
HTTP/1.1 404 NOT FOUND
Server: Werkzeug/3.0.3 Python/3.12.3
Date: Fri, 28 Jun 2024 13:02:53 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 207
Connection: close
<!doctype html>
<html lang=en>
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
我想回来
{"error_message":"person not found"}, 404
这是我在 server.py 中的端点,带有硬编码列表
from flask import Flask, make_response, request
app = Flask(__name__)
data = [
{
"id": "66c09925-589a-43b6-9a5d-d1601cf53287",
"first_name": "Lilla",
"last_name": "Aupol",
"graduation_year": 1985,
"address": "637 Carey Pass",
"city": "Gainesville",
"zip": "32627",
"country": "United States",
"avatar": "http://dummyimage.com/174x100.png/ff4444/ffffff",
}
]
@app.route("/person/<var_name>")
def find_by_uuid(var_name):
for person in data:
if person["id"] == str(var_name):
return person
else:
return {"error_message":"person not found"}, 404
我尝试使用
type:name
语法只允许调用者传入有效的 UUID。
像这样:
@app.route("/person/<type:var_name>")
以下是server.py的完整代码:
你的
for
循环实际上并没有循环你的 data
,因为你总是在第一次迭代中返回。将 return {"error_message: ..."}, 404
放在循环后面应该可以使其工作。