Skip to content

Commit

Permalink
some work with the server
Browse files Browse the repository at this point in the history
  • Loading branch information
SanPen committed Jun 17, 2024
1 parent 8940ce9 commit 64c718f
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 3 deletions.
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pytest >= 7.2.0
rdflib
pymoo
fastapi
starlette
uvicorn
websockets
opencv-python
Expand Down
14 changes: 14 additions & 0 deletions src/GridCal/Gui/Main/SubClasses/Server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ def __init__(self, parent=None) -> None:
# menu
self.ui.actionEnable_server_mode.triggered.connect(self.server_start_stop)

# table double click
self.ui.server_tableView.doubleClicked.connect(self.get_results)

@staticmethod
def server_config_file_path() -> str:
"""
Expand Down Expand Up @@ -142,3 +145,14 @@ def post_start_stop_server(self):
if len(self.server_driver.logger):
warning_msg(text="Could not connect to the server", title="Server connection")
self.ui.actionEnable_server_mode.setChecked(False)

def get_results(self):
"""
:return:
"""
self.server_driver.download_results(job_id="",
api_key="",
local_filename="received.bin")

print("Done")
30 changes: 29 additions & 1 deletion src/GridCal/Session/server_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,10 @@ def report_status(self, txt: str):
self.status_func(txt)

def base_url(self):

"""
Base URL of the service
:return:
"""
return f"http://{self.url}:{self.port}"

def is_running(self) -> bool:
Expand Down Expand Up @@ -361,6 +364,31 @@ def delete_job(self, job_id: str, api_key: str) -> dict:

self.get_jobs()

def download_results(self, job_id: str, api_key: str, local_filename: str):
"""
:param job_id:
:param api_key:
:param local_filename:
:return:
"""
url = f"{self.base_url()}/download_results/{job_id}"

headers = {
"accept": "application/json",
"API-Key": api_key
}

# Stream the download to avoid loading the entire file into memory
with requests.get(url, headers=headers, stream=True) as response:
response.raise_for_status() # Check if the request was successful
with open(local_filename, "wb") as file:
for chunk in response.iter_content(chunk_size=1024 * 1024): # 1MB chunks
if chunk: # Filter out keep-alive chunks
file.write(chunk)

print(f"Downloaded file saved as {local_filename}")

def cancel_job(self, job_id: str, api_key: str) -> dict:
"""
Cancel a specific job by ID using the REST API.
Expand Down
34 changes: 32 additions & 2 deletions src/GridCalServer/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
import json
import numpy as np
import pyarrow as pa
import pyarrow.ipc as ipc
from typing import Dict
from hashlib import sha256
from fastapi import FastAPI, Header, HTTPException, BackgroundTasks
from fastapi import FastAPI, Header, HTTPException, BackgroundTasks, Response
from fastapi.responses import FileResponse
from starlette.responses import StreamingResponse
from GridCalEngine.IO.gridcal.remote import RemoteInstruction, RemoteJob
Expand Down Expand Up @@ -77,7 +80,7 @@ async def stream_load_json(json_data):

async def generate():
"""
generate
"""
yield json.dumps(json_data).encode()

Expand Down Expand Up @@ -161,6 +164,33 @@ async def cancel_job(job_id: str):
return {"message": f"Job {job_id} canceled successfully"}


@app.get("/download_results")
async def download_large_file():
"""
:return:
"""
# Path to your large binary file
file_path = "/home/santi/Vídeos/Dentro.del.Laberinto.avi"

# Check if the file exists
if not os.path.exists(file_path):
return Response(status_code=404, content="File not found")

# Function to stream the file
def iterfile():
"""
:return:
"""
with open(file_path, "rb") as file:
while chunk := file.read(1024 * 1024): # Read in chunks of 1MB
yield chunk

# Return a streaming response
return StreamingResponse(iterfile(), media_type="application/octet-stream")


if __name__ == "__main__":
import uvicorn

Expand Down

0 comments on commit 64c718f

Please sign in to comment.