-
Notifications
You must be signed in to change notification settings - Fork 94
/
service.py
1944 lines (1417 loc) · 67.4 KB
/
service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""OData service implementation
Details regarding batch requests and changesets:
http://www.odata.org/documentation/odata-version-2-0/batch-processing/
"""
# pylint: disable=too-many-lines
import logging
from functools import partial
import json
import random
from email.parser import Parser
from http.client import HTTPResponse
from io import BytesIO
from urllib.parse import urlencode, quote
from pyodata.exceptions import HttpError, PyODataException, ExpressionError, ProgramError
from . import model
LOGGER_NAME = 'pyodata.service'
HTTP_CODE_OK = 200
HTTP_CODE_CREATED = 201
def urljoin(*path):
"""Joins the passed string parts into a one string url"""
return '/'.join((part.strip('/') for part in path))
def encode_multipart(boundary, http_requests):
"""Encode list of requests into multipart body"""
lines = []
lines.append('')
for req in http_requests:
lines.append(f'--{boundary}')
if not isinstance(req, MultipartRequest):
lines.extend(('Content-Type: application/http ', 'Content-Transfer-Encoding:binary'))
lines.append('')
# request line (method + path + query params)
line = f'{req.get_method()} {req.get_path()}'
query_params = urlencode(req.get_query_params())
if query_params:
line += '?' + query_params
line += ' HTTP/1.1'
lines.append(line)
# request specific headers
for hdr, hdr_val in req.get_headers().items():
lines.append(f'{hdr}: {hdr_val}')
lines.append('')
body = req.get_body()
if body is not None:
lines.append(req.get_body())
else:
# this is very important since SAP gateway rejected request witout this line. It seems
# blank line must be provided as a representation of emtpy body, else we are getting
# 400 Bad fromat from SAP gateway
lines.append('')
lines.append(f'--{boundary}--')
return '\r\n'.join(lines)
def decode_multipart(data, content_type):
"""Decode parts of the multipart mime content"""
def decode(message):
"""Decode tree of messages for specific message"""
messages = []
for i, part in enumerate(message.walk()): # pylint: disable=unused-variable
if part.get_content_type() == 'multipart/mixed':
for submessage in part.get_payload():
messages.append(decode(submessage))
break
messages.append(part.get_payload())
return messages
data = f"Content-Type: {content_type}\n" + data
parser = Parser()
parsed = parser.parsestr(data)
decoded = decode(parsed)
return decoded
class ODataHttpResponse:
"""Representation of http response"""
def __init__(self, headers, status_code, content=None, url=None):
self.url = url
self.headers = headers
self.status_code = status_code
self.content = content
@staticmethod
def from_string(data):
"""Parse http response to status code, headers and body
Based on: https://stackoverflow.com/questions/24728088/python-parse-http-response-string
"""
class FakeSocket:
"""Fake socket to simulate received http response content"""
def __init__(self, response_str):
self._file = BytesIO(response_str.encode('utf-8'))
def makefile(self, *args, **kwargs):
"""Fake file that provides string content"""
# pylint: disable=unused-argument
return self._file
source = FakeSocket(data)
response = HTTPResponse(source)
response.begin()
response.length = response.fp.__sizeof__()
return ODataHttpResponse(
dict(response.getheaders()),
response.status,
response.read(len(data)) # the len here will give a 'big enough' value to read the whole content
)
def json(self):
"""Return response as decoded json"""
# TODO: see implementation in python requests, our simple
# approach can bring issues with encoding
# https://github.com/requests/requests/blob/master/requests/models.py#L868
if self.content:
return json.loads(self.content.decode('utf-8'))
return None
class EntityKey:
"""An immutable entity-key, made up of either a single value (single)
or multiple key-value pairs (complex).
Every entity must have an entity-key. The entity-key must be unique
within the entity-set, and thus defines an entity's identity.
The string representation of an entity-key is wrapped with parentheses,
such as (2), ('foo') or (a=1,foo='bar').
Entity-keys are equal if their string representations are equal.
"""
TYPE_SINGLE = 0
TYPE_COMPLEX = 1
def __init__(self, entity_type, single_key=None, **args):
self._logger = logging.getLogger(LOGGER_NAME)
self._proprties = args
self._entity_type = entity_type
self._key = entity_type.key_proprties
# single key does not need property name
if single_key is not None:
# check that entity type key consists of exactly one property
if len(self._key) != 1:
raise PyODataException(('Key of entity type {} consists of multiple properties {} '
'and cannot be initialized by single value').format(
self._entity_type.name, ', '.join([prop.name for prop in self._key])))
# get single key property and format key string
key_prop = self._key[0]
args[key_prop.name] = single_key
self._type = EntityKey.TYPE_SINGLE
self._logger.debug(('Detected single property key, adding pair %s->%s to key'
'properties'), key_prop.name, single_key)
else:
for key_prop in self._key:
if key_prop.name not in args:
raise PyODataException(f'Missing value for key property {key_prop.name}')
self._type = EntityKey.TYPE_COMPLEX
@property
def key_properties(self):
"""Key properties"""
return self._key
def to_key_string_without_parentheses(self):
"""Gets the string representation of the key without parentheses"""
if self._type == EntityKey.TYPE_SINGLE:
# first property is the key property
key_prop = self._key[0]
return key_prop.to_literal(self._proprties[key_prop.name])
key_pairs = []
for key_prop in self._key:
# if key_prop.name not in self.__dict__['_cache']:
# raise RuntimeError('Entity key is not complete, missing value of property: {0}'.format(key_prop.name))
key_pairs.append(
f'{key_prop.name}={key_prop.to_literal(self._proprties[key_prop.name])}')
return ','.join(key_pairs)
def to_key_string(self):
"""Gets the string representation of the key, including parentheses"""
return f'({self.to_key_string_without_parentheses()})'
def __repr__(self):
return self.to_key_string()
class ODataHttpRequest:
"""Deferred HTTP Request"""
def __init__(self, url, connection, handler, headers=None):
self._connection = connection
self._url = url
self._handler = handler
self._headers = headers or dict()
self._logger = logging.getLogger(LOGGER_NAME)
self._customs = {} # string -> string hash
self._next_url = None
@property
def handler(self):
"""Getter for handler"""
return self._handler
def get_path(self):
"""Get path of the HTTP request"""
# pylint: disable=no-self-use
return ''
def get_query_params(self):
"""Get query params"""
# pylint: disable=no-self-use
return dict(self._customs)
def get_method(self):
"""Get HTTP method"""
# pylint: disable=no-self-use
return 'GET'
def get_body(self):
"""Get HTTP body or None if not applicable"""
# pylint: disable=no-self-use
return None
def get_default_headers(self):
"""Get dict of Child specific HTTP headers"""
# pylint: disable=no-self-use
return dict()
def get_headers(self):
"""Get dict of HTTP headers which is union of return value
of the method get_default_headers() and the headers
added via the method add_headers() where the latter
headers have priority - same keys get value of the latter.
"""
headers = self.get_default_headers()
headers.update(self._headers)
return headers
def add_headers(self, value):
"""Add the give dictionary of HTTP headers to
HTTP request sent by this ODataHttpRequest instance.
"""
if not isinstance(value, dict):
raise TypeError(f"Headers must be of type 'dict' not {type(value)}")
self._headers.update(value)
def _build_request(self):
if self._next_url:
url = self._next_url
else:
url = urljoin(self._url, self.get_path())
# pylint: disable=assignment-from-none
body = self.get_body()
headers = self.get_headers()
self._logger.debug('Send (execute) %s request to %s', self.get_method(), url)
self._logger.debug(' query params: %s', self.get_query_params())
self._logger.debug(' headers: %s', headers)
if body:
self._logger.debug(' body: %s', body)
params = self.get_query_params()
return url, body, headers, params
async def async_execute(self):
"""Fetches HTTP response and returns processed result
Sends the query-request to the OData service, returning a client-side Enumerable for
subsequent in-memory operations.
Fetches HTTP response and returns processed result"""
url, body, headers, params = self._build_request()
async with self._connection.request(self.get_method(),
url,
headers=headers,
params=params,
data=body) as async_response:
response = ODataHttpResponse(url=async_response.url,
headers=async_response.headers,
status_code=async_response.status,
content=await async_response.read())
return self._call_handler(response)
def execute(self):
"""Fetches HTTP response and returns processed result
Sends the query-request to the OData service, returning a client-side Enumerable for
subsequent in-memory operations.
Fetches HTTP response and returns processed result"""
url, body, headers, params = self._build_request()
response = self._connection.request(
self.get_method(), url, headers=headers, params=urlencode(params), data=body)
return self._call_handler(response)
def _call_handler(self, response):
self._logger.debug('Received response')
self._logger.debug(' url: %s', response.url)
self._logger.debug(' headers: %s', response.headers)
self._logger.debug(' status code: %d', response.status_code)
try:
self._logger.debug(' body: %s', response.content.decode('utf-8'))
except UnicodeDecodeError:
self._logger.debug(' body: <cannot be decoded>')
return self._handler(response)
def custom(self, name, value):
"""Adds a custom name-value pair."""
# returns QueryRequest
self._customs[name] = value
return self
class EntityGetRequest(ODataHttpRequest):
"""Used for GET operations of a single entity"""
def __init__(self, handler, entity_key, entity_set_proxy, encode_path=True):
super(EntityGetRequest, self).__init__(entity_set_proxy.service.url, entity_set_proxy.service.connection,
handler)
self._logger = logging.getLogger(LOGGER_NAME)
self._entity_key = entity_key
self._entity_set_proxy = entity_set_proxy
self._select = None
self._expand = None
self._encode_path = encode_path
self._logger.debug('New instance of EntityGetRequest for last segment: %s', self._entity_set_proxy.last_segment)
def nav(self, nav_property):
"""Navigates to given navigation property and returns the EntitySetProxy"""
return self._entity_set_proxy.nav(nav_property, self._entity_key)
def select(self, select):
"""Specifies a subset of properties to return.
@param select a comma-separated list of selection clauses
"""
self._select = select
return self
def expand(self, expand):
"""Specifies related entities to expand inline as part of the response.
@param expand a comma-separated list of navigation properties
"""
self._expand = expand
return self
def get_path(self):
if self.get_encode_path():
return quote(self._entity_set_proxy.last_segment + self._entity_key.to_key_string())
return self._entity_set_proxy.last_segment + self._entity_key.to_key_string()
def get_default_headers(self):
return {'Accept': 'application/json'}
def get_query_params(self):
qparams = super(EntityGetRequest, self).get_query_params()
if self._select is not None:
qparams['$select'] = self._select
if self._expand is not None:
qparams['$expand'] = self._expand
return qparams
def get_value(self, connection=None):
"""Returns Value of Media EntityTypes also known as the $value URL suffix."""
if connection is None:
connection = self._connection
def stream_handler(response):
"""Returns $value from HTTP Response"""
if response.status_code != HTTP_CODE_OK:
raise HttpError('HTTP GET for $value failed with status code {}'
.format(response.status_code), response)
return response
return ODataHttpRequest(
urljoin(self._url, self.get_path(), '/$value'),
connection,
stream_handler)
def get_encode_path(self):
"""Getter for encode path flag"""
return self._encode_path
class NavEntityGetRequest(EntityGetRequest):
"""Used for GET operations of a single entity accessed via a Navigation property"""
def __init__(self, handler, master_key, entity_set_proxy, nav_property):
super(NavEntityGetRequest, self).__init__(handler, master_key, entity_set_proxy)
self._nav_property = nav_property
def get_path(self):
return f"{super(NavEntityGetRequest, self).get_path()}/{self._nav_property}"
class EntityCreateRequest(ODataHttpRequest):
"""Used for creating entities (POST operations of a single entity)
Call execute() to send the create-request to the OData service
and get the newly created entity."""
def __init__(self, url, connection, handler, entity_set, last_segment=None):
super(EntityCreateRequest, self).__init__(url, connection, handler)
self._logger = logging.getLogger(LOGGER_NAME)
self._entity_set = entity_set
self._entity_type = entity_set.entity_type
if last_segment is None:
self._last_segment = self._entity_set.name
else:
self._last_segment = last_segment
self._values = {}
# get all properties declared by entity type
self._type_props = self._entity_type.proprties()
self._logger.debug('New instance of EntityCreateRequest for entity type: %s on path %s', self._entity_type.name,
self._last_segment)
def get_path(self):
return self._last_segment
def get_method(self):
# pylint: disable=no-self-use
return 'POST'
def _get_body(self):
"""Recursively builds a dictionary of values where some of the values
might be another entities.
"""
body = {}
for key, val in self._values.items():
# The value is either an entity or a scalar
if isinstance(val, EntityProxy):
body[key] = val._get_body() # pylint: disable=protected-access
else:
body[key] = val
return body
def get_body(self):
return json.dumps(self._get_body())
def get_default_headers(self):
return {'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'X'}
@staticmethod
def _build_values(entity_type, entity):
"""Recursively converts a dictionary of values where some of the values
might be another entities (navigation properties) into the internal
representation.
"""
if isinstance(entity, list):
return [EntityCreateRequest._build_values(entity_type, item) for item in entity]
values = {}
for key, val in entity.items():
try:
val = entity_type.proprty(key).to_json(val)
except KeyError:
try:
nav_prop = entity_type.nav_proprty(key)
val = EntityCreateRequest._build_values(nav_prop.typ, val)
except KeyError:
raise PyODataException('Property {} is not declared in {} entity type'.format(
key, entity_type.name))
values[key] = val
return values
def set(self, **kwargs):
"""Set properties on the new entity."""
self._logger.info(kwargs)
# TODO: consider use of attset for setting properties
self._values = EntityCreateRequest._build_values(self._entity_type, kwargs)
return self
class EntityDeleteRequest(ODataHttpRequest):
"""Used for deleting entity (DELETE operations on a single entity)"""
def __init__(self, url, connection, handler, entity_set, entity_key, encode_path=True):
super(EntityDeleteRequest, self).__init__(url, connection, handler)
self._logger = logging.getLogger(LOGGER_NAME)
self._entity_set = entity_set
self._entity_key = entity_key
self._encode_path = encode_path
self._logger.debug('New instance of EntityDeleteRequest for entity type: %s', entity_set.entity_type.name)
def get_path(self):
if self.get_encode_path():
return quote(self._entity_set.name + self._entity_key.to_key_string())
return self._entity_set.name + self._entity_key.to_key_string()
def get_encode_path(self):
"""Getter for encode path flag"""
return self._encode_path
def get_method(self):
# pylint: disable=no-self-use
return 'DELETE'
# pylint: disable=too-many-instance-attributes
class EntityModifyRequest(ODataHttpRequest):
"""Used for modyfing entities (UPDATE/MERGE operations on a single entity)
Call execute() to send the update-request to the OData service
and get the modified entity."""
ALLOWED_HTTP_METHODS = ['PATCH', 'PUT', 'MERGE']
# pylint: disable=too-many-arguments
def __init__(self, url, connection, handler, entity_set, entity_key, method="PATCH", encode_path=True):
super(EntityModifyRequest, self).__init__(url, connection, handler)
self._logger = logging.getLogger(LOGGER_NAME)
self._entity_set = entity_set
self._entity_type = entity_set.entity_type
self._entity_key = entity_key
self._encode_path = encode_path
self._method = method.upper()
if self._method not in EntityModifyRequest.ALLOWED_HTTP_METHODS:
raise ValueError('The value "{}" is not on the list of allowed Entity Update HTTP Methods: {}'
.format(method, ', '.join(EntityModifyRequest.ALLOWED_HTTP_METHODS)))
self._values = {}
# get all properties declared by entity type
self._type_props = self._entity_type.proprties()
self._logger.debug('New instance of EntityModifyRequest for entity type: %s', self._entity_type.name)
def get_path(self):
if self.get_encode_path():
return quote(self._entity_set.name + self._entity_key.to_key_string())
return self._entity_set.name + self._entity_key.to_key_string()
def get_method(self):
# pylint: disable=no-self-use
return self._method
def get_body(self):
# pylint: disable=no-self-use
body = {}
for key, val in self._values.items():
body[key] = val
return json.dumps(body)
def get_default_headers(self):
return {'Accept': 'application/json', 'Content-Type': 'application/json'}
def get_encode_path(self):
"""Getter for encode path flag"""
return self._encode_path
def set(self, **kwargs):
"""Set properties to be changed."""
self._logger.info(kwargs)
for key, val in kwargs.items():
try:
val = self._entity_type.proprty(key).to_json(val)
except KeyError:
raise PyODataException(
f'Property {key} is not declared in {self._entity_type.name} entity type')
self._values[key] = val
return self
class QueryRequest(ODataHttpRequest):
"""INTERFACE A consumer-side query-request builder. Call execute() to issue the request."""
# pylint: disable=too-many-instance-attributes
def __init__(self, url, connection, handler, last_segment):
super(QueryRequest, self).__init__(url, connection, handler)
self._logger = logging.getLogger(LOGGER_NAME)
self._count = None
self._inlinecount = None
self._top = None
self._skip = None
self._order_by = None
self._filter = None
self._select = None
self._expand = None
self._last_segment = last_segment
self._logger.debug('New instance of QueryRequest for last segment: %s', self._last_segment)
def count(self, inline=False):
"""Sets a flag to return the number of items. Can be inline with results or just the count."""
if inline:
self._inlinecount = True
else:
self._count = True
return self
def next_url(self, next_url):
"""
Sets URL which identifies the next partial set of entities from the originally identified complete set. Once
set, this URL takes precedence over all query parameters.
For details, see section "6. Representing Collections of Entries" on
https://www.odata.org/documentation/odata-version-2-0/json-format/
"""
self._next_url = next_url
return self
def expand(self, expand):
"""Sets the expand expressions."""
self._expand = expand
return self
def filter(self, filter_val):
"""Sets the filter expression."""
# returns QueryRequest
self._filter = filter_val
return self
# def nav(self, key_value, nav_property):
# """Navigates to a referenced collection using a collection-valued navigation property."""
# # returns QueryRequest
# raise NotImplementedError
def order_by(self, order_by):
"""Sets the ordering expressions."""
self._order_by = order_by
return self
def select(self, select):
"""Sets the selection clauses."""
self._select = select
return self
def skip(self, skip):
"""Sets the number of items to skip."""
self._skip = skip
return self
def top(self, top):
"""Sets the number of items to return."""
self._top = top
return self
def get_path(self):
if self._count:
return urljoin(self._last_segment, '/$count')
return self._last_segment
def get_default_headers(self):
if self._count:
return {}
return {
'Accept': 'application/json',
}
def get_query_params(self):
if self._next_url:
return {}
qparams = super(QueryRequest, self).get_query_params()
if self._top is not None:
qparams['$top'] = self._top
if self._skip is not None:
qparams['$skip'] = self._skip
if self._order_by is not None:
qparams['$orderby'] = self._order_by
if self._filter is not None:
qparams['$filter'] = self._filter
if self._select is not None:
qparams['$select'] = self._select
if self._expand is not None:
qparams['$expand'] = self._expand
if self._inlinecount:
qparams['$inlinecount'] = 'allpages'
return qparams
class FunctionRequest(QueryRequest):
"""Function import request (Service call)"""
def __init__(self, url, connection, handler, function_import):
super(FunctionRequest, self).__init__(url, connection, handler, function_import.name)
self._function_import = function_import
self._logger.debug('New instance of FunctionRequest for %s', self._function_import.name)
def parameter(self, name, value):
'''Sets value of parameter.'''
# check if param is valid (is declared in metadata)
try:
param = self._function_import.get_parameter(name)
# add parameter as custom query argument
self.custom(param.name, param.to_literal(value))
except KeyError:
raise PyODataException('Function import {0} does not have pararmeter {1}'
.format(self._function_import.name, name))
return self
def get_method(self):
return self._function_import.http_method
def get_default_headers(self):
return {
'Accept': 'application/json'
}
# pylint: disable=too-many-instance-attributes
class EntityProxy:
"""An immutable OData entity instance, consisting of an identity (an
entity-set and a unique entity-key within that set), properties (typed,
named values), and links (references to other entities).
"""
# pylint: disable=too-many-branches,too-many-nested-blocks,too-many-statements
def __init__(self, service, entity_set, entity_type, proprties=None, entity_key=None, etag=None):
self._logger = logging.getLogger(LOGGER_NAME)
self._service = service
self._entity_set = entity_set
self._entity_type = entity_type
self._key_props = entity_type.key_proprties
self._cache = dict()
self._entity_key = entity_key
self._etag = etag
self._logger.debug('New entity proxy instance of type %s from properties: %s', entity_type.name, proprties)
# cache values of individual properties if provided
if proprties is not None:
etag_body = proprties.get('__metadata', dict()).get('etag', None)
if etag is not None and etag_body is not None and etag_body != etag:
raise PyODataException('Etag from header does not match the Etag from response body')
if etag_body is not None:
self._etag = etag_body
# first, cache values of direct properties
for type_proprty in self._entity_type.proprties():
if type_proprty.name in proprties:
# Property value available
if proprties[type_proprty.name] is not None:
self._cache[type_proprty.name] = type_proprty.from_json(proprties[type_proprty.name])
continue
# Property value missing and user wants a type specific default value filled in
if not self._service.retain_null:
# null value is in literal form for now, convert it to python representation
self._cache[type_proprty.name] = type_proprty.from_literal(type_proprty.typ.null_value)
continue
# Property is nullable - save it as such
if type_proprty.nullable:
self._cache[type_proprty.name] = None
continue
raise PyODataException(f'Value of non-nullable Property {type_proprty.name} is null')
# then, assign all navigation properties
for prop in self._entity_type.nav_proprties:
if prop.name in proprties:
# entity type of navigation property
prop_etype = prop.to_role.entity_type
# cache value according to multiplicity
if prop.to_role.multiplicity in \
[model.EndRole.MULTIPLICITY_ONE,
model.EndRole.MULTIPLICITY_ZERO_OR_ONE]:
# cache None in case we receive nothing (null) instead of entity data
if proprties[prop.name] is None:
self._cache[prop.name] = None
else:
self._cache[prop.name] = EntityProxy(service, None, prop_etype, proprties[prop.name])
elif prop.to_role.multiplicity == model.EndRole.MULTIPLICITY_ZERO_OR_MORE:
# default value is empty array
self._cache[prop.name] = []
# if there are no entities available, received data consists of
# metadata properties only.
if 'results' in proprties[prop.name]:
# available entities are serialized in results array
for entity in proprties[prop.name]['results']:
self._cache[prop.name].append(EntityProxy(service, None, prop_etype, entity))
else:
for entity in proprties[prop.name]:
self._cache[prop.name].append(EntityProxy(service, None, prop_etype, entity))
else:
raise PyODataException('Unknown multiplicity {0} of association role {1}'
.format(prop.to_role.multiplicity, prop.to_role.name))
# build entity key if not provided
if self._entity_key is None:
# try to build key from available property values
try:
# if key seems to be simple (consists of single property)
if len(self._key_props) == 1:
self._entity_key = EntityKey(entity_type, self._cache[self._key_props[0].name])
else:
# build complex key
self._entity_key = EntityKey(entity_type, **self._cache)
except KeyError:
pass
except PyODataException:
pass
def __repr__(self):
return self._entity_key.to_key_string()
def __getattr__(self, attr):
try:
return self._cache[attr]
except KeyError:
try:
value = self.get_proprty(attr).execute()
self._cache[attr] = value
return value
except KeyError as ex:
raise AttributeError('EntityType {0} does not have Property {1}: {2}'
.format(self._entity_type.name, attr, str(ex)))
async def async_getattr(self, attr):
"""Get cached value of attribute or do async call to service to recover attribute value"""
try:
return self._cache[attr]
except KeyError:
try:
value = await self.get_proprty(attr).async_execute()
self._cache[attr] = value
return value
except KeyError as ex:
raise AttributeError('EntityType {0} does not have Property {1}: {2}'
.format(self._entity_type.name, attr, str(ex)))
def nav(self, nav_property):
"""Navigates to given navigation property and returns the EntitySetProxy"""
# for now duplicated with simillar method in entity set proxy class
try:
navigation_property = self._entity_type.nav_proprty(nav_property)
except KeyError:
raise PyODataException('Navigation property {} is not declared in {} entity type'.format(
nav_property, self._entity_type))
# Get entity set of navigation property
association_info = navigation_property.association_info
association_set = self._service.schema.association_set_by_association(
association_info.name,
association_info.namespace)
end = association_set.end_by_role(navigation_property.to_role.role)
navigation_entity_set = self._service.schema.entity_set(end.entity_set_name)
if navigation_property.to_role.multiplicity != model.EndRole.MULTIPLICITY_ZERO_OR_MORE:
return self._get_nav_entity(nav_property, navigation_entity_set)
return EntitySetProxy(
self._service,
self._service.schema.entity_set(navigation_entity_set.name),
nav_property,
self._entity_set.name + self._entity_key.to_key_string())
def _get_nav_entity(self, nav_property, navigation_entity_set):
"""Get entity based on Navigation property name"""
def get_entity_handler(parent, nav_property, navigation_entity_set, response):
"""Gets entity from HTTP response"""
if response.status_code != HTTP_CODE_OK:
raise HttpError('HTTP GET for Entity {0} failed with status code {1}'
.format(self._name, response.status_code), response)
entity = response.json()['d']
return NavEntityProxy(parent, nav_property, navigation_entity_set.entity_type, entity)
self._logger.info(
'Getting the nav property %s of the entity %s for the key %s',
nav_property,
self._entity_set,
self.entity_key)
return NavEntityGetRequest(
partial(get_entity_handler, self, nav_property, navigation_entity_set),
self.entity_key,
getattr(self._service.entity_sets, self.entity_set.name),
nav_property)
def get_path(self):
"""Returns this entity's relative path - e.g. EntitySet(KEY)"""
return self._entity_set._name + self._entity_key.to_key_string() # pylint: disable=protected-access
def get_proprty(self, name, connection=None):
"""Returns value of the property"""
self._logger.info('Initiating property request for %s', name)
def proprty_get_handler(key, proprty, response):
"""Gets property value from HTTP Response"""
if response.status_code != HTTP_CODE_OK:
raise HttpError('HTTP GET for Attribute {0} of Entity {1} failed with status code {2}'
.format(proprty.name, key, response.status_code), response)
data = response.json()['d']