问题
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