Skip to content

Commit

Permalink
Add FileStreaming for static files
Browse files Browse the repository at this point in the history
  • Loading branch information
mikaelGusse committed Jun 24, 2024
1 parent c29b875 commit 008c8ae
Showing 1 changed file with 25 additions and 23 deletions.
48 changes: 25 additions & 23 deletions review/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
from io import BytesIO
import logging
import json
import shutil
Expand Down Expand Up @@ -630,6 +631,8 @@ class dolos_proxy_view(View):
upstream_url = 'https://dolos.cs.aalto.fi'

def dispatch(self, request, path):
local_static_directory = path

# Rewrite the URL: prepend the path with the upstream URL

base_url = f'{self.upstream_url}/{path}'
Expand All @@ -645,39 +648,38 @@ def dispatch(self, request, path):
'content-length': str(len(request.body)),
})


# Prepare the files
files = [(field_name, file) for (field_name, file) in request.FILES.items()]

# If the path starts with 'static', download and save the file
if path.startswith('static') or path.startswith('assets') or path.startswith('api'):
local_file_path = os.path.join(local_static_directory)

print(local_file_path)

with requests.get(true_url, stream=True) as r:
r.raise_for_status()
with open(local_file_path, 'wb') as f:
shutil.copyfileobj(r.raw, f)

# If the path starts with 'static', use the true_url
if path.startswith('static') or path.startswith('assets') or path.startswith('api/rails/active_storage'):
response = requests.get(true_url, stream=True)
if response.status_code == 200:
# Create a FileResponse from the content of the downloaded file
file_response = FileResponse(response.content, content_type=response.headers['Content-Type'])

file_response['Access-Control-Allow-Origin'] = '*'
return file_response
else:
return HttpResponse(f"Error: {response.status_code}. Could not fetch static file from {true_url}", status=response.status_code)
else:
# Send the proxied request to the upstream service
response = requests.request(
method=request.method,
url=proxy_url,
data=request.body,
headers=headers,
files=files,
cookies=request.COOKIES,
allow_redirects=True,
)
print("PATHPATHPATHPATHPATH: " + path)
# Send the proxied request to the upstream service
response = requests.request(
method=request.method,
url=proxy_url,
data=request.body,
headers=headers,
files=files,
cookies=request.COOKIES,
allow_redirects=True,
)


# Create a Django HttpResponse from the upstream response
proxy_response = HttpResponse(
content=response.content,
status=response.status_code,
#content_type=response.headers['Content-Type']
)

# Add the Access-Control-Allow-Origin header
Expand Down

0 comments on commit 008c8ae

Please sign in to comment.