Skip to content

Commit

Permalink
new headers on adoption
Browse files Browse the repository at this point in the history
  • Loading branch information
maceto committed Dec 10, 2024
1 parent 6dfe880 commit 4926834
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 18 deletions.
17 changes: 13 additions & 4 deletions functions/adoption/libs/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,33 @@
Handles formatting responses to match the tuple pattern required by
the flask/GCP wrapper for Cloud Functions.
"""
import json
from .utils import convert_to_hashes

PREFLIGHT_HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Headers": "Content-Type, Timing-Allow-Origin",
"Access-Control-Max-Age": "3600",
}

HEADERS = {"Access-Control-Allow-Origin": "*", "Content-Type": "application/json"}
HEADERS = {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
"cache-control": "public, max-age=21600",
"Timing-Allow-Origin": "*"
}

def respond_cors():
"""
To be used to return OPTIONS responses to satisfy CORS preflight requests.
"""
return ("", 204, PREFLIGHT_HEADERS)

def respond(data, status=200):
def respond(result, headers=HEADERS):
"""
To be used to return responses to satisfy CORS requests.
"""
return (data, status, HEADERS)
status = 200 if result.success() else 400
payload = result.result if result.success() else convert_to_hashes(result.errors)
return (json.dumps(payload), status, headers)
5 changes: 0 additions & 5 deletions functions/adoption/libs/utils.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
import json
from urllib.parse import unquote

def output(result, headers={}):
status = 200 if result.success() else 400
payload = result.result if result.success() else convert_to_hashes(result.errors)
return (json.dumps(payload), status, headers)

def convert_to_hashes(arr):
hashes_arr = []
for inner_arr in arr:
Expand Down
12 changes: 3 additions & 9 deletions functions/adoption/main.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,24 @@
import functions_framework

from .libs.validator import Validator
from .libs.utils import output
from .libs.queries import list_data
from .libs.network import respond_cors
from .libs.network import respond_cors, respond

@functions_framework.http
def dispatcher(request):

if request.method == "OPTIONS":
return respond_cors()

headers = {
"Access-Control-Allow-Origin": "*",
"cache-control": "public, max-age=21600"
}

args = request.args.to_dict()

validator = Validator(params=args)
result = validator.validate()

if result.failure():
print("error", result.errors)
return output(result)
return respond(result)

response = list_data(result.result)

return output(response, headers)
return respond(response)

0 comments on commit 4926834

Please sign in to comment.