Thursday, July 16, 2015

Upload image to Google Cloud Storage using App Engine [Python]

Today i will show you how you can build app engine service that can handle "POST" requests to save images to "Google Cloud Storage".

The Handler will extract image data from "post" request "base64" and create it on the Cloud Storage




1 - download cloud storage client library from here.
   - i prefer using "git bash" for download it using the following command
   "git clone https://github.com/GoogleCloudPlatform/appengine-gcs-client.git gcs-client" 


2 - goto the "cloudstorage" folder and copy the folder to your project directory. 
   - Path to the folder ==> "\gcs-client\python\src"



3 - open Console Developer and create bucket for storing images.
  


4 - Now we are ready to write some code 
  • I suppose you are familiar with app engine so i will focus on cloud storage only.
  • I'm using PyCharm as IDE. 

5 - Create new python file and name it "UploadImageToCloudStorage,py".


5 - open the file, import "webapp2 - cloudstorage - os - time" libraries and declare your "retry_params".



6 - Create UploadHandler that will handle your post request.


7 - Create "CreateImage" function that will take image name,data, extension and save it to your bucket.


8 - now we need to get the image data and extension from post request :




9 - Now we add the code in our "post method" :-
  1. define bucket variable the will hold your bucket name.
  2. generate unique name for image using "time" library.
  3. combine bucket with image name
  4. invoke "CreateImage" method.
  5. generate a link to the image
  6. respond on the request with the image url on the cloud storage.


10 - Now you are ready to deploy your project and create post request to save images to "gcs".

11 - If your app in a different domain you need to enable "CORS" on cloud storage using "gsutil" tool

i hope my post is useful for you :)


No comments:

Post a Comment