使用fastapi和jinja2从html链接文件



嗨,我试图链接到json文件从html代码使用fastapi和jinja2,但链接不工作。我想我必须告诉fastapi如何找到文件或类似的东西…我得到一个json (api)的答案,而不是文件..

{"detail":"Not Found"}
python代码:
from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory='templates')

@app.get('/data', response_class=HTMLResponse)
async def data(request: Request):
return templates.TemplateResponse('data.html', {
'request': request
})

和HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>
<title>Data</title>
</head>
<body>
<div class="ui container">
<h1>
Data downloader:
</h1>
<a href="../json/data.json" target="_blank">
Data
</a>
</div>
</body>
</html>

这段代码做到了…

python:

from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/json", StaticFiles(directory="json"), name="json")
templates = Jinja2Templates(directory='templates')

@app.get('/data', response_class=HTMLResponse)
async def data(request: Request):
return templates.TemplateResponse('data.html', {
'request': request
})

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>
<title>Data</title>
</head>
<body>
<div class="ui container">
<h1>
Data downloader:
</h1>
<a href="{{ url_for('json', path='/data.json') }}" target="_blank">
Data
</a>
</div>
</body>
</html>

所以是StaticFiles的导入和使用使得第一个代码点具有

相关内容

  • 没有找到相关文章

最新更新