feat(web基础): 新增零基础Web开发课程
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
"""第5-3课标准示例:根据业务结果生成HTTP响应。"""
|
||||
|
||||
from http import HTTPStatus
|
||||
|
||||
|
||||
BOOKS = {1: "Python入门", 2: "数据库实践"}
|
||||
|
||||
|
||||
def find_book(book_id: int) -> dict:
|
||||
"""查询图书,并用状态码明确表达查询结果。"""
|
||||
|
||||
title = BOOKS.get(book_id)
|
||||
if title is None:
|
||||
return {
|
||||
"status": HTTPStatus.NOT_FOUND,
|
||||
"headers": {"Content-Type": "application/json; charset=utf-8"},
|
||||
"body": {"message": "图书不存在"},
|
||||
}
|
||||
return {
|
||||
"status": HTTPStatus.OK,
|
||||
"headers": {"Content-Type": "application/json; charset=utf-8"},
|
||||
"body": {"id": book_id, "title": title},
|
||||
}
|
||||
|
||||
|
||||
def print_response(response: dict) -> None:
|
||||
"""输出响应状态行、响应头和响应体。"""
|
||||
|
||||
status = response["status"]
|
||||
print(f"HTTP/1.1 {status.value} {status.phrase}")
|
||||
print(f"Content-Type: {response['headers']['Content-Type']}")
|
||||
print(f"响应体:{response['body']}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""分别展示查询成功与资源不存在的响应。"""
|
||||
|
||||
print_response(find_book(1))
|
||||
print("---")
|
||||
print_response(find_book(99))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user