Google Cloud Storage + Python Flask - File Upload, Download, List, and Delete Example
Here’s an example of how to use Google Cloud Storage with Python Flask for file upload, download, list, and delete operations. You’ll need to install the
google-cloud-storage
library and set up your Google Cloud project with the necessary credentials.Prerequisites:
Install the required packages:
Set up your Google Cloud project and service account credentials. Download the JSON credentials file and set the
GOOGLE_APPLICATION_CREDENTIALS
environment variable to the path of the file:
Flask Application with Google Cloud Storage Integration
Explanation:
Upload File (
/upload
):- Accepts a file via a
POST
request. It checks if the file is present and then uploads it to the specified Google Cloud Storage bucket.
- Accepts a file via a
Download File (
/download/<filename>
):- Accepts a
GET
request to download a file from Google Cloud Storage. The file is temporarily downloaded to the server and sent back as an attachment.
- Accepts a
List Files (
/list
):- Accepts a
GET
request to list all the files in the Google Cloud Storage bucket.
- Accepts a
Delete File (
/delete/<filename>
):- Accepts a
DELETE
request to delete a specific file from Google Cloud Storage.
- Accepts a
Testing:
You can test the application using tools like Postman or cURL.
Upload File:
Download File:
List Files:
Delete File:
Make sure to replace 'your-bucket-name'
with your actual Google Cloud Storage bucket name.