-
-
Notifications
You must be signed in to change notification settings - Fork 527
-
Hi, I am a newbee in backend developing and I am trying to implement functions to retrieve and update the images. I am using Swift UI as the frontend. I am not sure how to do that because basically all tutorials online uses post method to create a file. I try to handle the image like normal files and parameters but it does not work at least in the OpenAPI document. How to write these functions correctly?
Here are the api functions.
@survey_router.get("/retrieve-basic-info-profile-picture/{user_id}", response={200: BasicInfoProfilePictureSchema, 403: BasicInfoError})
def retrieve_basic_info_profile_picture(request, user_id: int):
return get_basic_info_with_code(user_id)
@survey_router.put("/update-basic-info-profile-picture/{user_id}", response={200: BasicInfoSuccess, 403: BasicInfoError})
def update_basic_info_profile_picture(request, user_id: int, image: UploadedFile = File(...)):
try:
basic_info = BasicInfo.objects.get(user_id=user_id)
except BasicInfo.DoesNotExist:
return 403, {"message": "Basic Info Does Not Exist."}
basic_info.profile_picture = image
basic_info.save()
return 200, {"success": True}
def get_basic_info_with_code(user_id: int):
"""
Get basic info data from database as an object and handle exceptions
:param user_id: unique int for each user
:return: a tuple with code and object or dict follow the schema of the related response,
if the schema's field is part of the model, then just return the object itself and framework will take care of the
rest, otherwise you can also return a dict match with the schema.
"""
try:
basic_info = BasicInfo.objects.get(user_id=user_id)
except BasicInfo.DoesNotExist:
return 403, {"message": "Basic Info Does Not Exist."}
return 200, basic_info
Here are the schemas and models:
class BasicInfoProfilePictureSchema(Schema):
profile_picture: str
class BasicInfo(models.Model):
# account basic info
user_id = models.IntegerField(primary_key=True)
user_name = models.TextField()
email = models.TextField()
password = models.TextField()
gender = models.TextField()
profile_picture = models.ImageField(upload_to="profile_picture/")
# student personal info
school_year = models.IntegerField()
Testing on the OpenAPI and it said "Error: Unprocessable Entity" with code 422 and the following JSON
{
"detail": [
{
"loc": [
"file",
"image"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 3 comments
-
there is a bug with the put and image, you need to use post
Beta Was this translation helpful? Give feedback.
All reactions
-
This PR aims to fix it #397
Beta Was this translation helpful? Give feedback.
All reactions
-
Beta Was this translation helpful? Give feedback.