SlideShare ist ein Scribd-Unternehmen logo
1 von 9
Downloaden Sie, um offline zu lesen
[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

Weitere ähnliche Inhalte

Was ist angesagt?

Oracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web ServicesOracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web ServicesKim Berg Hansen
 
Resource-Oriented Web Services
Resource-Oriented Web ServicesResource-Oriented Web Services
Resource-Oriented Web ServicesBradley Holt
 
Hive data migration (export/import)
Hive data migration (export/import)Hive data migration (export/import)
Hive data migration (export/import)Bopyo Hong
 
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014it-people
 
An Introduction to Solr
An Introduction to SolrAn Introduction to Solr
An Introduction to Solrtomhill
 
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)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 PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQLPeter Eisentraut
 
Hadoop 20111215
Hadoop 20111215Hadoop 20111215
Hadoop 20111215exsuns
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5Tom Corrigan
 
All Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istioAll Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istioLin Sun
 
Terraform Introduction
Terraform IntroductionTerraform Introduction
Terraform Introductionsoniasnowfrog
 
InfiniFlux collector
InfiniFlux collectorInfiniFlux collector
InfiniFlux collectorInfiniFlux
 
Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Mohan Arumugam
 

Was ist angesagt? (20)

Oracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web ServicesOracle database - Get external data via HTTP, FTP and Web Services
Oracle database - Get external data via HTTP, FTP and Web Services
 
Resource-Oriented Web Services
Resource-Oriented Web ServicesResource-Oriented Web Services
Resource-Oriented Web Services
 
Hive data migration (export/import)
Hive data migration (export/import)Hive data migration (export/import)
Hive data migration (export/import)
 
Asyncio
AsyncioAsyncio
Asyncio
 
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014Пишем для asyncio - Андрей Светлов, PyCon RU 2014
Пишем для asyncio - Андрей Светлов, PyCon RU 2014
 
An Introduction to Solr
An Introduction to SolrAn Introduction to Solr
An Introduction to Solr
 
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
Hadoop 20111215
Hadoop 20111215Hadoop 20111215
Hadoop 20111215
 
nginx mod PSGI
nginx mod PSGInginx mod PSGI
nginx mod PSGI
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5
 
Refactoring terraform
Refactoring terraformRefactoring terraform
Refactoring terraform
 
Python at Facebook
Python at FacebookPython at Facebook
Python at Facebook
 
All Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istioAll Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istio
 
Terraform Introduction
Terraform IntroductionTerraform Introduction
Terraform Introduction
 
InfiniFlux collector
InfiniFlux collectorInfiniFlux collector
InfiniFlux collector
 
OWASP Proxy
OWASP ProxyOWASP Proxy
OWASP Proxy
 
Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013Power Shell and Sharepoint 2013
Power Shell and Sharepoint 2013
 

Ähnlich wie Python Google Cloud Function with CORS

What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11Henry Schreiner
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code LabColin Su
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4JoeDinaso
 
NodeJs
NodeJsNodeJs
NodeJsdizabl
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 
Scaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachScaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachJinal Jhaveri
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScriptQiangning Hong
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flaskJeetendra singh
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk PemulaOon Arfiandwi
 
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...Databricks
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBMongoDB
 
Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots DeepAnshu Sharma
 
Dpilot - Source Code with Snapshots
Dpilot - Source Code with SnapshotsDpilot - Source Code with Snapshots
Dpilot - Source Code with SnapshotsKritika Phulli
 
Source Code for Dpilot
Source Code for Dpilot Source Code for Dpilot
Source Code for Dpilot Nidhi Chauhan
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4DEVCON
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimizationxiaojueqq12345
 

Ähnlich wie Python Google Cloud Function with CORS (20)

What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4
 
NodeJs
NodeJsNodeJs
NodeJs
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
Scaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approachScaling python webapps from 0 to 50 million users - A top-down approach
Scaling python webapps from 0 to 50 million users - A top-down approach
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
Crawler 2
Crawler 2Crawler 2
Crawler 2
 
Frontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and HowFrontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and How
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
From HelloWorld to Configurable and Reusable Apache Spark Applications in Sca...
 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
 
Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots
 
