FastAPI NameError: name 'Request' is not defined

FastAPI NameError: name 'Request' is not defined

我正在松散地关注构建全栈交易应用程序的教程,并尝试 运行 使用 FastAPI 和 uvicorn 编写此脚本。我真的找不到我的错误,也不知道我在做什么,所以非常感谢您的帮助。

代码:

import sqlite3, config
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.get("/")
def index(request: Request):
    connection = sqlite3.connect(config.DB_FILE)
    connection.row_factory = sqlite3.Row
    cursor = connection.cursor()

    cursor.execute("""
        SELECT id, symbol, name FROM stock order by symbol
    """)

    rows = cursor.fetchall()

    return templates.TemplateResponse("index.html", {"request": request, "stocks": rows})

@app.get("/stock/{symbol}")
def index(request: Request, symbol):
    connection = sqlite3.connect(config.DB_FILE)
    connection.row_factory = sqlite3.Row
    cursor = connection.cursor()

    cursor.execute("""
        SELECT id, symbol, name FROM stock WHERE symbol = ?
    """, (symbol,))

    row = cursor.fetchall()

    return templates.TemplateResponse("stock_detail.html", {"request": request, "stock": row})

错误

line 9, in <module>
    def index(request: Request):
NameError: name 'Request' is not defined

非常感谢您抽出宝贵时间

您需要导入 Request。替换你的第一行:

from fastapi import FastAPI, Request

您需要导入请求 class。

请将第 2 行更改为:from fastapi import FastAPI, Request