AviC
AviC

Reputation: 414

Fastapi - Copy data with sqlalchamy to couchbase

Webserver - fastapi

the sqlahcmay ORM model name--> CustomerModel, where the pydantic schema --> SchemaCustomerBase

The document being fetch correctly see line :

customer = get_customer(db, customer_no=customer_no)

so all good by ORM side , the thing is i want to copy it to couchbase , the type of "customer" object is:

print(type(customer))
<class 'mig.schema.CustomerModel'>

the return of "customer" done by response_model=SchemaCustomerBase, Which indeed return it as valid Json so document is valid json.

I tried several way to convert customer as Json (i.e json.dumps(customer) ) so i could copy it couchbase but it didn't work.

code:

def get_customer(db: Session, customer_no: int):
    return db.query(CustomerModel).filter(CustomerModel.customer_no == customer_no).first()


@mig_router.post("/cb_customer/{customer_no}",response_model=SchemaCustomerBase)
def move_customer(customer_no: int , db: Session = Depends(get_db)):
    customer = get_customer(db, customer_no=customer_no)
    bucket: Bucket = cluster.bucket("customer")
    try:
       key = customer["customer_type"] + "_" + str(customer["customer_no"])
#here it failed
       result = bucket.upsert(key, customer)
       print(result.cas)
    except Exception as e:
       print(e)
    
    return customer

error:

'CustomerModel' object is not subscriptable

I missing something here , I know i can encode to json but I could use the pydantic model as happend in respone_modle (as it actually work), how can i use also before injecting the document to couchbase?

Upvotes: 1

Views: 379

Answers (1)

AviC
AviC

Reputation: 414

solution:

In case u have sqlalchamy and u need to use the pydantic model, u should add to the pydantic class:

    class Config:
        orm_mode = True

And in code:

    customer_db = get_customer(db, customer_no=customer_no)
    customer_orm = SchemaCustomerBase.from_orm(customer)

Upvotes: 1

Related Questions