gmicloud 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- examples/__init__.py +0 -0
- examples/example.py +145 -0
- gmicloud/__init__.py +41 -0
- gmicloud/_internal/__init__.py +0 -0
- gmicloud/_internal/_client/__init__.py +0 -0
- gmicloud/_internal/_client/_artifact_client.py +179 -0
- gmicloud/_internal/_client/_decorator.py +22 -0
- gmicloud/_internal/_client/_file_upload_client.py +115 -0
- gmicloud/_internal/_client/_http_client.py +150 -0
- gmicloud/_internal/_client/_iam_client.py +92 -0
- gmicloud/_internal/_client/_task_client.py +142 -0
- gmicloud/_internal/_config.py +3 -0
- gmicloud/_internal/_constants.py +13 -0
- gmicloud/_internal/_enums.py +23 -0
- gmicloud/_internal/_exceptions.py +19 -0
- gmicloud/_internal/_manager/__init__.py +0 -0
- gmicloud/_internal/_manager/_artifact_manager.py +303 -0
- gmicloud/_internal/_manager/_task_manager.py +221 -0
- gmicloud/_internal/_models.py +336 -0
- gmicloud/client.py +51 -0
- gmicloud/tests/__init__.py +0 -0
- gmicloud/tests/test_artifacts.py +274 -0
- gmicloud/tests/test_tasks.py +207 -0
- gmicloud-0.1.0.dist-info/METADATA +208 -0
- gmicloud-0.1.0.dist-info/RECORD +27 -0
- gmicloud-0.1.0.dist-info/WHEEL +5 -0
- gmicloud-0.1.0.dist-info/top_level.txt +2 -0
examples/__init__.py
ADDED
File without changes
|
examples/example.py
ADDED
@@ -0,0 +1,145 @@
|
|
1
|
+
import os
|
2
|
+
import time
|
3
|
+
from datetime import datetime
|
4
|
+
|
5
|
+
from openai import OpenAI
|
6
|
+
|
7
|
+
from gmicloud import *
|
8
|
+
|
9
|
+
|
10
|
+
def create_artifact_with_file(client: Client) -> str:
|
11
|
+
artifact_manager = client.artifact_manager
|
12
|
+
|
13
|
+
# Create an artifact with a file
|
14
|
+
artifact_id = artifact_manager.create_artifact_with_file(
|
15
|
+
artifact_name="Llama3.1 8B",
|
16
|
+
artifact_file_path="./files/Llama-3.1-8B-Instruct.zip",
|
17
|
+
description="This is a test artifact",
|
18
|
+
tags=['example', 'test']
|
19
|
+
)
|
20
|
+
|
21
|
+
return artifact_id
|
22
|
+
|
23
|
+
|
24
|
+
def create_artifact_from_template(client: Client) -> str:
|
25
|
+
artifact_manager = client.artifact_manager
|
26
|
+
|
27
|
+
# Get all artifact templates
|
28
|
+
templates = artifact_manager.get_artifact_templates()
|
29
|
+
print(templates)
|
30
|
+
for template in templates:
|
31
|
+
if template.artifact_name == "Llama3.1 8B":
|
32
|
+
# Create an artifact from a template
|
33
|
+
artifact_id = artifact_manager.create_artifact_from_template(
|
34
|
+
artifact_template_id=template.artifact_template_id,
|
35
|
+
)
|
36
|
+
|
37
|
+
return artifact_id
|
38
|
+
|
39
|
+
return ""
|
40
|
+
|
41
|
+
|
42
|
+
def create_task_and_start(client: Client, artifact_id: str) -> str:
|
43
|
+
artifact_manager = client.artifact_manager
|
44
|
+
# Wait for the artifact to be ready
|
45
|
+
while True:
|
46
|
+
try:
|
47
|
+
artifact = artifact_manager.get_artifact(artifact_id)
|
48
|
+
print(f"Artifact status: {artifact.build_status}")
|
49
|
+
# Wait until the artifact is ready
|
50
|
+
if artifact.build_status == BuildStatus.SUCCESS:
|
51
|
+
break
|
52
|
+
except Exception as e:
|
53
|
+
raise e
|
54
|
+
# Wait for 2 seconds
|
55
|
+
time.sleep(2)
|
56
|
+
try:
|
57
|
+
task_manager = client.task_manager
|
58
|
+
# Create a task
|
59
|
+
task = task_manager.create_task(Task(
|
60
|
+
config=TaskConfig(
|
61
|
+
ray_task_config=RayTaskConfig(
|
62
|
+
ray_version="latest-py311-gpu",
|
63
|
+
file_path="serve",
|
64
|
+
artifact_id=artifact_id,
|
65
|
+
deployment_name="app",
|
66
|
+
replica_resource=ReplicaResource(
|
67
|
+
cpu=24,
|
68
|
+
ram_gb=128,
|
69
|
+
gpu=2,
|
70
|
+
),
|
71
|
+
),
|
72
|
+
task_scheduling=TaskScheduling(
|
73
|
+
scheduling_oneoff=OneOffScheduling(
|
74
|
+
trigger_timestamp=int(datetime.now().timestamp()) + 60,
|
75
|
+
min_replicas=1,
|
76
|
+
max_replicas=10,
|
77
|
+
)
|
78
|
+
),
|
79
|
+
),
|
80
|
+
))
|
81
|
+
|
82
|
+
# Start the task
|
83
|
+
task_manager.start_task(task.task_id)
|
84
|
+
except Exception as e:
|
85
|
+
raise e
|
86
|
+
|
87
|
+
return task.task_id
|
88
|
+
|
89
|
+
|
90
|
+
def call_chat_completion(client: Client, task_id: str):
|
91
|
+
task_manager = client.task_manager
|
92
|
+
# Wait for the task to be ready
|
93
|
+
while True:
|
94
|
+
try:
|
95
|
+
task = task_manager.get_task(task_id)
|
96
|
+
print(f"task status: {task.task_status}")
|
97
|
+
# Wait until the task is ready
|
98
|
+
if task.task_status == "ready":
|
99
|
+
break
|
100
|
+
except Exception as e:
|
101
|
+
print(e)
|
102
|
+
return
|
103
|
+
# Wait for 2 seconds
|
104
|
+
time.sleep(2)
|
105
|
+
|
106
|
+
if not task.info.endpoint or not task.info.endpoint.strip():
|
107
|
+
raise Exception("Task endpoint is not ready yet")
|
108
|
+
|
109
|
+
open_ai = OpenAI(
|
110
|
+
api_key=os.getenv("OPENAI_API_KEY", "YOUR_DEFAULT_API_KEY"),
|
111
|
+
base_url=os.getenv("OPENAI_API_BASE", task.info.endpoint)
|
112
|
+
)
|
113
|
+
# Make a chat completion request using the new OpenAI client.
|
114
|
+
completion = open_ai.chat.completions.create(
|
115
|
+
model="meta-llama/Llama-3.1-8B-Instruct",
|
116
|
+
messages=[
|
117
|
+
{"role": "system", "content": "You are a helpful assistant."},
|
118
|
+
{"role": "user",
|
119
|
+
"content": f"Translate the sentences to Chinese"},
|
120
|
+
],
|
121
|
+
max_tokens=200,
|
122
|
+
temperature=0.7
|
123
|
+
)
|
124
|
+
|
125
|
+
print(completion.choices[0].message.content)
|
126
|
+
|
127
|
+
|
128
|
+
if __name__ == '__main__':
|
129
|
+
# Initialize the Client
|
130
|
+
cli = Client()
|
131
|
+
|
132
|
+
# print(cli.artifact_manager.get_all_artifacts())
|
133
|
+
|
134
|
+
# Create an artifact with a file
|
135
|
+
# artifact_id = create_artifact_with_file(cli)
|
136
|
+
|
137
|
+
# Create an artifact from a template
|
138
|
+
#artifact_id = create_artifact_from_template(cli)
|
139
|
+
artifact_id = "cba6db2f-315a-4765-9e94-1e692f7fdb39"
|
140
|
+
|
141
|
+
# Create a task and start it
|
142
|
+
task_id = create_task_and_start(cli, artifact_id)
|
143
|
+
|
144
|
+
# Call chat completion
|
145
|
+
call_chat_completion(cli, task_id)
|
gmicloud/__init__.py
ADDED
@@ -0,0 +1,41 @@
|
|
1
|
+
from ._internal._models import (
|
2
|
+
Artifact,
|
3
|
+
ArtifactData,
|
4
|
+
ArtifactMetadata,
|
5
|
+
Task,
|
6
|
+
TaskOwner,
|
7
|
+
TaskConfig,
|
8
|
+
TaskInfo,
|
9
|
+
RayTaskConfig,
|
10
|
+
TaskScheduling,
|
11
|
+
ReplicaResource,
|
12
|
+
OneOffScheduling,
|
13
|
+
DailyScheduling,
|
14
|
+
DailyTrigger,
|
15
|
+
ArtifactTemplate
|
16
|
+
)
|
17
|
+
from ._internal._enums import (
|
18
|
+
BuildStatus,
|
19
|
+
TaskEndpointStatus
|
20
|
+
)
|
21
|
+
from .client import Client
|
22
|
+
|
23
|
+
__all__ = [
|
24
|
+
"Client",
|
25
|
+
"Artifact",
|
26
|
+
"ArtifactData",
|
27
|
+
"ArtifactMetadata",
|
28
|
+
"Task",
|
29
|
+
"TaskOwner",
|
30
|
+
"TaskConfig",
|
31
|
+
"TaskInfo",
|
32
|
+
"RayTaskConfig",
|
33
|
+
"TaskScheduling",
|
34
|
+
"ReplicaResource",
|
35
|
+
"OneOffScheduling",
|
36
|
+
"DailyScheduling",
|
37
|
+
"DailyTrigger",
|
38
|
+
"ArtifactTemplate",
|
39
|
+
"BuildStatus",
|
40
|
+
"TaskEndpointStatus"
|
41
|
+
]
|
File without changes
|
File without changes
|
@@ -0,0 +1,179 @@
|
|
1
|
+
from typing import List
|
2
|
+
|
3
|
+
from ._http_client import HTTPClient
|
4
|
+
from ._iam_client import IAMClient
|
5
|
+
from ._decorator import handle_refresh_token
|
6
|
+
from .._models import *
|
7
|
+
from .._config import ARTIFACT_SERVICE_BASE_URL
|
8
|
+
from .._constants import ACCESS_TOKEN_HEADER, CLIENT_ID_HEADER
|
9
|
+
|
10
|
+
|
11
|
+
class ArtifactClient:
|
12
|
+
"""
|
13
|
+
Client for interacting with the Artifact Service API.
|
14
|
+
|
15
|
+
This client provides methods to perform CRUD operations on artifacts,
|
16
|
+
as well as generating signed URLs for uploading large files.
|
17
|
+
"""
|
18
|
+
|
19
|
+
def __init__(self, iam_client: IAMClient):
|
20
|
+
"""
|
21
|
+
Initializes the ArtifactClient with an HTTPClient configured
|
22
|
+
to communicate with the Artifact Service base URL.
|
23
|
+
"""
|
24
|
+
self.client = HTTPClient(ARTIFACT_SERVICE_BASE_URL)
|
25
|
+
self.iam_client = iam_client
|
26
|
+
|
27
|
+
@handle_refresh_token
|
28
|
+
def get_artifact(self, artifact_id: str) -> Artifact:
|
29
|
+
"""
|
30
|
+
Fetches an artifact by its ID.
|
31
|
+
|
32
|
+
:param artifact_id: The ID of the artifact to fetch.
|
33
|
+
:return: The Artifact object.
|
34
|
+
:rtype: Artifact
|
35
|
+
"""
|
36
|
+
custom_headers = {
|
37
|
+
ACCESS_TOKEN_HEADER: self.iam_client.get_access_token(),
|
38
|
+
CLIENT_ID_HEADER: self.iam_client.get_client_id()
|
39
|
+
}
|
40
|
+
result = self.client.get(f"/get_artifact", custom_headers, {"artifact_id": artifact_id})
|
41
|
+
|
42
|
+
return Artifact.model_validate(result)
|
43
|
+
|
44
|
+
@handle_refresh_token
|
45
|
+
def get_all_artifacts(self, user_id: str) -> List[Artifact]:
|
46
|
+
"""
|
47
|
+
Fetches all artifacts for a given user ID.
|
48
|
+
|
49
|
+
:param user_id: The ID of the user whose artifacts are being fetched.
|
50
|
+
:return: A list of Artifact objects.
|
51
|
+
:rtype: List[Artifact]
|
52
|
+
"""
|
53
|
+
custom_headers = {
|
54
|
+
ACCESS_TOKEN_HEADER: self.iam_client.get_access_token(),
|
55
|
+
CLIENT_ID_HEADER: self.iam_client.get_client_id()
|
56
|
+
}
|
57
|
+
result = self.client.get("/get_all_artifacts", custom_headers, {"user_id": user_id})
|
58
|
+
if not result:
|
59
|
+
return []
|
60
|
+
return [Artifact.model_validate(item) for item in result]
|
61
|
+
|
62
|
+
@handle_refresh_token
|
63
|
+
def create_artifact(self, request: CreateArtifactRequest) -> CreateArtifactResponse:
|
64
|
+
"""
|
65
|
+
Creates a new artifact in the service.
|
66
|
+
|
67
|
+
:param request: The request object containing artifact details.
|
68
|
+
:return: The response object containing the created artifact details.
|
69
|
+
:rtype: CreateArtifactResponse
|
70
|
+
"""
|
71
|
+
custom_headers = {
|
72
|
+
ACCESS_TOKEN_HEADER: self.iam_client.get_access_token(),
|
73
|
+
CLIENT_ID_HEADER: self.iam_client.get_client_id()
|
74
|
+
}
|
75
|
+
result = self.client.post("/create_artifact", custom_headers, request.model_dump())
|
76
|
+
|
77
|
+
return CreateArtifactResponse.model_validate(result)
|
78
|
+
|
79
|
+
@handle_refresh_token
|
80
|
+
def create_artifact_from_template(self,
|
81
|
+
request: CreateArtifactFromTemplateRequest) -> CreateArtifactFromTemplateResponse:
|
82
|
+
"""
|
83
|
+
Creates a new artifact in the service.
|
84
|
+
|
85
|
+
:param request: The request object containing artifact details.
|
86
|
+
:return: The response object containing the created artifact details.
|
87
|
+
:rtype: CreateArtifactFromTemplateResponse
|
88
|
+
"""
|
89
|
+
custom_headers = {
|
90
|
+
ACCESS_TOKEN_HEADER: self.iam_client.get_access_token(),
|
91
|
+
CLIENT_ID_HEADER: self.iam_client.get_client_id()
|
92
|
+
}
|
93
|
+
result = self.client.post("/create_artifact_from_template", custom_headers,
|
94
|
+
request.model_dump())
|
95
|
+
|
96
|
+
return CreateArtifactFromTemplateResponse.model_validate(result)
|
97
|
+
|
98
|
+
@handle_refresh_token
|
99
|
+
def rebuild_artifact(self, artifact_id: str) -> RebuildArtifactResponse:
|
100
|
+
"""
|
101
|
+
Rebuilds an artifact in the service.
|
102
|
+
|
103
|
+
:param artifact_id: The ID of the artifact to rebuild.
|
104
|
+
:return: The response object containing the rebuilt artifact details.
|
105
|
+
:rtype: RebuildArtifactResponse
|
106
|
+
"""
|
107
|
+
custom_headers = {
|
108
|
+
ACCESS_TOKEN_HEADER: self.iam_client.get_access_token(),
|
109
|
+
CLIENT_ID_HEADER: self.iam_client.get_client_id()
|
110
|
+
}
|
111
|
+
result = self.client.post("/rebuild_artifact", custom_headers, {"artifact_id": artifact_id})
|
112
|
+
|
113
|
+
return CreateArtifactResponse.model_validate(result)
|
114
|
+
|
115
|
+
@handle_refresh_token
|
116
|
+
def delete_artifact(self, artifact_id: str) -> DeleteArtifactResponse:
|
117
|
+
"""
|
118
|
+
Deletes an artifact by its ID.
|
119
|
+
|
120
|
+
:param artifact_id: The ID of the artifact to delete.
|
121
|
+
:return: The response object containing the deleted artifact details.
|
122
|
+
:rtype: DeleteArtifactResponse
|
123
|
+
"""
|
124
|
+
custom_headers = {
|
125
|
+
ACCESS_TOKEN_HEADER: self.iam_client.get_access_token(),
|
126
|
+
CLIENT_ID_HEADER: self.iam_client.get_client_id()
|
127
|
+
}
|
128
|
+
result = self.client.delete("/delete_artifact", custom_headers, {"artifact_id": artifact_id})
|
129
|
+
|
130
|
+
return DeleteArtifactResponse.model_validate(result)
|
131
|
+
|
132
|
+
@handle_refresh_token
|
133
|
+
def get_bigfile_upload_url(self, request: GetBigFileUploadUrlRequest) -> GetBigFileUploadUrlResponse:
|
134
|
+
"""
|
135
|
+
Generates a pre-signed URL for uploading a large file.
|
136
|
+
|
137
|
+
:param request: The request object containing the artifact ID, file name, and file type.
|
138
|
+
:return: The response object containing the pre-signed URL and upload details.
|
139
|
+
:rtype: GetBigFileUploadUrlResponse
|
140
|
+
"""
|
141
|
+
custom_headers = {
|
142
|
+
ACCESS_TOKEN_HEADER: self.iam_client.get_access_token(),
|
143
|
+
CLIENT_ID_HEADER: self.iam_client.get_client_id()
|
144
|
+
}
|
145
|
+
result = self.client.post("/get_bigfile_upload_url", custom_headers, request.model_dump())
|
146
|
+
|
147
|
+
return GetBigFileUploadUrlResponse.model_validate(result)
|
148
|
+
|
149
|
+
@handle_refresh_token
|
150
|
+
def delete_bigfile(self, request: DeleteBigfileRequest) -> DeleteBigfileResponse:
|
151
|
+
"""
|
152
|
+
Deletes a large file associated with an artifact.
|
153
|
+
|
154
|
+
:param request: The request object containing the artifact ID and file name.
|
155
|
+
:return: The response object containing the deletion status.
|
156
|
+
:rtype: DeleteBigfileResponse
|
157
|
+
"""
|
158
|
+
custom_headers = {
|
159
|
+
ACCESS_TOKEN_HEADER: self.iam_client.get_access_token(),
|
160
|
+
CLIENT_ID_HEADER: self.iam_client.get_client_id()
|
161
|
+
}
|
162
|
+
result = self.client.delete("/delete_bigfile", custom_headers, request.dict())
|
163
|
+
|
164
|
+
return DeleteBigfileResponse.model_validate(result)
|
165
|
+
|
166
|
+
@handle_refresh_token
|
167
|
+
def get_artifact_templates(self) -> GetArtifactTemplatesResponse:
|
168
|
+
"""
|
169
|
+
Fetches all artifact templates.
|
170
|
+
|
171
|
+
:return: A list of ArtifactTemplate objects.
|
172
|
+
:rtype: List[ArtifactTemplate]
|
173
|
+
"""
|
174
|
+
custom_headers = {
|
175
|
+
ACCESS_TOKEN_HEADER: self.iam_client.get_access_token(),
|
176
|
+
CLIENT_ID_HEADER: self.iam_client.get_client_id()
|
177
|
+
}
|
178
|
+
result = self.client.get("/get_artifact_templates", custom_headers)
|
179
|
+
return GetArtifactTemplatesResponse.model_validate(result)
|
@@ -0,0 +1,22 @@
|
|
1
|
+
from functools import wraps
|
2
|
+
|
3
|
+
from .._exceptions import UnauthorizedError
|
4
|
+
|
5
|
+
|
6
|
+
def handle_refresh_token(method):
|
7
|
+
"""
|
8
|
+
Decorator to handle automatic token refresh on 401 Unauthorized errors.
|
9
|
+
"""
|
10
|
+
|
11
|
+
@wraps(method)
|
12
|
+
def wrapper(self, *args, **kwargs):
|
13
|
+
try:
|
14
|
+
# First attempt to call the original method
|
15
|
+
return method(self, *args, **kwargs)
|
16
|
+
except UnauthorizedError: # Assume ArtifactClient raises this for 401 errors
|
17
|
+
# Refresh the token using the IAMClient
|
18
|
+
self.iam_client.refresh_token()
|
19
|
+
# Retry the original method
|
20
|
+
return method(self, *args, **kwargs)
|
21
|
+
|
22
|
+
return wrapper
|
@@ -0,0 +1,115 @@
|
|
1
|
+
import os
|
2
|
+
import requests
|
3
|
+
|
4
|
+
from .._exceptions import UploadFileError
|
5
|
+
|
6
|
+
|
7
|
+
class FileUploadClient:
|
8
|
+
CHUNK_SIZE = 10 * 1024 * 1024 # 10MB Default Chunk Size
|
9
|
+
|
10
|
+
"""
|
11
|
+
A file upload client supporting small files and resumable uploads (chunked uploads).
|
12
|
+
"""
|
13
|
+
|
14
|
+
@staticmethod
|
15
|
+
def upload_small_file(upload_url: str, file_path: str,
|
16
|
+
content_type: str = "application/zip"):
|
17
|
+
"""
|
18
|
+
Uploads a small file directly to a signed Google Storage upload URL.
|
19
|
+
|
20
|
+
:param upload_url: Signed upload URL for small files.
|
21
|
+
:param file_path: The local path to the file to upload.
|
22
|
+
:param content_type: MIME type of the file.
|
23
|
+
"""
|
24
|
+
try:
|
25
|
+
with open(file_path, "rb") as file:
|
26
|
+
file_data = file.read()
|
27
|
+
|
28
|
+
headers = {"Content-Type": content_type}
|
29
|
+
response = requests.put(upload_url, headers=headers, data=file_data)
|
30
|
+
|
31
|
+
if response.status_code not in [200, 201]:
|
32
|
+
raise UploadFileError(f"Failed to upload file, code:{response.status_code} ,message: {response.text}")
|
33
|
+
|
34
|
+
except requests.exceptions.RequestException as e:
|
35
|
+
raise UploadFileError(f"Failed to upload file: {str(e)}")
|
36
|
+
|
37
|
+
@staticmethod
|
38
|
+
def upload_large_file(upload_url: str, file_path: str, chunk_size: int = CHUNK_SIZE):
|
39
|
+
"""
|
40
|
+
Performs resumable (chunked) file uploads to a signed Google Storage URL.
|
41
|
+
|
42
|
+
:param upload_url: Signed resumable upload URL.
|
43
|
+
:param file_path: The local path to the file to upload.
|
44
|
+
:param chunk_size: Chunk size in bytes (default: 10MB).
|
45
|
+
"""
|
46
|
+
try:
|
47
|
+
file_size = os.path.getsize(file_path)
|
48
|
+
print(f"File Size: {file_size} bytes")
|
49
|
+
|
50
|
+
start_byte = 0
|
51
|
+
uploaded_range = FileUploadClient._check_file_status(upload_url, file_size)
|
52
|
+
if uploaded_range:
|
53
|
+
start_byte = int(uploaded_range.split("-")[1]) + 1
|
54
|
+
print(f"Resuming upload from {start_byte} bytes")
|
55
|
+
|
56
|
+
with open(file_path, "rb") as file:
|
57
|
+
while start_byte < file_size:
|
58
|
+
# Calculate end byte and adjust chunk to not exceed file size
|
59
|
+
end_byte = min(start_byte + chunk_size - 1, file_size - 1)
|
60
|
+
|
61
|
+
# Seek to the current position in the file and read the chunk
|
62
|
+
file.seek(start_byte)
|
63
|
+
chunk_data = file.read(chunk_size)
|
64
|
+
|
65
|
+
# Set the Content-Range and headers
|
66
|
+
content_range = f"bytes {start_byte}-{end_byte}/{file_size}"
|
67
|
+
headers = {
|
68
|
+
"Content-Length": str(len(chunk_data)),
|
69
|
+
"Content-Range": content_range
|
70
|
+
}
|
71
|
+
|
72
|
+
# Upload the chunk
|
73
|
+
resp = requests.put(upload_url, headers=headers, data=chunk_data)
|
74
|
+
# Ensure upload is successful for this chunk
|
75
|
+
if resp.status_code not in (200, 201, 308):
|
76
|
+
raise UploadFileError(
|
77
|
+
f"Failed to upload file, code:{resp.status_code} ,message: {resp.text}")
|
78
|
+
|
79
|
+
start_byte = end_byte + 1
|
80
|
+
print(f"Uploaded {end_byte + 1}/{file_size} bytes")
|
81
|
+
|
82
|
+
print("Upload completed successfully.")
|
83
|
+
except Exception as e:
|
84
|
+
raise UploadFileError(f"Failed to upload file: {str(e)}")
|
85
|
+
|
86
|
+
@staticmethod
|
87
|
+
def _check_file_status(upload_url: str, file_size: int) -> str:
|
88
|
+
"""
|
89
|
+
Check the status of a resumable upload.
|
90
|
+
|
91
|
+
:param upload_url: The resumable upload URL.
|
92
|
+
:param file_size: Total file size in bytes.
|
93
|
+
:return: The status of the upload (e.g., 'bytes=0-10485759') or None if no partial upload.
|
94
|
+
"""
|
95
|
+
headers = {
|
96
|
+
"Content-Length": "0", # No payload for status check
|
97
|
+
"Content-Range": f"bytes */{file_size}" # Asking server where the upload left off
|
98
|
+
}
|
99
|
+
|
100
|
+
try:
|
101
|
+
resp = requests.put(upload_url, headers=headers)
|
102
|
+
|
103
|
+
# If upload is incomplete (HTTP 308: Resume Incomplete), retrieve the "Range" header
|
104
|
+
if resp.status_code == 308:
|
105
|
+
range_header = resp.headers.get("Range")
|
106
|
+
if range_header:
|
107
|
+
print(f"Server reports partial upload range: {range_header}")
|
108
|
+
return range_header
|
109
|
+
|
110
|
+
if resp.status_code in (200, 201):
|
111
|
+
return None
|
112
|
+
|
113
|
+
resp.raise_for_status()
|
114
|
+
except requests.RequestException as e:
|
115
|
+
raise UploadFileError(f"Failed to check file status: {str(e)}") from e
|
@@ -0,0 +1,150 @@
|
|
1
|
+
import requests
|
2
|
+
from .._exceptions import APIError
|
3
|
+
from .._exceptions import UnauthorizedError
|
4
|
+
from .._constants import *
|
5
|
+
from .._config import *
|
6
|
+
|
7
|
+
|
8
|
+
class HTTPClient:
|
9
|
+
"""
|
10
|
+
A simple HTTP API client for interacting with REST APIs.
|
11
|
+
"""
|
12
|
+
|
13
|
+
def __init__(self, base_url):
|
14
|
+
"""
|
15
|
+
Initialize the HTTP client.
|
16
|
+
|
17
|
+
:param base_url: The base URL of the REST API (e.g., https://api.example.com)
|
18
|
+
"""
|
19
|
+
self.base_url = base_url.rstrip('/')
|
20
|
+
|
21
|
+
def _prepare_url(self, endpoint):
|
22
|
+
"""
|
23
|
+
Helper method to prepare the full URL.
|
24
|
+
|
25
|
+
:param endpoint: The API endpoint to append to the base URL.
|
26
|
+
:return: The full API URL as a string.
|
27
|
+
"""
|
28
|
+
return f"{self.base_url}{endpoint}"
|
29
|
+
|
30
|
+
def _send_request(self, method, endpoint, custom_headers=None, data=None, params=None):
|
31
|
+
"""
|
32
|
+
Internal method for sending HTTP requests.
|
33
|
+
|
34
|
+
:param method: The HTTP method (e.g., 'GET', 'POST', 'PUT', 'PATCH', 'DELETE').
|
35
|
+
:param endpoint: The API endpoint.
|
36
|
+
:param custom_headers: The request headers (optional).
|
37
|
+
:param data: The request payload for POST/PUT/PATCH requests (optional).
|
38
|
+
:param params: The query parameters for GET/DELETE requests (optional).
|
39
|
+
:return: The JSON response parsed as a Python dictionary.
|
40
|
+
:raises APIError: If the request fails or the response is invalid.
|
41
|
+
"""
|
42
|
+
print("data=", data)
|
43
|
+
url = self._prepare_url(endpoint)
|
44
|
+
headers = {
|
45
|
+
ACCEPT_HEADER: JSON_CONTENT_TYPE,
|
46
|
+
CONTENT_TYPE_HEADER: JSON_CONTENT_TYPE,
|
47
|
+
}
|
48
|
+
|
49
|
+
# Add custom headers if provided
|
50
|
+
if custom_headers:
|
51
|
+
headers.update(custom_headers)
|
52
|
+
|
53
|
+
response = None
|
54
|
+
try:
|
55
|
+
# if method == HTTP_METHOD_POST:
|
56
|
+
# response = requests.post(url, json=data, headers=headers)
|
57
|
+
# elif method == HTTP_METHOD_GET:
|
58
|
+
# response = requests.get(url, params=params, headers=headers)
|
59
|
+
# elif method == HTTP_METHOD_PATCH:
|
60
|
+
# response = requests.patch(url, data=data, headers=headers)
|
61
|
+
# elif method == HTTP_METHOD_DELETE:
|
62
|
+
# response = requests.delete(url, params=params, headers=headers)
|
63
|
+
# else:
|
64
|
+
# raise APIError(f"Unsupported HTTP method: {method}")
|
65
|
+
response = requests.request(method, url, params=params, json=data, headers=headers)
|
66
|
+
# response = method_map[method](url, json=data if method != HTTP_METHOD_GET else None,
|
67
|
+
# params=params, headers=headers)
|
68
|
+
|
69
|
+
print("=============", response.text)
|
70
|
+
if response.status_code == 401:
|
71
|
+
raise UnauthorizedError("Access token expired or invalid.")
|
72
|
+
elif response.status_code != 200 and response.status_code != 201:
|
73
|
+
if url.find("ie/artifact") != -1 or url.find("ie/task") != -1:
|
74
|
+
error_message = response.json().get('error', 'Unknown error')
|
75
|
+
else:
|
76
|
+
error_message = response.json().get('message', 'Unknown error')
|
77
|
+
raise APIError(f"HTTP Request failed: {error_message}")
|
78
|
+
|
79
|
+
# Raise for HTTP errors
|
80
|
+
response.raise_for_status()
|
81
|
+
|
82
|
+
except requests.exceptions.RequestException as e:
|
83
|
+
raise APIError(f"HTTP Request failed: {str(e)}")
|
84
|
+
except ValueError as e:
|
85
|
+
# Fallback if response JSON is invalid
|
86
|
+
raise APIError(f"Failed to parse JSON response: {response.text}")
|
87
|
+
|
88
|
+
if response.headers.get(CONTENT_TYPE_HEADER).find(JSON_CONTENT_TYPE) != -1:
|
89
|
+
return response.json()
|
90
|
+
elif response.headers.get(CONTENT_TYPE_HEADER).find(TEXT_CONTENT_TYPE) != -1:
|
91
|
+
raise APIError(f"Got text response: {response.text}")
|
92
|
+
else:
|
93
|
+
raise APIError(f"Unsupported content type: {response.headers.get(CONTENT_TYPE_HEADER)}")
|
94
|
+
|
95
|
+
def post(self, endpoint, custom_headers=None, data=None):
|
96
|
+
"""
|
97
|
+
Send a POST request to the given API endpoint.
|
98
|
+
|
99
|
+
:param endpoint: The API endpoint.
|
100
|
+
:param custom_headers: The request headers (optional).
|
101
|
+
:param data: The request payload as a dictionary.
|
102
|
+
:return: The JSON response parsed as a Python dictionary.
|
103
|
+
"""
|
104
|
+
return self._send_request(method=HTTP_METHOD_POST, endpoint=endpoint, custom_headers=custom_headers, data=data)
|
105
|
+
|
106
|
+
def get(self, endpoint, custom_headers=None, params=None):
|
107
|
+
"""
|
108
|
+
Send a GET request to the given API endpoint.
|
109
|
+
|
110
|
+
:param endpoint: The API endpoint.
|
111
|
+
:param custom_headers: The request headers (optional).
|
112
|
+
:param params: Query parameters as a dictionary (optional).
|
113
|
+
:return: The JSON response parsed as a Python dictionary.
|
114
|
+
"""
|
115
|
+
return self._send_request(method=HTTP_METHOD_GET, endpoint=endpoint, custom_headers=custom_headers,
|
116
|
+
params=params)
|
117
|
+
|
118
|
+
def put(self, endpoint, custom_headers=None, data=None):
|
119
|
+
"""
|
120
|
+
Send a PUT request to the given API endpoint.
|
121
|
+
|
122
|
+
:param endpoint: The API endpoint.
|
123
|
+
:param custom_headers: The request headers (optional).
|
124
|
+
:param data: The request payload as a dictionary.
|
125
|
+
:return: The JSON response parsed as a Python dictionary.
|
126
|
+
"""
|
127
|
+
return self._send_request(method=HTTP_METHOD_PUT, endpoint=endpoint, custom_headers=custom_headers, data=data)
|
128
|
+
|
129
|
+
def patch(self, endpoint, custom_headers=None, data=None):
|
130
|
+
"""
|
131
|
+
Send a PATCH request to the given API endpoint.
|
132
|
+
|
133
|
+
:param endpoint: The API endpoint.
|
134
|
+
:param custom_headers: The request headers (optional).
|
135
|
+
:param data: The request payload as a dictionary.
|
136
|
+
:return: The JSON response parsed as a Python dictionary.
|
137
|
+
"""
|
138
|
+
return self._send_request(method=HTTP_METHOD_PATCH, endpoint=endpoint, custom_headers=custom_headers, data=data)
|
139
|
+
|
140
|
+
def delete(self, endpoint, custom_headers=None, params=None):
|
141
|
+
"""
|
142
|
+
Send a DELETE request to the given API endpoint.
|
143
|
+
|
144
|
+
:param endpoint: The API endpoint.
|
145
|
+
:param custom_headers: The request headers (optional).
|
146
|
+
:param params: Query parameters as a dictionary (optional).
|
147
|
+
:return: The JSON response parsed as a Python dictionary.
|
148
|
+
"""
|
149
|
+
return self._send_request(method=HTTP_METHOD_DELETE, endpoint=endpoint, custom_headers=custom_headers,
|
150
|
+
params=params)
|