OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Fast API SQL Post Request receiving 500 Error Internal Server Error

  • Thread starter Thread starter Avik Samanta
  • Start date Start date
A

Avik Samanta

Guest
I'm using Fast API and SQL Alchemy trying to make a post request to my "Player" table in my Postgres SQL Database. However, my player table raises the following error: (https://i.sstatic.net/0k9ulaYC.png)

500: Internal Server Error: Object of type AttributeError is not JSON serializable

Which confuses me, as my Questions and Choices table work perfectly well without any issues. I tried to create another similar table but keep receiving the same issues, could someone please help?

This is my models.py:

Code:
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from database import Base


class Players(Base):
    __tablename__ = "players"

    id = Column(Integer, primary_key=True)
    user_name = Column(String, index=True)
    # hashed_password = Column(String)
    # is_active = Column(Boolean, default=True)

    # items = relationship("Item", back_populates="owner")

class Questions(Base):
    __tablename__ = 'questions'
    #id (Eg: 69420)
    #question = Have u seen my scrunchie?
    id = Column(Integer, primary_key=True, index=True)
    question_text = Column(String, index=True)
    # answer = Column(String)

class Choices(Base):
    __tablename__ = 'choices'

    # id
    #choices: A: yes, B: No
    #is_correct: True/False
    #question_id: foreign key to questions table 
    id = Column(Integer, primary_key=True, index=True)
    choice_text = Column(String, index=True)
    #column with answer either True/False
    is_correct = Column(Boolean, default=False)
    #Links back to question (Eg: 69420)
    question_id = Column(Integer, ForeignKey("questions.id"))

    


# class User(Base):
#     __tablename__ = "users"

#     id = Column(Integer, primary_key=True, index=True)

And here is my main.py

Code:
from fastapi import FastAPI, HTTPException, Depends, Request
from pydantic import BaseModel
from typing import List, Annotated

from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse

import models, crud, schemas
from database import engine, SessionLocal
from sqlalchemy.orm import Session

from starlette.exceptions import HTTPException
from fastapi.exceptions import RequestValidationError
from exception_handlers import request_validation_exception_handler, http_exception_handler, unhandled_exception_handler
from middleware import log_request_middleware

app = FastAPI()

app.middleware("http")(log_request_middleware)
app.add_exception_handler(RequestValidationError, request_validation_exception_handler)
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(Exception, unhandled_exception_handler)

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

class PlayerBase(BaseModel):
    user_name: str
#Model rep the choice user makes and whether its True/False
class ChoiceBase(BaseModel):
    choice_text: str
    is_correct: bool

#Model rep the possible choices a user can make A, B, C, D
class QuestionBase(BaseModel):
    question_text: str
    choices: List[ChoiceBase]
    

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

db_dependency = Annotated[Session, Depends(get_db)]

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return PlainTextResponse(str(exc), status_code=400)

@app.post("/players")
async def create_player(user: PlayerBase, db: db_dependency):
    try:
        db_player = models.Player(user_name=user.user_name)
        db.add(db_player)
        db.commit()
        db.refresh(db_player)
    except Exception as e:
        print(e)
        raise HTTPException(status_code=404, detail=e)
        
# @app.get("/users/", response_model=list[schemas.User])
# def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
#     users = crud.get_users(db, skip=skip, limit=limit)
#     return users

@app.post("/questions")
async def create_questions(question: QuestionBase, db: db_dependency):
    db_question = models.Questions(question_text=question.question_text)
    print("This works for some stupid reason")
    db.add(db_question)
    db.commit()
    #Refresh
    db.refresh(db_question)
    for choice in question.choices:
        #quick filter for db choice, look into model. choices
        db_choice = models.Choices(choice_text=choice.choice_text, is_correct=choice.is_correct, question_id=db_question.id)
        db.add(db_choice)
    db.commit()

@app.get("/questions/{questions_id}")
async def read_question(question_id: int, db: db_dependency):
    result = db.query(models.Questions).filter(models.Questions.id == question_id).first()
    if not result:
        raise HTTPException(status_code=404, detail='Question is not found')
    return result

@app.get("/choices/{question_id}")
async def read_choices(question_id: int, db: db_dependency):
    result = db.query(models.Choices).filter(models.Choices.question_id == question_id).all()
    if not result:
        raise HTTPException(status_code=404, detail='Choices is not found')
    return result

