Try another fix

This commit is contained in:
Anup Raj Gopinathan
2025-06-25 16:24:29 +02:00
parent e533a98b84
commit 30ba68a799
+21 -6
View File
@@ -9,8 +9,24 @@ from flask_migrate import upgrade
import awsgi import awsgi
import base64 import base64
from flask import send_from_directory, request, make_response
app = create_app() app = create_app()
# Patch static file serving to base64-encode for Lambda/awsgi
@app.route('/static/<path:filename>')
def static_files(filename):
# Serve static files with base64 encoding for Lambda
static_folder = os.path.join(app.root_path, 'static')
response = make_response(send_from_directory(static_folder, filename))
# Only base64-encode for binary types
content_type = response.headers.get('Content-Type', '')
binary_types = ["application/octet-stream", "image/", "application/pdf", "font/"]
if any(content_type.startswith(b) for b in binary_types):
# Mark for lambda_handler to base64 encode
response.headers['X-Is-Binary'] = '1'
return response
@app.cli.command("init-db") @app.cli.command("init-db")
def init_db_command(): def init_db_command():
"""Initialize the database.""" """Initialize the database."""
@@ -47,18 +63,17 @@ if __name__ == '__main__':
def lambda_handler(event, context): def lambda_handler(event, context):
response = awsgi.response(app, event, context) response = awsgi.response(app, event, context)
headers = response.get("headers", {}) headers = response.get("headers", {})
content_type = headers.get("Content-Type", headers.get("content-type", "")) # Only base64-encode if our custom header is set (for /static)
# List of binary content types (add more as needed) if headers.get("X-Is-Binary") == "1":
binary_types = ["application/octet-stream", "image/", "application/pdf"]
if any(content_type.startswith(b) for b in binary_types):
# Base64 encode the body if not already encoded
if not response.get("isBase64Encoded"): if not response.get("isBase64Encoded"):
body = response["body"] body = response["body"]
if isinstance(body, str): if isinstance(body, str):
# Try to encode as latin1 to preserve binary data
body = body.encode("latin1") body = body.encode("latin1")
import base64
response["body"] = base64.b64encode(body).decode("utf-8") response["body"] = base64.b64encode(body).decode("utf-8")
response["isBase64Encoded"] = True response["isBase64Encoded"] = True
# Remove the custom header from the response
response["headers"].pop("X-Is-Binary", None)
return response return response
def lambda_handler_upgrade_db(event, context): def lambda_handler_upgrade_db(event, context):