2

来自https://frankie567.github.io/fastapiusers/ - 还有其他人可以使用乌龟 ORM 吗?当我收到此错误时,您能否与我分享配置:

module = importlib.import_module(module_str)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1006, in _gcd_import
File "", line 983, in _find_and_load
File "", line 967, in _find_and_load_unlocked
File "", line 677, in _load_unlocked
File "", line 728, in exec_module
File "", line 219, in _call_with_frames_removed
File "./main.py", line 4, in
from fastapi_users import FastAPIUsers, models
File "./fastapi_users.py", line 7, in
from fastapi_users import models
ImportError: cannot import name 'models' from 'fastapi_users' (./fastapi_users.py)

如果您需要提供 main.py 文件,我需要确定吗?它在 fast-api_users 目录中吗?

这是我的 main.py 文件:

资源

from fastapi import FastAPI
from fastapi_users import FastAPIUsers, models
from fastapi_users.authentication import JWTAuthentication
from fastapi_users.db import TortoiseBaseUserModel, TortoiseUserDatabase
from starlette.requests import Request
from tortoise.contrib.starlette import register_tortoise

DATABASE_URL = "sqlite://./test.db"
SECRET = "SECRET"


class User(models.BaseUser):
    pass


class UserCreate(User, models.BaseUserCreate):
    pass


class UserUpdate(User, models.BaseUserUpdate):
    pass


class UserDB(User, models.BaseUserDB):
    pass


class UserModel(TortoiseBaseUserModel):
    pass


user_db = TortoiseUserDatabase(UserDB, UserModel)
app = FastAPI()
register_tortoise(app, db_url=DATABASE_URL, modules={"models": ["WHAT DO I PUT HERE?"]})

auth_backends = [
    JWTAuthentication(secret=SECRET, lifetime_seconds=3600),
]

fastapi_users = FastAPIUsers(
    user_db, auth_backends, User, UserCreate, UserUpdate, UserDB, SECRET,
)
app.include_router(fastapi_users.router, prefix="/users", tags=["users"])


@fastapi_users.on_after_register()
def on_after_register(user: User, request: Request):
    print(f"User {user.id} has registered.")


@fastapi_users.on_after_forgot_password()
def on_after_forgot_password(user: User, token: str, request: Request):
    print(f"User {user.id} has forgot their password. Reset token: {token}")
4

1 回答 1

0

["WHAT DO I PUT HERE?"]应该是具有用户模型的模块的 python 路径。

因此,如果您的项目如下所示:

  • store/
    • users.py -> 模型在这里定义,例如
    • main.py
    • ...

您需要将其设置为["store.users"]

把它想象成如果你导入那个模块你会放什么?例如import store.users,或者如果更平坦,可能import users

请仅使用完全限定的模块名称,而不是相对名称,因为这样我们将无法找到将模型绑定到数据库的模块。

main.py使用 a作为入口点可能是个好主意,但它不应该是必需的。

另一个感兴趣的例子可能是:https ://tortoise-orm.readthedocs.io/en/latest/examples/fastapi.html

那里的模型在 a 中models.py,因为它在根中,所以modules={"models": ["models"]},.

于 2020-05-18T12:00:16.350 回答