Ⅰ. はじめに
タイトルの通り「PythonでFastAPIを利用してHTMLページを公開する方法」です。
Ⅱ. サンプルプログラム
web.py
# pip install jinja2 import uvicorn from fastapi import FastAPI, Request from fastapi.responses import RedirectResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from starlette.templating import _TemplateResponse app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) # app.mount('/static', StaticFiles(directory='static'), name='static') templates = Jinja2Templates(directory='templates') @app.get('/') async def getTopPage(request: Request) -> _TemplateResponse: return templates.TemplateResponse('index.html', {'request': request, 'title': 'トップページ'}) @app.get('/item/{id}') async def getItemDetail(request: Request, id: str) -> _TemplateResponse: return templates.TemplateResponse('item_detail.html', {'request': request, 'title': 'アイテム詳細', 'id': id}) # @app.get('/redirect') # async def redirect() -> RedirectResponse: # return RedirectResponse('https://example.com', status_code=302, headers=None, background=None) if __name__ == '__main__': uvicorn.run('web:app', host='127.0.0.1', port=8000, log_level='info', reload=True)
templates/base.html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% <link href="{{ url_for('static', path='/style.css') }}" rel="stylesheet"> %} <title>{{title}}</title> </head> <body> {% block main %} {% endblock %} </body> </html>
templates/index.html
{% extends 'base.html' %} {% block main %} <a href="/item/1">アイテムID1 詳細ページ</a> {% endblock %}
templates/item_detail.html
{% extends 'base.html' %} {% block main %} <span>アイテムID: {{ id }}</span> {% endblock %}
実行結果