首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在尝试构建模板时使用Jinja2时出现上下文函数错误

在尝试构建模板时使用Jinja2时出现上下文函数错误
EN

Stack Overflow用户
提问于 2022-09-23 16:07:01
回答 1查看 180关注 0票数 0

我正在学习ChristopherGS关于FASTapi的教程,但是我被困在了第6部分上,因为我相信他的语法可能已经过时了。

当程序停止时,我得到了AttributeError: module 'jinja2' has no attribute 'contextfunction。我怎么解决这个问题,我已经被困在这里三天了。

这是我的密码:

代码语言:javascript
运行
复制
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")
EN

回答 1

Stack Overflow用户

发布于 2022-10-15 11:15:29

这可能是由于jinja和starlette(fastapi)版本错配造成的。我在最新的快速对接图像(python3.9)中也遇到了类似的问题。通过安装旧版本的jinja2解决了这个问题。

如果您使用的是jinja2 >3.0.3,请尝试降级jinja2:

代码语言:javascript
运行
复制
pip install jinja2==3.0.3

其他的选择是升级fastapi/starlette。

参考:

  1. FastAPI Jinja2Templates -运行初始化模板时出错?
  2. https://github.com/pallets/jinja/blob/1b714c7e82c73575d1dba48f560db07fe9a5cb74/CHANGES.rst#version-310
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73830400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档