Reputation: 163
I hope everyone are safe and fine. I am trying this code to make it work. I have a main.py file and models.py file where I have a Class User created in the models.py file and I am trying to import the User class from models.py file to main.py file. I a using Tortoise ORM for this purpose. I am getting an error "ImportError: cannot import name 'register_tortoise' from 'tortoise.contrib.pydantic'" in the command prompt
**main.py**
from fastapi import FastAPI, Request, Form, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from models import User_Pydantic, UserIn_Pydantic, User
from tortoise.contrib.pydantic import register_tortoise, HTTPNotFoundError
app = FastAPI()
register_tortoise(
app,
db_url="sqlite://store.db",
modules={'models':['models']},
generate_schemas = True,
add_exception_handlers = True
)
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def login_page(request :Request):
return templates.TemplateResponse("index.html", {"request":request})
@app.post("/loginsuccess/", response_class=HTMLResponse)
async def login_success(request: Request, username: str = Form(...), password: str = Form(...)):
if username=='michael' and password=='clarke':
return templates.TemplateResponse("homepage.html", {"request": request, "username":username})
else:
status_code:int
status_code = 500
return templates.TemplateResponse("index.html", {"request":request, "status_code":status_code})
**models.py**
from tortoise import fields
from tortoise.models import Model
from tortoise.contrib.pydantic import pydantic_model_creator
class User(Model):
id = fields.CharField(pk=True, max_length=50)
username = fields.CharField(max_length=50, unique=True)
password = fields.CharField(max_length=50, null=True)
class PydanticMeta:
pass
User_Pydantic = pydantic_model_creator(User, name="User")
UserIn_Pydantic = pydantic_model_creator(User, name="UserIn", exclude_readonly=True)
Upvotes: 1
Views: 2931
Reputation: 267
The library's API was changed, so you'll need to import the register_tortoise
function from tortoise.contrib.fastapi
instead. e.g:
from tortoise.contrib.fastapi import HTTPNotFoundError, register_tortoise
Upvotes: 1
Reputation: 1
Try this command, it works. https://coffeebytes.dev/en/python-tortoise-orm-integration-with-fastapi/#installation-of-the-python-tortoise-orm
pip install tortoise-orm
Upvotes: 0