Dpilot - Source Code with Snapshots
Dpilot - Source Code with SnapshotsDpilot - Source Code with Snapshots
Dpilot - Source Code with Snapshots
 
Source Code for Dpilot
Source Code for Dpilot Source Code for Dpilot
Source Code for Dpilot
 
Hadoop
HadoopHadoop
Hadoop
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
 

Mehr von RapidValue

How to Build a Micro-Application using Single-Spa
How to Build a Micro-Application using Single-SpaHow to Build a Micro-Application using Single-Spa
How to Build a Micro-Application using Single-SpaRapidValue
 
Play with Jenkins Pipeline
Play with Jenkins PipelinePlay with Jenkins Pipeline
Play with Jenkins PipelineRapidValue
 
Accessibility Testing using Axe
Accessibility Testing using AxeAccessibility Testing using Axe
Accessibility Testing using AxeRapidValue
 
Guide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in KotlinGuide to Generate Extent Report in Kotlin
Guide to Generate Extent Report in KotlinRapidValue
 
Automation in Digital Cloud Labs
Automation in Digital Cloud LabsAutomation in Digital Cloud Labs
Automation in Digital Cloud LabsRapidValue
 
Microservices Architecture - Top Trends & Key Business Benefits
Microservices Architecture -  Top Trends & Key Business BenefitsMicroservices Architecture -  Top Trends & Key Business Benefits
Microservices Architecture - Top Trends & Key Business BenefitsRapidValue
 
Uploading Data Using Oracle Web ADI
Uploading Data Using Oracle Web ADIUploading Data Using Oracle Web ADI
Uploading Data Using Oracle Web ADIRapidValue
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with KotlinRapidValue
 
Build UI of the Future with React 360
Build UI of the Future with React 360Build UI of the Future with React 360
Build UI of the Future with React 360RapidValue
 
Real-time Automation Result in Slack Channel
Real-time Automation Result in Slack ChannelReal-time Automation Result in Slack Channel
Real-time Automation Result in Slack ChannelRapidValue
 
Automation Testing with KATALON Cucumber BDD
Automation Testing with KATALON Cucumber BDDAutomation Testing with KATALON Cucumber BDD
Automation Testing with KATALON Cucumber BDDRapidValue
 
How to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular FrameworkHow to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular FrameworkRapidValue
 
Video Recording of Selenium Automation Flows
Video Recording of Selenium Automation FlowsVideo Recording of Selenium Automation Flows
Video Recording of Selenium Automation FlowsRapidValue
 
JMeter JMX Script Creation via BlazeMeter
JMeter JMX Script Creation via BlazeMeterJMeter JMX Script Creation via BlazeMeter
JMeter JMX Script Creation via BlazeMeterRapidValue
 
Migration to Extent Report 4
Migration to Extent Report 4Migration to Extent Report 4
Migration to Extent Report 4RapidValue
 
The Definitive Guide to Implementing Shift Left Testing in QA
The Definitive Guide to Implementing Shift Left Testing in QAThe Definitive Guide to Implementing Shift Left Testing in QA
The Definitive Guide to Implementing Shift Left Testing in QARapidValue
 
Data Seeding via Parameterized API Requests
Data Seeding via Parameterized API RequestsData Seeding via Parameterized API Requests
Data Seeding via Parameterized API RequestsRapidValue
 
Test Case Creation in Katalon Studio
Test Case Creation in Katalon StudioTest Case Creation in Katalon Studio
Test Case Creation in Katalon StudioRapidValue
 
How to Perform Memory Leak Test Using Valgrind
How to Perform Memory Leak Test Using ValgrindHow to Perform Memory Leak Test Using Valgrind
How to Perform Memory Leak Test Using ValgrindRapidValue
 
DevOps Continuous Integration & Delivery - A Whitepaper by RapidValue
DevOps Continuous Integration & Delivery - A Whitepaper by RapidValueDevOps Continuous Integration & Delivery - A Whitepaper by RapidValue
DevOps Continuous Integration & Delivery - A Whitepaper by RapidValueRapidValue
 

Mehr von RapidValue (20)

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

Kürzlich hochgeladen

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Kürzlich hochgeladen (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

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 contactus@rapidvaluesolutions.com