FastAPI系列:如何响应txt和json文件
这篇简洁实用的文章向您展示了如何在FastAPI中返回TXT或JSON文件。我假设你已经对web框架有了一定的了解,所以我不会浪费你的时间来解释什么是FastAPI,它是如何工作的,或者漫谈它的历史。让我们直入主题吧。
返回TXT文件
TXT文件是一种纯文本文件,不包含图像或其他非文本字符1。它可以通过任何文本编辑器打开和编辑,例如Notepad或TextEdit。TXT文件通常用于存储人类可读的数据,如笔记、指令、日志或其他基于文本的信息。
在FastAPI中,您可以通过使用PlainTextResponse返回TXT文件,它将内容类型头设置为text/plain。
例子:
# main.py
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse
app = FastAPI()
# returns a TXT file with your dynamic data
@app.get("/welcome.txt")
async def get_txt():
text = "Welcome to Sling Academy."
return PlainTextResponse(text)
# returns a TXT file from disk
@app.get("/static_data.txt")
async def get_txt_file():
file_name = "data.txt"
# Assume that the file is in the root directory of the project.
file_path = f"./{file_name}"
file = open(file_path, "r")
return PlainTextResponse(file.read())
现在启动fastapi服务:
uvicorn main:app --reload
然后登录http://localhost:8000/welcome.txt 和 http://localhost:8000/static_data.txt。为了使后面的路由工作,不要忘记在项目的根目录中创建一个名为data.txt的纯文本文件。
返回JSON文件
下面的URL指向一个JSON文件,该文件由Sling Academy的公共API(使用FastAPI构建)返回:
https://api.slingacademy.com/v1/sample-data/files/customers.json
你可以在这个页面上看到用FastAPI做的其他有趣的东西。现在,让我们关注这个问题:如何返回JSON文件?答案取决于你的需要:
-
如果你想提供动态JSON数据(从数据库中获取或动态创建),使用
JSONResponse
,它会自动将你的数据转换为JSON并设置适当的内容类型头。 -
如果你想从磁盘返回JSON文件,使用
FileResponse
。
下面是代码示例:
# main.py
from fastapi import FastAPI
from fastapi.responses import JSONResponse, FileResponse
app = FastAPI()
# Return a JSON response with the data
# You can fetch data from a database or create it dynamically
@app.get("/hello.json")
async def get_hello():
data = {
"hello": "world",
"foo": "bar",
"sling": "academy"
}
return JSONResponse(data)
# Return a JSON response with a JSON file from disk
@app.get("/data.json")
async def get_data():
filename = "data.json"
# assume the file is in the root directory of the project
file_path = f"./{filename}"
return FileResponse(filename)
添加名为data的JSON文件。将json放到项目的根目录中(只要json语法有效,文件的内容并不重要)。启动API,然后访问http://localhost:8000/hello.json 和 http://localhost:8000/data.json。