繁体   English   中英

FastAPI NameError:未定义名称“请求”

[英]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

非常感谢您抽出宝贵的时间

您需要导入请求 class。

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

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

from fastapi import FastAPI, Request

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM