SlideShare a Scribd company logo
[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

More Related Content

What's hot (20)

Oracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web Services
Kim Berg Hansen
 
Resource-Oriented Web Services
Resource-Oriented Web Services
Bradley Holt
 
Hive data migration (export/import)
Hive data migration (export/import)
Bopyo Hong
 
Asyncio
Asyncio
Andrew Svetlov
 
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
it-people
 
An Introduction to Solr
An Introduction to Solr
tomhill
 
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
I Goo Lee
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
Hadoop 20111215
Hadoop 20111215
exsuns
 
nginx mod PSGI
nginx mod PSGI
Yaroslav Korshak
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Introducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
What's new in PHP 5.5
What's new in PHP 5.5
Tom Corrigan
 
Refactoring terraform
Refactoring terraform
Nell Shamrell-Harrington
 
Python at Facebook
Python at Facebook
Angelo Failla
 
All Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istio
Lin Sun
 
Terraform Introduction
Terraform Introduction
soniasnowfrog
 
InfiniFlux collector
InfiniFlux collector
InfiniFlux
 
OWASP Proxy
OWASP Proxy
Security B-Sides
 
Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013
Mohan Arumugam
 
Oracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web Services
Kim Berg Hansen
 
Resource-Oriented Web Services
Resource-Oriented Web Services
Bradley Holt
 
Hive data migration (export/import)
Hive data migration (export/import)
Bopyo Hong
 
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
it-people
 
An Introduction to Solr
An Introduction to Solr
tomhill
 
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
I Goo Lee
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
Hadoop 20111215
Hadoop 20111215
exsuns
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
Introducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
What's new in PHP 5.5
What's new in PHP 5.5
Tom Corrigan
 
All Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istio
Lin Sun
 
Terraform Introduction
Terraform Introduction
soniasnowfrog
 
InfiniFlux collector
InfiniFlux collector
InfiniFlux
 
Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013
Mohan Arumugam
 

Similar to Python Google Cloud Function with CORS (20)

Cross site calls with javascript - the right way with CORS
Cross site calls with javascript - the right way with CORS
Michael Neale
 
Cors michael
Cors michael
Michael Neale
 
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
PROIDEA
 
CORS and (in)security
CORS and (in)security
n|u - The Open Security Community
 
Cross Origin Resource Sharing (CORS) - Azizul Hakim
Cross Origin Resource Sharing (CORS) - Azizul Hakim
Cefalo
 
Of CORS thats a thing how CORS in the cloud still kills security
Of CORS thats a thing how CORS in the cloud still kills security
John Varghese
 
Conquering CORS. Taming Cross-Origin Resource Sharing.
Conquering CORS. Taming Cross-Origin Resource Sharing.
Tony Nazarov
 
PyFoursquare: Python Library for Foursquare
PyFoursquare: Python Library for Foursquare
Marcel Caraciolo
 
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
bejdajzaher
 
Flask patterns
Flask patterns
it-people
 
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
mahadekurg
 
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
hosleadamsfy
 
Web Dev 21-01-2024.pptx
Web Dev 21-01-2024.pptx
PARDHIVANNABATTULA
 
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
Thomas Witt
 
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
rawenkatesa4
 
Get Distributed and Cloud Computing 1st Edition Hwang Solutions Manual free a...
Get Distributed and Cloud Computing 1st Edition Hwang Solutions Manual free a...
tansichaniu6
 
Go Serverless with Cloud Functions and Python
Go Serverless with Cloud Functions and Python
mfazal
 
Restful App Engine
Restful App Engine
Ryan Morlok
 
Google app-engine-with-python
Google app-engine-with-python
Deepak Garg
 
Cross-domain requests with CORS
Cross-domain requests with CORS
Vladimir Dzhuvinov
 
Cross site calls with javascript - the right way with CORS
Cross site calls with javascript - the right way with CORS
Michael Neale
 
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
CONFidence 2014: Kiss, Zagon, Sseller: Scaling security
PROIDEA
 
Cross Origin Resource Sharing (CORS) - Azizul Hakim
Cross Origin Resource Sharing (CORS) - Azizul Hakim
Cefalo
 
Of CORS thats a thing how CORS in the cloud still kills security
Of CORS thats a thing how CORS in the cloud still kills security
John Varghese
 
Conquering CORS. Taming Cross-Origin Resource Sharing.
Conquering CORS. Taming Cross-Origin Resource Sharing.
Tony Nazarov
 
PyFoursquare: Python Library for Foursquare
PyFoursquare: Python Library for Foursquare
Marcel Caraciolo
 
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
bejdajzaher
 
Flask patterns
Flask patterns
it-people
 
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
mahadekurg
 
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
hosleadamsfy
 
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
JavaScript Security: Mastering Cross Domain Communications in complex JS appl...
Thomas Witt
 
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
Distributed and Cloud Computing 1st Edition Hwang Solutions Manual
rawenkatesa4
 
Get Distributed and Cloud Computing 1st Edition Hwang Solutions Manual free a...
Get Distributed and Cloud Computing 1st Edition Hwang Solutions Manual free a...
tansichaniu6
 
Go Serverless with Cloud Functions and Python
Go Serverless with Cloud Functions and Python
mfazal
 
Restful App Engine
Restful App Engine
Ryan Morlok
 
Google app-engine-with-python
Google app-engine-with-python
Deepak Garg
 
Cross-domain requests with CORS
Cross-domain requests with CORS
Vladimir Dzhuvinov
 
Ad

More from RapidValue (20)

How to Build a Micro-Application using Single-Spa
How to Build a Micro-Application using Single-Spa
RapidValue
 
Play with Jenkins Pipeline
Play with Jenkins Pipeline
RapidValue
 
Accessibility Testing using Axe
Accessibility Testing using Axe
RapidValue
 
Guide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in Kotlin
RapidValue
 
Automation in Digital Cloud Labs
Automation in Digital Cloud Labs
RapidValue
 
Microservices Architecture - Top Trends & Key Business Benefits
Microservices Architecture - Top Trends & Key Business Benefits
RapidValue
 
Uploading Data Using Oracle Web ADI
Uploading Data Using Oracle Web ADI
RapidValue
 
Appium Automation with Kotlin
Appium Automation with Kotlin
RapidValue
 
Build UI of the Future with React 360
Build UI of the Future with React 360
RapidValue
 
Real-time Automation Result in Slack Channel
Real-time Automation Result in Slack Channel
RapidValue
 
Automation Testing with KATALON Cucumber BDD
Automation Testing with KATALON Cucumber BDD
RapidValue
 
How to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular Framework
RapidValue
 
Video Recording of Selenium Automation Flows
Video Recording of Selenium Automation Flows
RapidValue
 
JMeter JMX Script Creation via BlazeMeter
JMeter JMX Script Creation via BlazeMeter
RapidValue
 
Migration to Extent Report 4
Migration to Extent Report 4
RapidValue
 
The Definitive Guide to Implementing Shift Left Testing in QA
The Definitive Guide to Implementing Shift Left Testing in QA
RapidValue
 
Data Seeding via Parameterized API Requests
Data Seeding via Parameterized API Requests
RapidValue
 
Test Case Creation in Katalon Studio
Test Case Creation in Katalon Studio
RapidValue
 
How to Perform Memory Leak Test Using Valgrind
How to Perform Memory Leak Test Using Valgrind
RapidValue
 
DevOps Continuous Integration & Delivery - A Whitepaper by RapidValue
DevOps Continuous Integration & Delivery - A Whitepaper by RapidValue
RapidValue
 
How to Build a Micro-Application using Single-Spa
How to Build a Micro-Application using Single-Spa
RapidValue
 
Play with Jenkins Pipeline
Play with Jenkins Pipeline
RapidValue
 
Accessibility Testing using Axe
Accessibility Testing using Axe
RapidValue
 
Guide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in Kotlin
RapidValue
 
Automation in Digital Cloud Labs
Automation in Digital Cloud Labs
RapidValue
 
Microservices Architecture - Top Trends & Key Business Benefits
Microservices Architecture - Top Trends & Key Business Benefits
RapidValue
 
Uploading Data Using Oracle Web ADI
Uploading Data Using Oracle Web ADI
RapidValue
 
Appium Automation with Kotlin
Appium Automation with Kotlin
RapidValue
 
Build UI of the Future with React 360
Build UI of the Future with React 360
RapidValue
 
Real-time Automation Result in Slack Channel
Real-time Automation Result in Slack Channel
RapidValue
 
Automation Testing with KATALON Cucumber BDD
Automation Testing with KATALON Cucumber BDD
RapidValue
 
How to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular Framework
RapidValue
 
Video Recording of Selenium Automation Flows
Video Recording of Selenium Automation Flows
RapidValue
 
JMeter JMX Script Creation via BlazeMeter
JMeter JMX Script Creation via BlazeMeter
RapidValue
 
Migration to Extent Report 4
Migration to Extent Report 4
RapidValue
 
The Definitive Guide to Implementing Shift Left Testing in QA
The Definitive Guide to Implementing Shift Left Testing in QA
RapidValue
 
Data Seeding via Parameterized API Requests
Data Seeding via Parameterized API Requests
RapidValue
 
Test Case Creation in Katalon Studio
Test Case Creation in Katalon Studio
RapidValue
 
How to Perform Memory Leak Test Using Valgrind
How to Perform Memory Leak Test Using Valgrind
RapidValue
 
DevOps Continuous Integration & Delivery - A Whitepaper by RapidValue
DevOps Continuous Integration & Delivery - A Whitepaper by RapidValue
RapidValue
 
Ad

Recently uploaded (20)

Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Analysis of the changes in the attitude of the news comments caused by knowin...
Analysis of the changes in the attitude of the news comments caused by knowin...
Matsushita Laboratory
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
June Patch Tuesday
June Patch Tuesday
Ivanti
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Analysis of the changes in the attitude of the news comments caused by knowin...
Analysis of the changes in the attitude of the news comments caused by knowin...
Matsushita Laboratory
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 

Python Google Cloud Function with CORS

  • 1. [Type text] 1 Python Google Cloud Function with CORS
  • 2. 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()
  • 3. 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': '*'
  • 4. 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
  • 5. 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')
  • 6. 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' }
  • 7. 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)
  • 8. 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
  • 9. 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 [email protected]