# Utils

<a id="opengate_data.utils.expressions"></a>

## opengate\_data.utils.expressions

<a id="opengate_data.utils.expressions.Expressions"></a>

### Expressions Objects

```python
class Expressions()
```

Expressions

The filter conditions a search accepts, as static methods returning plain
dicts: `eq`, `neq`, `like`, `gt`, `lt`, `gte`, `lte`, `in_`, `nin` and
`exists`. `FilterBuilder` extends this class, so in practice you reach them
through `client.new_filter_builder()` and combine them with `and_` / `or_`
before calling `build()`.

**Example**:

  ~~~python
  filter = client.new_filter_builder().and_(
  Expressions.eq("provision.administration.organization", "organization"),
  Expressions.exists("provision.device.identifier", True),
  ).build()
  ~~~

<a id="opengate_data.utils.expressions.Expressions.eq"></a>

---
#### eq

```python
def eq(field, value)
```

Adds an equality condition to the filter.

**Arguments**:

- `field` _str_ - The field to compare.
- `value` _any_ - The value to compare against.
  

**Returns**:

- `dict` - The equality condition.
  

**Example**:

  eq("device.operationalStatus", "NORMAL")

<a id="opengate_data.utils.expressions.Expressions.neq"></a>

---
#### neq

```python
def neq(field, value)
```

Adds a not-equal condition to the filter.

**Arguments**:

- `field` _str_ - The field to compare.
- `value` _any_ - The value to compare against.
  

**Returns**:

- `dict` - The not-equal condition.
  

**Example**:

  neq("device.operationalStatus", "ERROR")

<a id="opengate_data.utils.expressions.Expressions.like"></a>

---
#### like

```python
def like(field, value)
```

Adds a like condition to the filter.

**Arguments**:

- `field` _str_ - The field to compare.
- `value` _str_ - The regex pattern to match.
  

**Returns**:

- `dict` - The like condition.
  

**Example**:

  like("device.name", "device_.*")

<a id="opengate_data.utils.expressions.Expressions.gt"></a>

---
#### gt

```python
def gt(field, value)
```

Adds a greater-than condition to the filter.

**Arguments**:

- `field` _str_ - The field to compare.
- `value` _any_ - The value to compare against.
  

**Returns**:

- `dict` - The greater-than condition.
  

**Example**:

  gt("device.batteryLevel", 50)

<a id="opengate_data.utils.expressions.Expressions.lt"></a>

---
#### lt

```python
def lt(field, value)
```

Adds a less-than condition to the filter.

**Arguments**:

- `field` _str_ - The field to compare.
- `value` _any_ - The value to compare against.
  

**Returns**:

- `dict` - The less-than condition.
  

**Example**:

  lt("device.batteryLevel", 20)

<a id="opengate_data.utils.expressions.Expressions.gte"></a>

---
#### gte

```python
def gte(field, value)
```

Adds a greater-than-or-equal condition to the filter.

**Arguments**:

- `field` _str_ - The field to compare.
- `value` _any_ - The value to compare against.
  

**Returns**:

- `dict` - The greater-than-or-equal condition.
  

**Example**:

  gte("device.batteryLevel", 80)

<a id="opengate_data.utils.expressions.Expressions.lte"></a>

---
#### lte

```python
def lte(field, value)
```

Adds a less-than-or-equal condition to the filter.

**Arguments**:

- `field` _str_ - The field to compare.
- `value` _any_ - The value to compare against.
  

**Returns**:

- `dict` - The less-than-or-equal condition.
  

**Example**:

  lte("device.batteryLevel", 30)

<a id="opengate_data.utils.expressions.Expressions.in_"></a>

---
#### in\_

```python
def in_(field, values)
```

Adds an in condition to the filter.

**Arguments**:

- `field` _str_ - The field to compare.
- `values` _list_ - The list of values to compare against.
  

**Returns**:

- `dict` - The in condition.
  

**Example**:

  in_("device.name", ["device_1", "device_2"])

<a id="opengate_data.utils.expressions.Expressions.nin"></a>

---
#### nin

```python
def nin(field, values)
```

Adds a not-in condition to the filter.

**Arguments**:

- `field` _str_ - The field to compare.
- `values` _list_ - The list of values to compare against.
  

