[Type text]
1
Python Google Cloud Function with CORS
Python Google Cloud Function with CORS
© RapidValue Solutions 2
Creating Python Cloud Function
The application would require the Python Cloud function to accept the file as an input, store it in a temporary directory, parse the data
and return a JSON data.
Please find below the main.py:
import os
import tempfile
from app import processor
# Helper function that computes the filepath to save files to temp directory
def get_file_path(filename):
# instance memory is referred to as here temporary directory
file_name = secure_filename(filename)
return os.path.join(tempfile.gettempdir(), file_name)
def parser(request):
# This code will process each non-file field in the form
fields = {}
data = request.form.to_dict()
for field in data:
fields[field] = data[field]
print('Processed field: %s' % field)
# This code will process each file uploaded
files = request.files.to_dict()
Python Google Cloud Function with CORS
© RapidValue Solutions 3
f_names = []
for file_name, file in files.items():
# Note: GCF may not keep files saved locally between invocations.
# If you want to preserve the uploaded files, you should save them
# to another location (such as a Cloud Storage bucket).
f_name = get_file_path(file_name)
file.save(f_name)
f_names.append(f_name)
print('Processed file: %s' % file_name)
return_data = processor.file_processor(file_path)
# Clear temporary directory
os.remove(file_path)
return return_data
Note:
The “processor” is the custom module in which “file_processor” is a function that parses the input file and returns a JSON response.
CORS Header in Preflight Request
To handle the preflight request, it is required to handle the below code in the main function “parser”.
# Set CORS headers for preflight requests
if request.method == 'OPTIONS':
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': '*'
Python Google Cloud Function with CORS
© RapidValue Solutions 4
}
return ('', 204, headers)
So the code would be something like:
…
…
….
def parser(request):
# Set CORS headers for preflight requests
if request.method == 'OPTIONS':
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': '*'
}
return ('', 204, headers)
# This code will process each non-file field in the form
fields = {}
data = request.form.to_dict()
for field in data:
fields[field] = data[field]
print('Processed field: %s' % field)
....
....
....
# Set CORS headers for the main request
Python Google Cloud Function with CORS
© RapidValue Solutions 5
headers = {
'Access-Control-Allow-Origin': '*'
}
CORS Header in Response Data
To handle this part, we have used the flask module so as to include the header in the response object.
Now, the main.py looks like:
import os
import tempfile
import flask
from app import processor
...
...
...
def parser(request):
...
...
...
return_data = processor.file_processor(file_path)
# Clear temporary directory
os.remove(file_path)
response = flask.jsonify(return_data)
response.headers.set('Access-Control-Allow-Origin','*')
response.headers.set('Access-Control-Allow-Methods','POST')
Python Google Cloud Function with CORS
© RapidValue Solutions 6
return response
(Note: “flask” import should be added in the dependencies file - “requirements.txt”)
Thus, the CORS error in the response object would be resolved.
In a similar way, you would also be able to set the header data for 'Access-Control-Allow-Headers’ and for various methods
as well.
Authentication
If you plan to send a request with an Authorization header, you must:
1. Add the Authorization header to Access-Control-Allow-Headers.
2. Set the Access-Control-Allow-Credentials header to true.
3. Set a specific origin in Access-Control-Allow-Origin (wildcards are not accepted).
Hence, the code had changed to:
if request.method == 'OPTIONS'
# Allows POST requests from origin
# https://myapplicationsample.firebaseapp.com
# # header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': ['https://myapplicationsample.firebaseapp.com’],
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': ['Authorization','Access-Control-Allow-Origin','Access-Control-Allow-Credentials'],
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Max-Age': '3600',
'Access-Control-Expose-Headers':'true'
}
Python Google Cloud Function with CORS
© RapidValue Solutions 7
return ('', 204, headers)
# Set CORS headers for main requests
headers = {
'Access-Control-Allow-Origin': ['https://myapplicationsample.firebaseapp.com’],
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': ['Authorization','Access-Control-Allow-Origin','Access-Control-Allow-Credentials'],
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Max-Age': '3600',
'Access-Control-Expose-Headers':'true'
}
Now, my main.py looks like:
import os
import tempfile
import flask
from app import processor
...
...
...
def parser(request):
...
...
...
return_data = processor.file_processor(file_path)
# Clear temporary directory
os.remove(file_path)
response = flask.jsonify(return_data)
Python Google Cloud Function with CORS
© RapidValue Solutions 8
response.headers.set('Access-Control-Allow-Origin', 'https://myapplicationsample.firebaseapp.com')
response.headers.set('Access-Control-Allow-Methods','POST')
response.headers.set('Access-Control-Allow-Credentials','true')
return response
Conclusion
After going through the above process, one should now have a fair knowledge about how the application with multiple backend like
Node.js and Python could be deployed on the Google Cloud platform with the Node.js handling the backend firebase. A single,
standalone business logic, implemented as a Google Cloud function in Python is quite capable of handling the CORS issue while you
also receive the authentication that is provided along with that.
By,
Roopa Budda Thiagarajan
Senior Software Engineer, RapidValue
Python Google Cloud Function with CORS
© RapidValue Solutions 9
About RapidValue
RapidValue is a global leader in digital product engineering solutions including mobility, omni-
channel, IoT, AI, RPA and cloud to enterprises worldwide. RapidValue offers its digital services to the
world’s top brands, Fortune 1000 companies and innovative emerging start-ups. With offices in the
United States, the United Kingdom, Germany and India and operations spread across the Middle-
East, Europe and Canada, RapidValue delivers enterprise services and solutions across various
industry verticals.
Disclaimer:
This document contains information that is confidential and proprietary to RapidValue Solutions Inc. No part of it
may be used, circulated, quoted, or reproduced for distribution outside RapidValue. If you are not the intended
recipient of this report, you are hereby notified that the use, circulation, quoting, or reproducing of this report is
strictly prohibited and may be unlawful.
@RapidValue Solutions
www.rapidvaluesolutions.com/blogwww.rapidvaluesolutions.com
+1 877.690.4844 contactus@rapidvaluesolutions.com

Python Google Cloud Function with CORS

  • 1.
    [Type text] 1 Python GoogleCloud Function with CORS
  • 2.
    Python Google CloudFunction with CORS © RapidValue Solutions 2 Creating Python Cloud Function The application would require the Python Cloud function to accept the file as an input, store it in a temporary directory, parse the data and return a JSON data. Please find below the main.py: import os import tempfile from app import processor # Helper function that computes the filepath to save files to temp directory def get_file_path(filename): # instance memory is referred to as here temporary directory file_name = secure_filename(filename) return os.path.join(tempfile.gettempdir(), file_name) def parser(request): # This code will process each non-file field in the form fields = {} data = request.form.to_dict() for field in data: fields[field] = data[field] print('Processed field: %s' % field) # This code will process each file uploaded files = request.files.to_dict()
  • 3.
    Python Google CloudFunction with CORS © RapidValue Solutions 3 f_names = [] for file_name, file in files.items(): # Note: GCF may not keep files saved locally between invocations. # If you want to preserve the uploaded files, you should save them # to another location (such as a Cloud Storage bucket). f_name = get_file_path(file_name) file.save(f_name) f_names.append(f_name) print('Processed file: %s' % file_name) return_data = processor.file_processor(file_path) # Clear temporary directory os.remove(file_path) return return_data Note: The “processor” is the custom module in which “file_processor” is a function that parses the input file and returns a JSON response. CORS Header in Preflight Request To handle the preflight request, it is required to handle the below code in the main function “parser”. # Set CORS headers for preflight requests if request.method == 'OPTIONS': headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': '*'
  • 4.
    Python Google CloudFunction with CORS © RapidValue Solutions 4 } return ('', 204, headers) So the code would be something like: … … …. def parser(request): # Set CORS headers for preflight requests if request.method == 'OPTIONS': headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': '*' } return ('', 204, headers) # This code will process each non-file field in the form fields = {} data = request.form.to_dict() for field in data: fields[field] = data[field] print('Processed field: %s' % field) .... .... .... # Set CORS headers for the main request
  • 5.
    Python Google CloudFunction with CORS © RapidValue Solutions 5 headers = { 'Access-Control-Allow-Origin': '*' } CORS Header in Response Data To handle this part, we have used the flask module so as to include the header in the response object. Now, the main.py looks like: import os import tempfile import flask from app import processor ... ... ... def parser(request): ... ... ... return_data = processor.file_processor(file_path) # Clear temporary directory os.remove(file_path) response = flask.jsonify(return_data) response.headers.set('Access-Control-Allow-Origin','*') response.headers.set('Access-Control-Allow-Methods','POST')
  • 6.
    Python Google CloudFunction with CORS © RapidValue Solutions 6 return response (Note: “flask” import should be added in the dependencies file - “requirements.txt”) Thus, the CORS error in the response object would be resolved. In a similar way, you would also be able to set the header data for 'Access-Control-Allow-Headers’ and for various methods as well. Authentication If you plan to send a request with an Authorization header, you must: 1. Add the Authorization header to Access-Control-Allow-Headers. 2. Set the Access-Control-Allow-Credentials header to true. 3. Set a specific origin in Access-Control-Allow-Origin (wildcards are not accepted). Hence, the code had changed to: if request.method == 'OPTIONS' # Allows POST requests from origin # https://myapplicationsample.firebaseapp.com # # header and caches preflight response for an 3600s headers = { 'Access-Control-Allow-Origin': ['https://myapplicationsample.firebaseapp.com’], 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': ['Authorization','Access-Control-Allow-Origin','Access-Control-Allow-Credentials'], 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '3600', 'Access-Control-Expose-Headers':'true' }
  • 7.
    Python Google CloudFunction with CORS © RapidValue Solutions 7 return ('', 204, headers) # Set CORS headers for main requests headers = { 'Access-Control-Allow-Origin': ['https://myapplicationsample.firebaseapp.com’], 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': ['Authorization','Access-Control-Allow-Origin','Access-Control-Allow-Credentials'], 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '3600', 'Access-Control-Expose-Headers':'true' } Now, my main.py looks like: import os import tempfile import flask from app import processor ... ... ... def parser(request): ... ... ... return_data = processor.file_processor(file_path) # Clear temporary directory os.remove(file_path) response = flask.jsonify(return_data)
  • 8.
    Python Google CloudFunction with CORS © RapidValue Solutions 8 response.headers.set('Access-Control-Allow-Origin', 'https://myapplicationsample.firebaseapp.com') response.headers.set('Access-Control-Allow-Methods','POST') response.headers.set('Access-Control-Allow-Credentials','true') return response Conclusion After going through the above process, one should now have a fair knowledge about how the application with multiple backend like Node.js and Python could be deployed on the Google Cloud platform with the Node.js handling the backend firebase. A single, standalone business logic, implemented as a Google Cloud function in Python is quite capable of handling the CORS issue while you also receive the authentication that is provided along with that. By, Roopa Budda Thiagarajan Senior Software Engineer, RapidValue
  • 9.
    Python Google CloudFunction with CORS © RapidValue Solutions 9 About RapidValue RapidValue is a global leader in digital product engineering solutions including mobility, omni- channel, IoT, AI, RPA and cloud to enterprises worldwide. RapidValue offers its digital services to the world’s top brands, Fortune 1000 companies and innovative emerging start-ups. With offices in the United States, the United Kingdom, Germany and India and operations spread across the Middle- East, Europe and Canada, RapidValue delivers enterprise services and solutions across various industry verticals. Disclaimer: This document contains information that is confidential and proprietary to RapidValue Solutions Inc. No part of it may be used, circulated, quoted, or reproduced for distribution outside RapidValue. If you are not the intended recipient of this report, you are hereby notified that the use, circulation, quoting, or reproducing of this report is strictly prohibited and may be unlawful. @RapidValue Solutions www.rapidvaluesolutions.com/blogwww.rapidvaluesolutions.com +1 877.690.4844 [email protected]