我正在尝试提供 package_docs 目录中的静态文件。当我在浏览器中打开时:
http://127.0.0.1:8001/packages/docs/index.html,页面正在运行。
但是我想打开页面:http : //127.0.0.1 : 8001/packages/docs/
没有源文件。输出是 404 Not Found
app.mount("/packages/docs",
StaticFiles(directory=pkg_resources.resource_filename(__name__, 'package_docs')
),
name="package_docs")
@app.get("/packages/docs/.*", include_in_schema=False)
def root():
return HTMLResponse(pkg_resources.resource_string(__name__, "package_docs/index.html"))
app.include_router(static.router)
app.include_router(jamcam.router, prefix="/api/v1/cams", tags=["jamcam"])
Run Code Online (Sandbox Code Playgroud)
如何更改我的代码?任何建议都会有所帮助。先感谢您。
我想使用 FastAPI 为我的 React 前端提供服务。目标是用户对 Javascript 的依赖为零。用户只需下载 Python 代码、启动服务器并在本地主机上查看网站即可。
\n我的文件夹结构是:
\n- my-fullstack-app\n - frontend/\n - build/\n - public/\n - ...\n - package.json\n - backend/\n - main.py\n - static/\nRun Code Online (Sandbox Code Playgroud)\n我跑去npm run build生成frontend/build/以下内容的文件夹:
build/\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 asset-manifest.json\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 favicon.ico\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 index.html\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 logo192.png\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 logo512.png\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 manifest.json\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 robots.txt\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 static\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 css\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.073c9b0a.css\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.073c9b0a.css.map\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 js\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 787.cda612ba.chunk.js\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 787.cda612ba.chunk.js.map\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.af955102.js\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.af955102.js.LICENSE.txt\n \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.af955102.js.map\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 media\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 logo.6ce24c58023cc2f8fd88fe9d219db6c6.svg\nRun Code Online (Sandbox Code Playgroud)\nfrontend/build/我把里面的文件夹内容复制了 …
这是一个简单的静态 FastAPI 应用程序。通过此设置,即使根路径预计返回 a FileResponse,custom.html应用程序仍会返回index.html。如何让根路径工作并渲染custom.html?
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
app = FastAPI()
app.mount(
"/",
StaticFiles(directory="static", html=True),
name="static",
)
@app.get("/")
async def index() -> FileResponse:
return FileResponse("custom.html", media_type="html")
Run Code Online (Sandbox Code Playgroud) fastapi ×3
python ×2
static-files ×2
fileresponse ×1
python-3.x ×1
reactjs ×1
routes ×1
starlette ×1