I've tried error handling techniques to narrow down the problem and searching other forums, I havent been able to find a similar issue or solution
<p>I'm using Fast API and SQL Alchemy trying to make a post request to my "Player" table in my Postgres SQL Database. However, my player table raises the following error:
(<a href="https://i.sstatic.net/0k9ulaYC.png" rel="nofollow noreferrer">https://i.sstatic.net/0k9ulaYC.png</a>)</p>
<p>500: Internal Server Error: Object of type AttributeError is not JSON serializable</p>
<p>Which confuses me, as my <strong>Questions</strong> and <strong>Choices</strong> table work perfectly well without any issues. I tried to create another similar table but keep receiving the same issues, could someone please help?</p>
<p>This is my models.py:</p>
<pre><code>from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from database import Base


class Players(Base):
__tablename__ = "players"

id = Column(Integer, primary_key=True)
user_name = Column(String, index=True)
# hashed_password = Column(String)
# is_active = Column(Boolean, default=True)

# items = relationship("Item", back_populates="owner")

class Questions(Base):
__tablename__ = 'questions'
#id (Eg: 69420)
#question = Have u seen my scrunchie?
id = Column(Integer, primary_key=True, index=True)
question_text = Column(String, index=True)
# answer = Column(String)

class Choices(Base):
__tablename__ = 'choices'

# id
#choices: A: yes, B: No
#is_correct: True/False
#question_id: foreign key to questions table
id = Column(Integer, primary_key=True, index=True)
choice_text = Column(String, index=True)
#column with answer either True/False
is_correct = Column(Boolean, default=False)
#Links back to question (Eg: 69420)
question_id = Column(Integer, ForeignKey("questions.id"))




# class User(Base):
# __tablename__ = "users"

# id = Column(Integer, primary_key=True, index=True)
</code></pre>
<p>And here is my <strong>main.py</strong></p>
<pre><code>from fastapi import FastAPI, HTTPException, Depends, Request
from pydantic import BaseModel
from typing import List, Annotated

from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse

import models, crud, schemas
from database import engine, SessionLocal
from sqlalchemy.orm import Session

from starlette.exceptions import HTTPException
from fastapi.exceptions import RequestValidationError
from exception_handlers import request_validation_exception_handler, http_exception_handler, unhandled_exception_handler
from middleware import log_request_middleware

app = FastAPI()

app.middleware("http")(log_request_middleware)
app.add_exception_handler(RequestValidationError, request_validation_exception_handler)
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(Exception, unhandled_exception_handler)

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

class PlayerBase(BaseModel):
user_name: str
#Model rep the choice user makes and whether its True/False
class ChoiceBase(BaseModel):
choice_text: str
is_correct: bool

#Model rep the possible choices a user can make A, B, C, D
class QuestionBase(BaseModel):
question_text: str
choices: List[ChoiceBase]


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

db_dependency = Annotated[Session, Depends(get_db)]

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
return PlainTextResponse(str(exc), status_code=400)

@app.post("/players")
async def create_player(user: PlayerBase, db: db_dependency):
try:
db_player = models.Player(user_name=user.user_name)
db.add(db_player)
db.commit()
db.refresh(db_player)
except Exception as e:
print(e)
raise HTTPException(status_code=404, detail=e)

# @app.get("/users/", response_model=list[schemas.User])
# def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
# users = crud.get_users(db, skip=skip, limit=limit)
# return users

@app.post("/questions")
async def create_questions(question: QuestionBase, db: db_dependency):
db_question = models.Questions(question_text=question.question_text)
print("This works for some stupid reason")
db.add(db_question)
db.commit()
#Refresh
db.refresh(db_question)
for choice in question.choices:
#quick filter for db choice, look into model. choices
db_choice = models.Choices(choice_text=choice.choice_text, is_correct=choice.is_correct, question_id=db_question.id)
db.add(db_choice)
db.commit()

@app.get("/questions/{questions_id}")
async def read_question(question_id: int, db: db_dependency):
result = db.query(models.Questions).filter(models.Questions.id == question_id).first()
if not result:
raise HTTPException(status_code=404, detail='Question is not found')
return result

@app.get("/choices/{question_id}")
async def read_choices(question_id: int, db: db_dependency):
result = db.query(models.Choices).filter(models.Choices.question_id == question_id).all()
if not result:
raise HTTPException(status_code=404, detail='Choices is not found')
return result
</code></pre>
<p>I've tried error handling techniques to narrow down the problem and searching other forums, I havent been able to find a similar issue or solution</p>
 

Latest posts

A
Replies
0
Views
1
Ashrik Ahamed
A
A
Replies
0
Views
1
Ashrik Ahamed
A

Online statistics

Members online
1
Guests online
3
Total visitors
4
Top