Skip to content

Commit 3015f19

Browse files
committed
start post collection
1 parent 2bfbba4 commit 3015f19

4 files changed

Lines changed: 173 additions & 40 deletions

File tree

src/msgraph_core/requests/batch_request_builder.py

Lines changed: 144 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import TypeVar, Dict, Optional
1+
from typing import TypeVar, Dict, Optional, Union, List
22
import json
33
import logging
44

@@ -10,7 +10,9 @@
1010
from kiota_abstractions.api_error import APIError
1111

1212
from .batch_request_content import BatchRequestContent
13+
from .batch_request_content_collection import BatchRequestContentCollection
1314
from .batch_response_content import BatchResponseContent
15+
from .batch_response_content_collection import BatchResponseContentCollection
1416

1517
T = TypeVar('T', bound='Parsable')
1618

@@ -31,7 +33,7 @@ def __init__(self, request_adapter: RequestAdapter, error_map: Optional[Dict[str
3133

3234
async def post(
3335
self,
34-
batch_request_content: BatchRequestContent,
36+
batch_request_content: Union[BatchRequestContent, BatchRequestContentCollection],
3537
error_map: Optional[Dict[str, int]] = None,
3638
) -> BatchResponseContent:
3739
"""
@@ -47,26 +49,121 @@ async def post(
4749
"""
4850
if batch_request_content is None:
4951
raise ValueError("batch_request_content cannot be Null.")
50-
request_info = await self.to_post_request_information(batch_request_content)
52+
if isinstance(batch_request_content, BatchRequestContent):
53+
request_info = await self.to_post_request_information(batch_request_content)
54+
content = json.loads(request_info.content.decode("utf-8"))
55+
json_body = json.dumps(content)
56+
request_info.content = json_body
57+
error_map = error_map or self.error_map
58+
response = None
59+
try:
60+
response = await self._request_adapter.send_async(
61+
request_info, BatchResponseContent, error_map
62+
)
63+
except APIError as e:
64+
logging.error(f"API Error: {e}")
65+
raise e
66+
if response is None:
67+
raise ValueError("Failed to get a valid response from the API.")
68+
return response
69+
if isinstance(batch_request_content, BatchRequestContentCollection):
70+
request_info = await self.to_post_request_information_from_collection(
71+
batch_request_content
72+
)
73+
74+
content = json.loads(request_info.content.decode("utf-8"))
75+
json_body = json.dumps(content)
76+
request_info.content = json_body
77+
error_map = error_map or self.error_map
78+
response = None
79+
try:
80+
response = await self._request_adapter.send_async(
81+
request_info, BatchResponseContent, error_map
82+
)
83+
except APIError as e:
84+
logging.error(f"API Error: {e}")
85+
raise e
86+
if response is None:
87+
raise ValueError("Failed to get a valid response from the API.")
88+
return response
89+
90+
async def post_content(
91+
self,
92+
batch_request_content: BatchRequestContentCollection,
93+
error_map: Optional[Dict[str, int]] = None,
94+
) -> BatchResponseContentCollection:
95+
if batch_request_content is None:
96+
raise ValueError("batch_request_content cannot be Null.")
97+
98+
# Determine the type of batch_request_content and call the appropriate method
99+
if isinstance(batch_request_content, BatchRequestContent):
100+
request_info = await self.to_post_request_information(batch_request_content)
101+
elif isinstance(batch_request_content, BatchRequestContentCollection):
102+
request_info = await self.to_post_request_information_from_collection(
103+
batch_request_content
104+
)
105+
batch_responses = await self.post_batch_collection(batch_request_content)
106+
return batch_responses
107+
else:
108+
raise ValueError("Invalid type for batch_request_content.")
109+
110+
print(f"request info to be posted {request_info}")
111+
112+
# Decode and re-encode the content to ensure it is in the correct format
51113
content = json.loads(request_info.content.decode("utf-8"))
52114
json_body = json.dumps(content)
53-
request_info.content = json_body
115+
request_info.content = json_body.encode("utf-8")
116+
54117
error_map = error_map or self.error_map
55118
response = None
119+
56120
try:
57121
response = await self._request_adapter.send_async(
58122
request_info, BatchResponseContent, error_map
59123
)
60124
except APIError as e:
61125
logging.error(f"API Error: {e}")
62126
raise e
127+
63128
if response is None:
64129
raise ValueError("Failed to get a valid response from the API.")
130+
65131
return response
66132

67-
async def to_post_request_information(
133+
async def post_batch_collection(
68134
self,
69-
batch_request_content: BatchRequestContent,
135+
batch_request_content_collection: BatchRequestContentCollection,
136+
error_map: Optional[Dict[str, int]] = None,
137+
) -> BatchResponseContentCollection:
138+
"""
139+
Sends a collection of batch requests and returns a collection of batch response contents.
140+
141+
Args:
142+
batch_request_content_collection (BatchRequestContentCollection): The collection of batch request contents.
143+
error_map: Dict[str, int] = {}:
144+
Error mappings for response handling.
145+
146+
Returns:
147+
BatchResponseContentCollection: The collection of batch response contents.
148+
"""
149+
if batch_request_content_collection is None:
150+
raise ValueError("batch_request_content_collection cannot be Null.")
151+
152+
batch_responses = BatchResponseContentCollection()
153+
154+
for batch_request_content in batch_request_content_collection.batches:
155+
request_info = await self.to_post_request_information(batch_request_content)
156+
print(f"request_info content before call {request_info.content}")
157+
# response = await self._request_adapter.send_async(
158+
# request_info, BatchResponseContent, error_map
159+
# )
160+
# = await self.post_content(batch_request_content, error_map)
161+
# batch_responses.add_response(batch_request_content.requests.keys(), response)
162+
163+
return batch_responses
164+
165+
async def to_post_request_information(
166+
self, batch_request_content: BatchRequestContent
70167
) -> RequestInformation:
71168
"""
72169
Creates request information for a batch POST request.
@@ -79,12 +176,51 @@ async def to_post_request_information(
79176
"""
80177
if batch_request_content is None:
81178
raise ValueError("batch_request_content cannot be Null.")
179+
if isinstance(batch_request_content, BatchRequestContent):
180+
request_info = RequestInformation()
181+
request_info.http_method = Method.POST
182+
request_info.url_template = self.url_template
183+
184+
requests_dict = [
185+
item.get_field_deserializers() for item in batch_request_content.requests
186+
]
187+
request_info.content = json.dumps({"requests": requests_dict}).encode("utf-8")
188+
189+
request_info.headers = HeadersCollection()
190+
request_info.headers.try_add("Content-Type", APPLICATION_JSON)
191+
request_info.set_content_from_parsable(
192+
self._request_adapter, APPLICATION_JSON, batch_request_content
193+
)
194+
195+
return request_info
196+
197+
async def to_post_request_information_from_collection(
198+
self, batch_request_content: BatchRequestContentCollection
199+
) -> RequestInformation:
200+
"""
201+
Creates request information for a batch POST request from a collection.
202+
203+
Args:
204+
batch_request_content (BatchRequestContentCollection): The batch request content collection.
205+
206+
Returns:
207+
RequestInformation: The request information.
208+
"""
209+
if batch_request_content is None:
210+
raise ValueError("batch_request_content cannot be Null.")
211+
82212
request_info = RequestInformation()
83213
request_info.http_method = Method.POST
84214
request_info.url_template = self.url_template
85215

86-
requests_dict = [item.get_field_deserializers() for item in batch_request_content.requests]
87-
request_info.content = json.dumps({"requests": requests_dict}).encode("utf-8")
216+
all_requests = []
217+
for batch_content in batch_request_content.batches:
218+
print(f"batch_content {batch_content}")
219+
requests_dict = [item.get_field_deserializers() for item in batch_content.requests]
220+
all_requests.extend(requests_dict)
221+
222+
request_info.content = json.dumps({"requests": all_requests}).encode("utf-8")
223+
print(f"All requests {request_info.content}")
88224

89225
request_info.headers = HeadersCollection()
90226
request_info.headers.try_add("Content-Type", APPLICATION_JSON)

src/msgraph_core/requests/batch_request_content.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ class BatchRequestContent(Parsable):
1313
Provides operations to call the batch method.
1414
"""
1515

16-
MAX_REQUESTS = 20
16+
MAX_REQUESTS = 5
1717

1818
def __init__(self, requests: List[Union['BatchRequestItem', 'RequestInformation']] = []):
1919
"""

src/msgraph_core/requests/batch_request_content_collection.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from typing import List, Optional
22

33
from kiota_abstractions.request_information import RequestInformation
4+
from kiota_abstractions.serialization import SerializationWriter
45

56
from .batch_request_content import BatchRequestContent
67
from .batch_request_item import BatchRequestItem
@@ -9,15 +10,13 @@
910
class BatchRequestContentCollection:
1011
"""A collection of request content objects."""
1112

12-
def __init__(self, batch_request_limit: int = 20):
13+
def __init__(self) -> None:
1314
"""
1415
Initializes a new instance of the BatchRequestContentCollection class.
1516
Args:
16-
batch_request_limit (int, optional): The maximum
1717
number of requests in a batch. Defaults to 20.
1818
1919
"""
20-
self.batch_request_limit = batch_request_limit or BatchRequestContent.MAX_REQUESTS
2120
self.batches: List[BatchRequestContent] = []
2221
self.current_batch: BatchRequestContent = BatchRequestContent()
2322

@@ -76,7 +75,17 @@ def get_batch_requests_for_execution(self) -> List[BatchRequestContent]:
7675
Returns:
7776
List[BatchRequestContent]: The batch requests for execution.
7877
"""
79-
if not self.current_batch.is_finalized:
80-
self.current_batch.finalize()
81-
self.batches.append(self.current_batch)
78+
# if not self.current_batch.is_finalized:
79+
# self.current_batch.finalize()
80+
# self.batches.append(self.current_batch)
8281
return self.batches
82+
83+
def serialize(self, writer: SerializationWriter) -> None:
84+
"""
85+
Serializes information the current object
86+
Args:
87+
writer: Serialization writer to use to serialize this model
88+
"""
89+
pass
90+
# print(f"serializing {self.batches}")
91+
# writer.write_collection_of_object_values("requests", self.batches)

src/msgraph_core/requests/batch_response_content_collection.py

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -20,36 +20,24 @@ def __init__(self) -> None:
2020
body: Optional[StreamInterface] = None
2121
2222
"""
23-
self._responses: BatchResponseContent = BatchResponseContent()
23+
self._responses = []
2424

25-
def add_response(self, content: Optional[BatchResponseItem] = None) -> None:
25+
def add_response(self, keys, response) -> None:
2626
"""
27-
Add a response to the collection
28-
:param content: The response to add to the collection
29-
:type content: Optional[BatchResponseItem]
27+
Adds a response to the collection.
28+
Args:
29+
keys: The keys of the response to add.
30+
response: The response to add.
3031
"""
31-
if content is None:
32-
return
33-
for item in content:
34-
self._responses.responses = content
32+
self._responses.append((keys, response))
3533

36-
async def get_response_by_id(self, request_id: str) -> Optional[BatchResponseItem]:
37-
"""
38-
Get a response by its request ID from the collection
39-
:param request_id: The request ID of the response to get
40-
:type request_id: str
41-
:return: The response with the specified request ID as a BatchResponseItem
42-
:rtype: Optional[BatchResponseItem]
34+
def get_responses(self):
35+
"""
36+
Gets the responses in the collection.
37+
Returns:
38+
List[Tuple[str, BatchResponseContent]]: The responses in the collection.
4339
"""
44-
if not self._responses:
45-
raise ValueError("No responses found in the collection")
46-
if isinstance(self._responses, BatchResponseContent):
47-
if self._responses.responses is None:
48-
raise ValueError("No responses found in the collection")
49-
for response in self._responses.responses:
50-
if isinstance(response, BatchResponseItem) and response.id == request_id:
51-
return response
52-
raise TypeError("Invalid type: Collection must be of type BatchResponseContent")
40+
return self._responses
5341

5442
@property
5543
async def responses_status_codes(self) -> Dict[str, int]:

0 commit comments

Comments
 (0)