零度冰l 2024-11-01 14:12 采纳率: 25%
浏览 13

fastapi数据库增添报错

fastapi结合tortosie-orm增加数据库内容报错

# 接口代码
@router.post("/registertest", summary="用户注册测试", response_model=ReturnNoneDataModel)
async def registertest(post: RegisterModel):
    user_id = generate_uuid()
    print(user_id)
    hashed_password = en_password(post.password)
    print(hashed_password)
    await User.create(user_id=user_id, username="18064164589", password=hashed_password)
    return ReturnNoneDataModel(code=STATUS_CODE["success"], msg="注册成功")
# 模型类
class TimestampModel(Model):
    created_time = fields.DatetimeField(auto_now_add=True, description="创建时间")
    updated_time = fields.DatetimeField(auto_now=True, description="更新时间")

    class Meta:
        abstract = True


class User(TimestampModel):
    # 本身属性
    user_id = fields.UUIDField(pk=True, description="用户编号,用户唯一标识", max_length=255)
    username = fields.CharField(description="用户的手机号码或者邮箱号码", max_length=255)
    password = fields.CharField(description="用户存储的密文密码", max_length=255)
    user_status = fields.IntField(description="用户使用状态,1为可以使用,0为被禁用", default=1)

    # 附加属性
    role = fields.ManyToManyField(model_name="models.Role", related_name="users")

    class Meta:
        table = "user"

# 工具类
def en_password(psw: str):
    password = pbkdf2_sha256.hash(psw)
    return password

#报错情况为
ERROR:    Exception in ASGI application
  + Exception Group Traceback (most recent call last):
Traceback (most recent call last):
  File "C:\fastray\fsray-api\Lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 401, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\Lib\site-packages\uvicorn\middleware\proxy_headers.py", line 60, in __call__
    return await self.app(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\Lib\site-packages\fastapi\applications.py", line 1054, in __call__
    await super().__call__(scope, receive, send)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\applications.py", line 113, in __call__
    await self.middleware_stack(scope, receive, send)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\middleware\errors.py", line 187, in __call__
    raise exc
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\middleware\errors.py", line 165, in __call__
    await self.app(scope, receive, _send)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\middleware\base.py", line 185, in __call__
    with collapse_excgroups():
  File "C:\Users\86182\AppData\Local\Programs\Python\Python311\Lib\contextlib.py", line 155, in __exit__
    self.gen.throw(typ, value, traceback)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\_utils.py", line 82, in collapse_excgroups
    raise exc
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\middleware\base.py", line 187, in __call__
    response = await self.dispatch_func(request, call_next)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\core\Middleware.py", line 24, in dispatch
    response = await call_next(request)
               ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\middleware\base.py", line 163, in call_next
    raise app_exc
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\middleware\base.py", line 149, in coro
    await self.app(scope, receive_or_disconnect, send_no_error)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\middleware\exceptions.py", line 62, in __call__
    await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app
    raise exc
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\_exception_handler.py", line 42, in wrapped_app
    await app(scope, receive, sender)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\routing.py", line 715, in __call__
    await self.middleware_stack(scope, receive, send)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\routing.py", line 735, in app
    await route.handle(scope, receive, send)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\routing.py", line 288, in handle
    await self.app(scope, receive, send)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\routing.py", line 76, in app
    await wrap_app_handling_exceptions(app, request)(scope, receive, send)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app
    raise exc
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\_exception_handler.py", line 42, in wrapped_app
    await app(scope, receive, sender)
  File "C:\fastray\fsray-api\Lib\site-packages\starlette\routing.py", line 73, in app
    response = await f(request)
               ^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\Lib\site-packages\fastapi\routing.py", line 301, in app
    raw_response = await run_endpoint_function(
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\Lib\site-packages\fastapi\routing.py", line 212, in run_endpoint_function
    return await dependant.call(**values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\api\endpoints\login.py", line 29, in registertest
    await User.create(user_id=user_id, username="18064164589", password=hashed_password)
  File "C:\fastray\fsray-api\Lib\site-packages\tortoise\models.py", line 1151, in create
    db = using_db or cls._choose_db(True)
                     ^^^^^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\Lib\site-packages\tortoise\models.py", line 1031, in _choose_db
    db = router.db_for_write(cls)
         ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\Lib\site-packages\tortoise\router.py", line 39, in db_for_write
    return self._db_route(model, "db_for_write")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\Lib\site-packages\tortoise\router.py", line 31, in _db_route
    return connections.get(self._router_func(model, action))
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\fastray\fsray-api\Lib\site-packages\tortoise\router.py", line 18, in _router_func
    for r in self._routers:
TypeError: 'NoneType' object is not iterable
  • 写回答

1条回答 默认 最新

  • 越重天 新星创作者: Java技术领域 2024-11-02 23:42
    关注

    本答案参考 多次询问 ChatGPT-3.5 后选择的最佳回答,若是满意,还请采纳,谢谢

    1. 问题分析

      • 从报错信息TypeError: 'NoneType' object is not iterable来看,问题出在Tortoise - ORM的数据库路由相关部分。具体是在_router_func方法中,它试图迭代self._routers,但self._routersNone
      • 在FastAPI与Tortoise - ORM集成时,这通常意味着数据库连接和路由配置可能存在问题。
    2. 解决方案

      • 检查数据库连接初始化

        • 确保你已经正确地初始化了Tortoise - ORM的数据库连接。通常,你需要在应用启动时配置数据库连接,例如:

          from tortoise import Tortoise
          
          async def init_db():
              await Tortoise.init(
                  db_url='your_database_url',
                  modules={'models': ['your.models.module']}
              )
              await Tortoise.generate_schemas()
          
        • 在FastAPI中,你可以在startup事件中调用init_db函数:

          from fastapi import FastAPI
          
          app = FastAPI()
          
          @app.on_event('startup')
          async def startup_event():
              await init_db()
          
      • 检查数据库路由配置(如果有自定义路由)

        • 如果你有自定义的数据库路由(例如,用于多数据库支持),确保路由配置正确。如果没有特殊需求,可以使用默认的数据库路由。
        • 例如,如果你错误地设置了数据库路由并且导致self._routersNone,你可能需要重新审视路由设置代码。
      • 确认模型模块导入正确

        • Tortoise.init函数中的modules参数中指定的模型模块路径要正确。如果模型模块无法正确加载,也可能导致与数据库交互时出现问题。
        • 确保your.models.module是正确的模块路径,其中包含了像User这样的模型类定义。
    评论

报告相同问题?

问题事件

  • 创建了问题 11月1日