I'm currently trying to send a POST request to my flask restful service that will generate a model to be saved to the database. This model will include a url to an image that is hosted through cloudinary along with other data like date and name
My issue is that in Postman i'm only allowed to send form-data
or raw
which will include the json. I'm able to upload to cloudinary and receive the url needed, however i'm unable to get the json from the request so i'm unable to completely generate a model to be saved.
image_json = request.get_json()
returns None
My question is if i'm only allowed to send one or the either raw or form-data
How am i supposed to get the image and the corresponding data needed to save the model?
from cloudinary.uploader import upload
from cloudinary.utils import cloudinary_url
from flask_restful import Resource
from flask import request
from models.image import ImageModel
from schemas.image import ImageSchema
image_schema = ImageSchema()
image_list_schema = ImageSchema(many=True)
class Image(Resource):
@classmethod
def post(cls):
image_to_upload = request.files["image"]
if image_to_upload:
upload_result = upload(image_to_upload)
url = cloudinary_url(upload_result['public_id'], format="jpg", crop="fill", width=100,height=100)[0]
full_size_url = cloudinary_url(upload_result['public_id'], format="jpg", crop="fill", width=200, height=100, radius=20, effect="sepia")[0]
image_json = request.get_json() # this returns None
image_json["url"] = url
image_json["full_size_url"] = full_size_url
image = image_schema.load(image_json)
try:
image.save_to_db()
except:
return {"message": "error uploading file"}
return image_schema.dump(image), 201
return {"message": "no image uploaded"}, 401
When you send a file to flask using multipart/form-data, the file will be at request.files, so, in your case, it would be
image_json = request.files['here is the key you add to the file on postman']
The other stuffs, called form-data, will be at request.form. So, to get that:
form_data = request.form
So, using postman, when you select multipartm/form-data, you will first give a name for the file, and then you will select it. The name (or key) will be the key used in the dict to get the file, as explained above. Also, for the form part, the key will work the same way