Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions services/edge/oas_commit
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0e64886dd0847341800d7191ed193b75413be998
157 changes: 79 additions & 78 deletions services/edge/src/stackit/edge/api/default_api.py

Large diffs are not rendered by default.

31 changes: 22 additions & 9 deletions services/edge/src/stackit/edge/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
""" # noqa: E501

import datetime
import decimal
import json
import mimetypes
import os
import re
import tempfile
import uuid
from enum import Enum
from typing import Dict, List, Optional, Tuple, Union
from urllib.parse import quote
Expand Down Expand Up @@ -63,8 +65,10 @@ class ApiClient:
"bool": bool,
"date": datetime.date,
"datetime": datetime.datetime,
"decimal": decimal.Decimal,
"object": object,
}
_pool = None

def __init__(self, configuration, header_name=None, header_value=None, cookie=None) -> None:
self.config: Configuration = configuration
Expand Down Expand Up @@ -267,7 +271,7 @@ def response_deserialize(
return_data = self.__deserialize_file(response_data)
elif response_type is not None:
match = None
content_type = response_data.getheader("content-type")
content_type = response_data.headers.get("content-type")
if content_type is not None:
match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
encoding = match.group(1) if match else "utf-8"
Expand All @@ -284,7 +288,7 @@ def response_deserialize(
return ApiResponse(
status_code=response_data.status,
data=return_data,
headers=response_data.getheaders(),
headers=response_data.headers,
raw_data=response_data.data,
)

Expand All @@ -296,6 +300,7 @@ def sanitize_for_serialization(self, obj):
If obj is str, int, long, float, bool, return directly.
If obj is datetime.datetime, datetime.date
convert to string in iso8601 format.
If obj is decimal.Decimal return string representation.
If obj is list, sanitize each element in the list.
If obj is dict, return the dict.
If obj is OpenAPI model, return the properties dict.
Expand All @@ -311,12 +316,16 @@ def sanitize_for_serialization(self, obj):
return obj.get_secret_value()
elif isinstance(obj, self.PRIMITIVE_TYPES):
return obj
elif isinstance(obj, uuid.UUID):
return str(obj)
elif isinstance(obj, list):
return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj]
elif isinstance(obj, tuple):
return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj)
elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
elif isinstance(obj, decimal.Decimal):
return str(obj)

elif isinstance(obj, dict):
obj_dict = obj
Expand All @@ -326,7 +335,7 @@ def sanitize_for_serialization(self, obj):
# and attributes which value is not None.
# Convert attribute name to json key in
# model definition for request.
if hasattr(obj, "to_dict") and callable(obj.to_dict):
if hasattr(obj, "to_dict") and callable(getattr(obj, "to_dict")): # noqa: B009
obj_dict = obj.to_dict()
else:
obj_dict = obj.__dict__
Expand Down Expand Up @@ -354,7 +363,7 @@ def deserialize(self, response_text: str, response_type: str, content_type: Opti
data = json.loads(response_text)
except ValueError:
data = response_text
elif re.match(r"^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)", content_type, re.IGNORECASE):
elif re.match(r"^application/(json|[\w!#$&.+\-^_]+\+json)\s*(;|$)", content_type, re.IGNORECASE):
if response_text == "":
data = ""
else:
Expand Down Expand Up @@ -400,12 +409,14 @@ def __deserialize(self, data, klass):

if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)
elif klass == object:
elif klass is object:
return self.__deserialize_object(data)
elif klass == datetime.date:
elif klass is datetime.date:
return self.__deserialize_date(data)
elif klass == datetime.datetime:
elif klass is datetime.datetime:
return self.__deserialize_datetime(data)
elif klass is decimal.Decimal:
return decimal.Decimal(data)
elif issubclass(klass, Enum):
return self.__deserialize_enum(data, klass)
else:
Expand Down Expand Up @@ -553,12 +564,14 @@ def __deserialize_file(self, response):
os.close(fd)
os.remove(path)

content_disposition = response.getheader("Content-Disposition")
content_disposition = response.headers.get("Content-Disposition")
if content_disposition:
m = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition)
if m is None:
raise ValueError("Unexpected 'content-disposition' header value")
filename = m.group(1)
filename = os.path.basename(m.group(1)) # Strip any directory traversal
if filename in ("", ".", ".."): # fall back to tmp filename
filename = os.path.basename(path)
path = os.path.join(os.path.dirname(path), filename)

with open(path, "wb") as f:
Expand Down
2 changes: 1 addition & 1 deletion services/edge/src/stackit/edge/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def __init__(
self.body = http_resp.data.decode("utf-8")
except Exception: # noqa: S110
pass
self.headers = http_resp.getheaders()
self.headers = http_resp.headers

@classmethod
def from_response(
Expand Down
1 change: 0 additions & 1 deletion services/edge/src/stackit/edge/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
Do not edit the class manually.
""" # noqa: E501


