How to update file in CRUD operation using FastApi and MongoDb?

大城市里の小女人 提交于 2021-02-11 12:40:41

问题


For CRUD operation with profile image upload, first I create a pyndantic model in models.py as :

For adding a new student

class StudentSchema(BaseModel):
    fullname:str = Field(...)
    email: EmailStr = Field(...)
    course_of_study: str = Field(...)
    year: int = Field(...,gt=0,lt=9)
    gpa: float = Field(..., le= 4.0)
    image: Optional[str]

And for updating in models.py

class UpdateStudentModel(BaseModel):
    fullname: Optional[str]
    email: Optional[EmailStr]
    course_of_study : Optional[str]
    year : Optional[int]
    gpa: Optional[float]
    image: Optional[str]

In routes.py endpoints are defined as:

@router.post("/",response_description="Student data added into the database")
async def add_student_data(student: StudentSchema= Depends(),file: UploadFile=File(None)):
    print(file)
    if file is not None:
        _, ext = os.path.splitext(file.filename)
        IMG_DIR = os.path.join('CRUD_FASTAPI', 'static/')
        if not os.path.exists(IMG_DIR):
            os.makedirs(IMG_DIR)
        content = await file.read()  
        

        if file.content_type not in ['image/jpeg', 'image/png']:
            raise HTTPException(status_code=406, detail="Only .jpeg or .png  files allowed")
             
        file_name= f'{uuid.uuid4().hex}{ext}'  
        file_location=IMG_DIR+file_name      
        async with aiofiles.open(file_location, "wb") as f:
            
            await f.write(content)
        
        student.image=file_name            


        path_on_cloud="images/"+file_name
        path_local=file_location
        storage.child(path_on_cloud).put(path_local)  
      
  
    student=jsonable_encoder(student)
    new_student=await add_student(student)
    return ResponseModel(new_student,"Student added successfully")

When the new data is provided, it is successfully added whether profile image is provided or not. I got error in updating section . Endpoint for update:

@router.put("/{id}")
async def update_student_data(id:str,req:UpdateStudentModel=Depends(),file:UploadFile=File(None)):
    req={k:v for k ,v in req.dict().items() if v is not None}

When I try to update data but not profile image then it throws an error.

And in terminal

When I provide file, it does not throw error. How can I update for the case not providing profile image during update? The update section with profile image should work as below: Add/replace image if I provide file during update No any action on profile image if I didnot provide file during update

来源:https://stackoverflow.com/questions/64474061/how-to-update-file-in-crud-operation-using-fastapi-and-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!