我正在学习ChristopherGS关于FASTapi的教程,但是我被困在了第6部分上,因为我相信他的语法可能已经过时了。
当程序停止时,我得到了AttributeError: module 'jinja2' has no attribute 'contextfunction
。我怎么解决这个问题,我已经被困在这里三天了。
这是我的密码:
from fastapi.templating import Jinja2Templates
from typing import Optional, Any
from pathlib import Path
from app.schemas import RecipeSearchResults, Recipe, RecipeCreate
from app.recipe_data import RECIPES
BASE_PATH = Path(__file__).resolve().parent
TEMPLATES = Jinja2Templates(directory=str(BASE_PATH / "templates"))
app = FastAPI(title="Recipe API", openapi_url="/openapi.json")
api_router = APIRouter()
# Updated to serve a Jinja2 template
# https://www.starlette.io/templates/
# https://jinja.palletsprojects.com/en/3.0.x/templates/#synopsis
@api_router.get("/", status_code=200)
def root(request: Request) -> dict:
"""
Root GET
"""
return TEMPLATES.TemplateResponse(
"index.html",
{"request": request, "recipes": RECIPES},
)
@api_router.get("/recipe/{recipe_id}", status_code=200, response_model=Recipe)
def fetch_recipe(*, recipe_id: int) -> Any:
"""
Fetch a single recipe by ID
"""
result = [recipe for recipe in RECIPES if recipe["id"] == recipe_id]
if not result:
# the exception is raised, not returned - you will get a validation
# error otherwise.
raise HTTPException(
status_code=404, detail=f"Recipe with ID {recipe_id} not found"
)
return result[0]
if __name__ == "__main__":
# Use this for debugging purposes only
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8001, log_level="debug")
发布于 2022-10-15 11:15:29
这可能是由于jinja和starlette(fastapi)版本错配造成的。我在最新的快速对接图像(python3.9)中也遇到了类似的问题。通过安装旧版本的jinja2解决了这个问题。
如果您使用的是jinja2 >3.0.3,请尝试降级jinja2:
pip install jinja2==3.0.3
其他的选择是升级fastapi/starlette。
参考:
https://stackoverflow.com/questions/73830400
复制相似问题