# import models into model package
from stackit.edge.models.bad_request import BadRequest
from stackit.edge.models.create_instance_payload import CreateInstancePayload
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
import json
import pprint
from typing import Any, ClassVar, Dict, List, Optional, Set
from uuid import UUID

from pydantic import BaseModel, ConfigDict, Field, StrictStr
from pydantic import BaseModel, ConfigDict, Field
from typing_extensions import Annotated, Self


Expand All @@ -32,7 +33,7 @@ class CreateInstancePayload(BaseModel):
display_name: Annotated[str, Field(min_length=4, strict=True, max_length=8)] = Field(
description="The displayed name to distinguish multiple instances.", alias="displayName"
)
plan_id: StrictStr = Field(description="Service Plan configures the size of the Instance.", alias="planId")
plan_id: UUID = Field(description="Service Plan configures the size of the Instance.", alias="planId")
__properties: ClassVar[List[str]] = ["description", "displayName", "planId"]

model_config = ConfigDict(
Expand Down
3 changes: 2 additions & 1 deletion services/edge/src/stackit/edge/models/instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import re # noqa: F401
from datetime import datetime
from typing import Any, ClassVar, Dict, List, Optional, Set
from uuid import UUID

from pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing_extensions import Annotated, Self
Expand All @@ -39,7 +40,7 @@ class Instance(BaseModel):
id: Annotated[str, Field(strict=True, max_length=16)] = Field(
description="A auto generated unique id which identifies the instance."
)
plan_id: StrictStr = Field(description="Service Plan configures the size of the Instance.", alias="planId")
plan_id: UUID = Field(description="Service Plan configures the size of the Instance.", alias="planId")
status: StrictStr = Field(description="The current status of the instance.")
__properties: ClassVar[List[str]] = [
"created",
Expand Down
6 changes: 3 additions & 3 deletions services/edge/src/stackit/edge/models/instance_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ def to_dict(self) -> Dict[str, Any]:
# override the default output from pydantic by calling `to_dict()` of each item in instances (list)
_items = []
if self.instances:
for _item in self.instances:
if _item:
_items.append(_item.to_dict())
for _item_instances in self.instances:
if _item_instances:
_items.append(_item_instances.to_dict())
_dict["instances"] = _items
return _dict

Expand Down
3 changes: 2 additions & 1 deletion services/edge/src/stackit/edge/models/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import json
import pprint
from typing import Any, ClassVar, Dict, List, Optional, Set
from uuid import UUID

from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing_extensions import Self
Expand All @@ -27,7 +28,7 @@ class Plan(BaseModel):
""" # noqa: E501

description: Optional[StrictStr] = Field(default=None, description="Description")
id: Optional[StrictStr] = Field(default=None, description="Service Plan Identifier")
id: Optional[UUID] = Field(default=None, description="Service Plan Identifier")
max_edge_hosts: Optional[StrictInt] = Field(
default=None, description="Maximum number of EdgeHosts", alias="maxEdgeHosts"
)
Expand Down
6 changes: 3 additions & 3 deletions services/edge/src/stackit/edge/models/plan_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ def to_dict(self) -> Dict[str, Any]:
# override the default output from pydantic by calling `to_dict()` of each item in valid_plans (list)
_items = []
if self.valid_plans:
for _item in self.valid_plans:
if _item:
_items.append(_item.to_dict())
for _item_valid_plans in self.valid_plans:
if _item_valid_plans:
_items.append(_item_valid_plans.to_dict())
_dict["validPlans"] = _items
return _dict

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
import json
import pprint
from typing import Any, ClassVar, Dict, List, Optional, Set
from uuid import UUID

from pydantic import BaseModel, ConfigDict, Field, StrictStr
from pydantic import BaseModel, ConfigDict, Field
from typing_extensions import Annotated, Self


Expand All @@ -29,7 +30,7 @@ class UpdateInstanceByNamePayload(BaseModel):
description: Optional[Annotated[str, Field(strict=True, max_length=256)]] = Field(
default=None, description="A user chosen description to distinguish multiple instances."
)
plan_id: Optional[StrictStr] = Field(
plan_id: Optional[UUID] = Field(
default=None, description="Service Plan configures the size of the Instance.", alias="planId"
)
__properties: ClassVar[List[str]] = ["description", "planId"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
import json
import pprint
from typing import Any, ClassVar, Dict, List, Optional, Set
from uuid import UUID

from pydantic import BaseModel, ConfigDict, Field, StrictStr
from pydantic import BaseModel, ConfigDict, Field
from typing_extensions import Annotated, Self


Expand All @@ -29,7 +30,7 @@ class UpdateInstancePayload(BaseModel):
description: Optional[Annotated[str, Field(strict=True, max_length=256)]] = Field(
default=None, description="A user chosen description to distinguish multiple instances."
)
plan_id: Optional[StrictStr] = Field(
plan_id: Optional[UUID] = Field(
default=None, description="Service Plan configures the size of the Instance.", alias="planId"
)
__properties: ClassVar[List[str]] = ["description", "planId"]
Expand Down
3 changes: 2 additions & 1 deletion services/edge/src/stackit/edge/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import json
import pprint
from typing import Any, ClassVar, Dict, List, Optional, Set
from uuid import UUID

from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing_extensions import Self
Expand All @@ -27,7 +28,7 @@ class User(BaseModel):
""" # noqa: E501

email: StrictStr = Field(description="The email of the user.")
internal_id: StrictStr = Field(description="The UUID of the user.", alias="internalId")
internal_id: UUID = Field(description="The UUID of the user.", alias="internalId")
__properties: ClassVar[List[str]] = ["email", "internalId"]

model_config = ConfigDict(
Expand Down
22 changes: 19 additions & 3 deletions services/edge/src/stackit/edge/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,17 @@ def read(self):
self.data = self.response.content
return self.data

@property
def headers(self):
"""Returns a dictionary of response headers."""
return self.response.headers

def getheaders(self):
"""Returns a dictionary of the response headers."""
"""Returns a dictionary of the response headers; use ``headers`` instead."""
return self.response.headers

def getheader(self, name, default=None):
"""Returns a given response header."""
"""Returns a given response header; use ``headers.get()`` instead."""
return self.response.headers.get(name, default)


Expand Down Expand Up @@ -93,13 +98,15 @@ def request(self, method, url, headers=None, body=None, post_params=None, _reque
url,
data=request_body,
headers=headers,
timeout=_request_timeout,
)
elif content_type == "application/x-www-form-urlencoded":
r = self.session.request(
method,
url,
params=post_params,
headers=headers,
timeout=_request_timeout,
)
elif content_type == "multipart/form-data":
# must del headers['Content-Type'], or the correct
Expand All @@ -113,6 +120,7 @@ def request(self, method, url, headers=None, body=None, post_params=None, _reque
url,
files=post_params,
headers=headers,
timeout=_request_timeout,
)
# Pass a `string` parameter directly in the body to support
# other content types than JSON when `body` argument is
Expand All @@ -123,10 +131,17 @@ def request(self, method, url, headers=None, body=None, post_params=None, _reque
url,
data=body,
headers=headers,
timeout=_request_timeout,
)
elif headers["Content-Type"].startswith("text/") and isinstance(body, bool):
request_body = "true" if body else "false"
r = self.session.request(method, url, data=request_body, headers=headers)
r = self.session.request(
method,
url,
data=request_body,
headers=headers,
timeout=_request_timeout,
)
else:
# Cannot generate the request from given parameters
msg = """Cannot prepare a request message for provided
Expand All @@ -140,6 +155,7 @@ def request(self, method, url, headers=None, body=None, post_params=None, _reque
url,
params={},
headers=headers,
timeout=_request_timeout,
)
except requests.exceptions.SSLError as e:
msg = "\n".join([type(e).__name__, str(e)])
Expand Down
Loading