**Returns**:

- `dict` - The not-in condition.
  

**Example**:

  nin("device.name", ["device_3", "device_4"])

<a id="opengate_data.utils.expressions.Expressions.exists"></a>

---
#### exists

```python
def exists(field, value)
```

Adds an existence condition to the filter.

**Arguments**:

- `field` _str_ - The field to check for existence.
- `value` _bool_ - True to match the entities that have the field, False
  to match the ones that do not.
  

**Returns**:

- `dict` - The existence condition.
  

**Example**:

  ~~~python
  exists("device.location", True)
  ~~~

<a id="opengate_data.utils.utils"></a>

## opengate\_data.utils.utils

<a id="opengate_data.utils.utils.validate_type"></a>

---
#### validate\_type

```python
def validate_type(variable: Any, expected_type: Any,
                  variable_name: str) -> None
```

Validates that the given variable is of the expected type or types.

This function checks if the variable matches the expected type or any type in a tuple of expected types.
It raises a TypeError if the variable does not match the expected type(s).

**Arguments**:

- `variable` _Any_ - The variable to be checked.
- `expected_type` _Any_ - The expected type or a tuple of expected types.
- `variable_name` _str_ - The name of the variable, used in the error message to identify the variable.
  

**Raises**:

- `TypeError` - If the variable is not of the expected type(s).
  

**Returns**:

- `None` - This function does not return a value; it raises an exception if the type check fails.

<a id="opengate_data.utils.utils.set_method_call"></a>

---
#### set\_method\_call

```python
def set_method_call(method)
```

Decorates a method to ensure it is properly registered and tracked within the builder's workflow.

This decorator adds the method's name to a set that tracks method calls

**Arguments**:

- `method` _function_ - The method to be decorated.
  

**Returns**:

- `function` - The wrapped method with added functionality to register its call.
  

**Raises**:

- `None` - This decorator does not raise exceptions by itself but ensures the method call is registered.

<a id="opengate_data.utils.utils.parse_json"></a>

---
#### parse\_json

```python
def parse_json(value)
```

Attempts to convert a string into a Python object by interpreting it as JSON.

**Arguments**:

- `value` _str | Any_ - The value to attempt to convert. If the value is not a string,
  it is returned directly without attempting conversion.
  

**Returns**:

- `Any` - The Python object resulting from the JSON conversion if `value` is a valid JSON string.
  If the conversion fails due to a formatting error (ValueError), the original value is returned.
  If `value` is not a string, it is returned as is.

<a id="opengate_data.utils.utils.send_request"></a>

---
#### send\_request

```python
def send_request(method: str,
                 headers: dict | None = None,
                 url: str = "",
                 data: dict[str, Any] | str | None = None,
                 files: Any = None,
                 json_payload: dict[str, Any] | None = None,
                 params: Any = None,
                 verify: bool = False,
                 timeout: int = 3000,
                 stream: bool = False) -> Response | dict[str, Any]
```

Helper function to make HTTP requests using the requests library.

**Arguments**:

- `method` _str_ - HTTP method (e.g., 'GET', 'POST', 'PUT', 'DELETE', 'PATCH').
- `headers` _dict, optional_ - Request headers.
- `url` _str_ - The URL for the request.
- `data` _dict | str, optional_ - Payload for the request body.
- `files` _Any, optional_ - Files for multipart encoding upload.
- `json_payload` _dict, optional_ - JSON payload for the request body.
- `params` _dict | Any, optional_ - URL parameters.
- `verify` _bool_ - Whether to verify SSL certificates. Defaults to False.
- `timeout` _int_ - Request timeout in seconds. Defaults to 3000.
- `stream` _bool_ - Whether to keep the response body unread until it is
  consumed, which is what a file download needs. Defaults to False.
  

**Returns**:

  Response | dict[str, Any]: The response object if successful, or an error dictionary.

<a id="opengate_data.utils.utils.handle_basic_response"></a>

---
#### handle\_basic\_response

```python
def handle_basic_response(response: requests.Response) -> dict[str, Any]
```

Handle basic HTTP response.

This function processes the HTTP response and returns a dictionary containing the status code. If the response indicates an error, it also includes the error message.

**Arguments**:

