FastAPI静态文件映射到网页

本文介绍了如何使用FastAPI和Uvicorn创建一个简单的Web应用,包括文件目录的静态文件映射和提供API接口来访问和读取文件。通过示例展示了如何在终端启动服务和通过路由访问文件内容。
摘要由CSDN通过智能技术生成

安装了FastAPI 和 Uvicorn:pip install fastapi uvicorn

然后运行代码

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

# 假设 dir_upload 为 "/Users/yourusername/yourprojectpath/files/"
dir_upload = "/Users/xiaokkk/Desktop/abragent_v1/files"

# 将文件目录映射为静态文件路径
app.mount("/files", StaticFiles(directory=dir_upload), name="files")

# 示例路由,演示访问文件
@app.get("/")
async def read_root():
    return {"message": "你可以在 /files 下访问文件"}

# 示例路由,读取文件内容
@app.get("/read-file/{file_path:path}")
async def read_file(file_path: str):
    # 组合完整文件路径
    full_path = f"{dir_upload}/{file_path}"

    try:
        # 读取并返回文件内容
        with open(full_path, "r") as file:
            file_content = file.read()
        return {"file_content": file_content}
    except FileNotFoundError:
        return {"detail": "文件未找到"}

接下来,在终端运行以下命令启动 FastAPI:

uvicorn main:app --reload

然后,打开浏览器访问 http://127.0.0.1:8000/files/example.txt,应该能够看到 example.txt 文件的内容。同样,你可以根据实际情况修改路径和路由。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值