Cloudinary & Flask
Sign up for an account and copy your Cloudinary URL and paste it into a .env
file.

Keep Your Secrets Secret
Keep your CLOUDINARY_URL
, session secrets, and other API Keys secret. Add .env
to your .gitignore
. You don't want to push your env file to GitHub or anyone can take your API keys and use your accounts.
Dependencies
To use Cloudinary in your Flask app, you need to install two packages:
pip install python-dotenv cloudinary
Uploading Images
To let your user upload images to your Flask app, you need an <input type="file" />
and the proper encoding type for the form: enctype=multipart/form-data
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<button type="submit">Upload Image</button>
</form>
To get the image from the form in Flask use request.files
NOT request.form
:
image = request.files.get('image')
To upload the image to Cloudinary, first import the cloudinary uploader:
import cloudinary.uploader
Then after you get the image from the form, upload it to Cloudinary and get its url:
image = request.files.get('image')
uploaded_image = cloudinary.uploader.upload(image)
image_url = uploaded_image['url']
Cloudinary image urls look like this: https://res.cloudinary.com/dlgwpetvg/image/upload/v1678065074/g9cpesuzdqyn4hkawjcv.jpg
. Store this url in your database tables.
cur.execute(
'INSERT INTO something (image_url) VALUES (%s)',
[image_url]
)
Fancier Cloudinary Usage
If you want to use Cloudinary's transformations on your images, store the image's public_id
:
image = request.files.get('image')
uploaded_image = cloudinary.uploader.upload(image)
public_id = uploaded_image['public_id']
#...
cur.execute(
'INSERT INTO something (image_public_id) VALUES (%s)',
[public_id]
)
Then transform the image before rendering your template:
from cloudinary import CloudinaryImage
#...
# Transforms the image and returns a <img> tag
image_tag = CloudinaryImage(thingie['public_id']).image(transformation=[
{'aspect_ratio': '1.0', 'width': 150, 'crop': 'fill'},
{'radius': 'max'}
])
# => <img src="http://res.cloudinary.com/dlgwpetvg/image/upload/c_crop,g_face,h_400,w_400/r_max/c_scale,w_200/u3d7lud5oeaz5fkbbbvg"/>
# Transforms the image and returns a url
image_url = CloudinaryImage(thingie['public_id']).build_url(
width = 150, aspect_ratio = '1.0', crop = 'fill', radius = 'max'
)
# => http://res.cloudinary.com/dlgwpetvg/image/upload/ar_1.0,c_fill,r_max,w_150/u3d7lud5oeaz5fkbbbvg
return render_template('something.html', image_url=image_url)
Links
Last updated
Was this helpful?