- `response` _requests.Response_ - The response object to process.
  

**Returns**:

  dict[str, Any]: A dictionary containing the status code and, if applicable, the error message.

<a id="opengate_data.utils.utils.handle_error_response"></a>

---
#### handle\_error\_response

```python
def handle_error_response(response: requests.Response) -> dict[str, Any]
```

Turn a failed HTTP response into the dictionary the builders return.

Nothing is raised: the caller gets the status code and, when the platform
sent one, the body as the error.

**Arguments**:

- `response` _requests.Response_ - The response object to process.
  

**Returns**:

  dict[str, Any]: The status code and, if the response carried a body,
  the error.

<a id="opengate_data.utils.utils.handle_exception"></a>

---
#### handle\_exception

```python
def handle_exception(e)
```

Turn a transport failure into the dictionary the builders return.

A request that never reached the platform has no status code, so the
result names the kind of failure instead: connection, timeout, request or
unexpected.

**Arguments**:

- `e` _Exception_ - The exception raised while sending the request.
  

**Returns**:

  dict[str, str]: The kind of failure and its details.

<a id="opengate_data.utils.utils.validate_build_method_calls_execute"></a>

---
#### validate\_build\_method\_calls\_execute

```python
def validate_build_method_calls_execute(method_calls)
```

Check that a chain was closed properly before `execute()` runs.

Every builder has to be closed with `build()` or with `build_execute()`,
and `build()` has to be the last call before `execute()` — otherwise a
setter called after it would never be validated.

**Arguments**:

- `method_calls` _list[str]_ - The methods called on the builder, in order.
  

**Raises**:

- `Exception` - If `build()` was called more than once, if it was not the
  last call before `execute()`, or if neither `build()` nor
  `build_execute()` was called.

<a id="opengate_data.utils.utils.validate_build"></a>

---
#### validate\_build

```python
def validate_build(*,
                   method: str,
                   state: dict,
                   spec: dict,
                   used_methods: list[str] | None = None,
                   allowed_method_calls: set[str] | None = None,
                   field_aliases: dict[str, str] | None = None,
                   method_aliases: dict[str, str] | None = None) -> None
```

Generic builder validator with messages intended for the end user.

The two alias maps exist so the errors name what the caller wrote, not the
internals: without them a missing `with_destiny_path()` would be reported
as a missing 'path'.

**Arguments**:

- `method` _str_ - The operation selected in the chain, which picks its
  entry in the spec.
- `state` _dict_ - The current value of each field of the builder, by
  internal name.
- `spec` _dict_ - The rules per operation: 'required' and 'forbidden' field
  names, 'choices' mapping a field to its allowed values, and
  'custom' holding extra checks called with the state.
- `used_methods` _list[str] | None_ - The methods called on the builder, in
  order. Needed to catch two operations in the same chain.
- `allowed_method_calls` _set[str] | None_ - The method names that select an
  operation, of which a chain may use exactly one, once.
- `field_aliases` _dict[str, str] | None_ - Maps internal fields to public
  setter names (e.g., 'path' → 'with_path').
- `method_aliases` _dict[str, str] | None_ - Maps logical method names to
  public method names (e.g., 'list_one' → 'list_one()').
  

**Raises**:

- `RuntimeError` - If the chain combines several operations, or repeats one.
- `ValueError` - If no operation was selected, if it is not in the spec, or
  if the state misses a required field, carries a forbidden one, or
  holds a value outside its choices.

<a id="opengate_data.utils.utils.build_headers"></a>

---
#### build\_headers

```python
def build_headers(client_headers: dict | None,
                  *,
                  accept: str | None = None,
                  content_type: str | None = None) -> dict
```

Build request headers starting from client headers (auth preserved)
and optionally overriding Accept / Content-Type.

This function NEVER mutates client headers.

**Arguments**:

- `client_headers` _dict | None_ - The headers of the client, holding the
  authentication. They are copied, never modified.
- `accept` _str | None_ - The Accept header to set. Left untouched if None.
- `content_type` _str | None_ - The Content-Type header to set. Left
  untouched if None.
  

**Returns**:

- `dict` - A new set of headers.

<a id="opengate_data.utils"></a>

## opengate\_data.utils

