Skip to content

Commit 39b9f19

Browse files
committed
refactoring preflight and cors
1 parent afb4369 commit 39b9f19

File tree

2 files changed

+30
-13
lines changed

2 files changed

+30
-13
lines changed

functions/adoption/libs/network.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
"""
3+
Network
4+
5+
Handles formatting responses to match the tuple pattern required by
6+
the flask/GCP wrapper for Cloud Functions.
7+
"""
8+
9+
PREFLIGHT_HEADERS = {
10+
"Access-Control-Allow-Origin": "*",
11+
"Access-Control-Allow-Methods": "GET",
12+
"Access-Control-Allow-Headers": "Content-Type",
13+
"Access-Control-Max-Age": "3600",
14+
}
15+
16+
HEADERS = {"Access-Control-Allow-Origin": "*", "Content-Type": "application/json"}
17+
18+
def respond_cors():
19+
"""
20+
To be used to return OPTIONS responses to satisfy CORS preflight requests.
21+
"""
22+
return ("", 204, PREFLIGHT_HEADERS)
23+
24+
def respond(data, status=200):
25+
"""
26+
To be used to return responses to satisfy CORS requests.
27+
"""
28+
return (data, status, HEADERS)

functions/adoption/main.py

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,13 @@
22
from .libs.validator import Validator
33
from .libs.utils import output
44
from .libs.queries import list_data
5+
from .libs.network import respond_cors, respond
56

67
@functions_framework.http
78
def dispatcher(request):
8-
# For more information about CORS and CORS preflight requests, see:
9-
# https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
109

11-
# Set CORS headers for the preflight request
1210
if request.method == "OPTIONS":
13-
# Allows GET requests from any origin with the Content-Type
14-
# header and caches preflight response for an 3600s
15-
headers = {
16-
"Access-Control-Allow-Origin": "*",
17-
"Access-Control-Allow-Methods": "GET",
18-
"Access-Control-Allow-Headers": "Content-Type",
19-
"Access-Control-Max-Age": "3600",
20-
}
21-
22-
return ("", 204, headers)
11+
return respond_cors()
2312

2413
# Set CORS headers for the main request
2514
headers = {"Access-Control-Allow-Origin": "*"}

0 commit comments

Comments
 (0)