Home > Net >  "str" object has no attricute 'c' error in fastapi while implimenting sqlalchemy
"str" object has no attricute 'c' error in fastapi while implimenting sqlalchemy

Time:06-09

I am learning fastapi from freecoding camp i ranup to a problem please helpme with this im stuck and been tailing this for 3 days


this is my file structure

App
|_ database.py
|_ main.py
|_ models.py
|_ init.py


This is my file

from fastapi.params import Body
from pydantic import BaseModel
from random import randrange
import psycopg2
from psycopg2.extras import RealDictCursor
import time
from sqlalchemy.orm import Session
from database import Base
import models
from database import engine,SessionLocal
# from requests import Response
app = FastAPI()

models.Base.metadata.create_all(bind=engine)


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

class postparam(BaseModel):
    title: str
    content:str
    Published: bool =True
    
while True:
    try:
        conn = psycopg2.connect(host= 'localhost',database='FastApi',user='postgres',password='2580',cursor_factory=RealDictCursor)
        cursor = conn.cursor()
        print('Database connection Established!!')
        break
    except Exception as error:
        print("connection to database failed !!")
        print('Error: ',error)
        time.sleep(2)

    

@app.get("/sql")
async def root(db:Session =Depends(get_db)):
    return {"message":"this is a sample fastapi"}

this is how my file looks like

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "postgresql://postgres:2580@localhost/Fastpi"  #use os.join from local variable
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

this is how my looks like

# from tokenize import String
from sqlalchemy import Column,Integer,String,Boolean
from sqlalchemy.sql.expression import null
from database import Base


class Post(Base):
    __table__ = 'posts'
    id = Column(Integer,primary_key= True,nullable=False)
    name = Column(String,nullable =False)
    content = Column(String,nullable = False)
    published = Column(Boolean,default= False)


Error showing in my powershell

This is my output Screen

CodePudding user response:

this is my full output


The output console was shrinked this contains much definition

CodePudding user response:

In your Post model you're overriding __table__ - this is an internal value used by SQLAlchemy.

You're looking for __tablename__:

class Post(Base):
    __tablename__ = 'posts'

    id = Column(Integer,primary_key= True,nullable=False)
    name = Column(String,nullable =False)
    content = Column(String,nullable = False)
    published = Column(Boolean,default= False)
  • Related