Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
metadata = document.pop("@metadata")
original_document = deepcopy(document)
original_metadata = deepcopy(metadata)
type_from_metadata = conventions.try_get_type_from_metadata(metadata)
mapper = conventions.mappers.get(object_type, None)
if object_type == dict:
return document, metadata, original_metadata, original_document
if type_from_metadata is None:
if object_type is not None:
metadata["Raven-Python-Type"] = "{0}.{1}".format(object_type.__module__, object_type.__name__)
else: # no type defined on document or during load, return a dict
return _DynamicStructure(**document), metadata, original_metadata, original_document
else:
object_from_metadata = Utils.import_class(type_from_metadata)
if object_from_metadata is not None:
if object_type is None:
object_type = object_from_metadata
elif Utils.is_inherit(object_type, object_from_metadata):
mapper = conventions.mappers.get(object_from_metadata, None) or mapper
object_type = object_from_metadata
if nested_object_types is None and mapper:
entity = create_entity_with_mapper(document, mapper, object_type)
else:
entity = _DynamicStructure(**document)
entity.__class__ = object_type
entity = Utils.initialize_object(document, object_type)
self._my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._my_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self._my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, send_buffer_size)
self._my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, receive_buffer_size)
self._my_socket.settimeout(30)
# TODO: wrap SSL
if self._store.certificate:
self._my_socket = ssl.wrap_socket(self._my_socket, certfile=self._store.certificate,
ssl_version=ssl.PROTOCOL_TLSv1_2)
try:
self._my_socket.connect((host, port))
except Exception as e:
print(e)
header = Utils.dict_to_bytes(
{"Operation": "Subscription", "DatabaseName": self._database_name, "OperationVersion": 40})
self._my_socket.sendall(header)
parser = IncrementalJsonParser(self._my_socket)
response = parser.next_object()
if response['Status'] != "Ok":
if response['Status'] == "AuthorizationFailed":
raise ConnectionRefusedError(
"Cannot access database {0} because {1}".format(self._database_name, response['Message']))
elif response['Status'] == "TcpVersionMismatch":
raise InvalidOperationException(
"Cannot access database {0} because {1}".format(self._database_name, response['Message']))
options = Utils.dict_to_bytes(self._options.to_json())
self._my_socket.sendall(options)
pass
elif isinstance(data[key], (tuple, list)):
for item in data[key]:
parse_dict_rec(item)
data[key] = mapper(key, data[key])
else:
mapper_result = mapper(key, data[key])
data[key] = mapper_result if mapper_result else data[key]
return data, True
except TypeError as e:
raise TypeError("Can't parse to custom object", e)
first_parsed, need_to_parse = parse_dict_rec(dict_obj)
# After create a complete dict for our object we need to create the object with the object_type
if first_parsed is not None and need_to_parse:
return Utils.initialize_object(first_parsed, object_type, convert_to_snake_case)
return first_parsed
def parse_dict_rec(data):
try:
if not isinstance(data, dict):
try:
for i in range(len(data)):
data[i] = Utils.initialize_object(parse_dict_rec(data[i])[0], object_type,
convert_to_snake_case)
except TypeError:
return data, False
for key in data:
if isinstance(data[key], dict):
parse_dict_rec(data[key])
data[key] = mapper(key, data[key])
if key is None:
pass
elif isinstance(data[key], (tuple, list)):
for item in data[key]:
parse_dict_rec(item)
data[key] = mapper(key, data[key])
else:
mapper_result = mapper(key, data[key])
def create_request(self, server_node):
self.url = (f"{server_node.url}/databases/{server_node.database}"
f"/timeseries?docId={Utils.quote_key(self._document_id)}"
f"{f'&start={self._start}' if self._start > 0 else ''}"
f"{f'&pageSize={self._page_size}' if self._page_size < sys.maxsize else ''}")
for range_ in self._ranges:
self.url += (f"&name={Utils.quote_key(range_.name)}"
f"&from={Utils.datetime_to_string(range_.from_date)}"
def _convert_and_save_entity(self, key, document, object_type, nested_object_types):
if key not in self._documents_by_id:
entity, metadata, original_metadata, original_document = Utils.convert_to_entity(document, object_type,
self.conventions,
nested_object_types)
self.save_entity(key, entity, original_metadata, metadata, original_document)
def set_response(self, response):
if response is None:
return None
data = {}
try:
response = response.json()["Results"]
if len(response) > 1:
raise ValueError("response is Invalid")
for key, value in response[0].items():
data[Utils.convert_to_snake_case(key)] = value
return IndexDefinition(**data)
except ValueError:
raise response.raise_for_status()
def set_response(self, response):
if response is None:
return None
if response.status_code == 200:
attachment_details = {"content_type": response.headers.get("Content-Type", None),
"change_vector": Utils.get_change_vector_from_header(response),
"hash": response.headers.get("Attachment-Hash", None),
"size": response.headers.get("Attachment-Size", 0)}
return {"response": response, "details": attachment_details}
def _json_default(o):
if o is None:
return None
if isinstance(o, datetime):
return Utils.datetime_to_string(o)
elif isinstance(o, timedelta):
return Utils.timedelta_to_str(o)
elif getattr(o, "__dict__", None):
return o.__dict__
elif isinstance(o, set):
return list(o)
elif isinstance(o, int) or isinstance(o, float):
return str(o)
else:
raise TypeError(repr(o) + " is not JSON serializable (Try add a json default method to store convention)")
def wait_for_operation_complete(self, operation_id, timeout=None):
from pyravendb.d_commands.raven_commands import GetOperationStateCommand
start_time = time.time()
try:
get_operation_command = GetOperationStateCommand(operation_id)
while True:
response = self.request_executor.execute(get_operation_command)
if timeout and time.time() - start_time > timeout:
raise exceptions.TimeoutException("The operation did not finish before the timeout end")
if response["Status"] == "Completed":
return response
if response["Status"] == "Faulted":
raise exceptions.InvalidOperationException(response["Result"]["Error"])
time.sleep(0.5)
except ValueError as e:
raise exceptions.InvalidOperationException(e)