Skip to content

Commit c2efd80

Browse files
committed
Add _iris module for IRIS namespace management and refactor imports
1 parent 00dcecc commit c2efd80

File tree

9 files changed

+67
-48
lines changed

9 files changed

+67
-48
lines changed

src/iop/_async_request.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import asyncio
2-
import iris
2+
from . import _iris
33
from typing import Any, Optional, Union
44
from iop._dispatch import dispatch_deserializer, dispatch_serializer
55
from iop._message import _Message as Message
@@ -24,6 +24,7 @@ def __init__(self, target: str, request: Union[Message, Any],
2424

2525
async def send(self) -> None:
2626
# init parameters
27+
iris = _iris.get_iris()
2728
message_header_id = iris.ref()
2829
queue_name = iris.ref()
2930
end_time = iris.ref()
@@ -46,6 +47,7 @@ async def send(self) -> None:
4647
self.set_result(self._response)
4748

4849
def is_done(self) -> None:
50+
iris = _iris.get_iris()
4951
response = iris.ref()
5052
status = self._iris_handle.dispatchIsRequestDone(self.timeout, self._end_time,
5153
self._queue_name, self._message_header_id,

src/iop/_business_host.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from inspect import getsource
22
from typing import Any,List, Optional, Tuple, Union
33

4-
import iris
4+
from . import _iris
55

66
from iop._common import _Common
77
from iop._message import _Message as Message
@@ -109,6 +109,7 @@ def _validate_target_request(self, target_request: List[Tuple[str, Union[Message
109109

110110
def _create_call_structure(self, target: str, request: Union[Message, Any]) -> Any:
111111
"""Create an Ens.CallStructure object for the request."""
112+
iris = _iris.get_iris()
112113
call = iris.cls("Ens.CallStructure")._New()
113114
call.TargetDispatchName = target
114115
call.Request = dispatch_serializer(request)

src/iop/_cli.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77
import sys
88
from typing import Optional, Callable
99
from importlib.metadata import version
10-
1110
from iop._director import _Director
1211
from iop._utils import _Utils
1312

13+
1414
class CommandType(Enum):
1515
DEFAULT = auto()
1616
LIST = auto()
@@ -46,11 +46,16 @@ class CommandArgs:
4646
test: Optional[str] = None
4747
classname: Optional[str] = None
4848
body: Optional[str] = None
49+
namespace: Optional[str] = None
4950

5051
class Command:
5152
def __init__(self, args: CommandArgs):
5253
self.args = args
5354

55+
if self.args.namespace and self.args.namespace != 'not_set':
56+
# set environment variable IRISNAMESPACE
57+
os.environ['IRISNAMESPACE'] = self.args.namespace
58+
5459
def execute(self) -> None:
5560
command_type = self._determine_command_type()
5661
command_handlers = {
@@ -182,6 +187,9 @@ def create_parser() -> argparse.ArgumentParser:
182187
test = main_parser.add_argument_group('test arguments')
183188
test.add_argument('-C', '--classname', help='test classname', nargs='?', const='not_set')
184189
test.add_argument('-B', '--body', help='test body', nargs='?', const='not_set')
190+
191+
namespace = main_parser.add_argument_group('namespace arguments')
192+
namespace.add_argument('-n', '--namespace', help='set namespace', nargs='?', const='not_set')
185193

186194
return main_parser
187195

src/iop/_common.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import traceback
44
from typing import Any, ClassVar, List, Optional, Tuple
55

6-
import iris
6+
from . import _iris
77

88
from iop._log_manager import LogManager, logging
99

@@ -285,6 +285,7 @@ def log_assert(self, message: str) -> None:
285285
Parameters:
286286
message: a string that is written to the log.
287287
"""
288+
iris = _iris.get_iris()
288289
current_class, current_method = self._log()
289290
iris.cls("Ens.Util.Log").LogAssert(current_class, current_method, message)
290291

src/iop/_director.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import asyncio
22
import datetime
33
import functools
4-
import iris
4+
from . import _iris
55
import intersystems_iris.dbapi._DBAPI as irisdbapi
66
import signal
77
from dataclasses import dataclass
@@ -55,7 +55,7 @@ def create_business_service(target):
5555
Returns:
5656
an object that contains an instance of IRISBusinessService
5757
"""
58-
iris_object = iris.cls("IOP.Director").dispatchCreateBusinessService(target)
58+
iris_object = _iris.get_iris().cls("IOP.Director").dispatchCreateBusinessService(target)
5959
return iris_object
6060

6161
@staticmethod
@@ -69,7 +69,7 @@ def create_python_business_service(target):
6969
Returns:
7070
an object that contains an instance of IRISBusinessService
7171
"""
72-
iris_object = iris.cls("IOP.Director").dispatchCreateBusinessService(target)
72+
iris_object = _iris.get_iris().cls("IOP.Director").dispatchCreateBusinessService(target)
7373
return iris_object.GetClass()
7474

7575
### List of function to manage the production
@@ -102,37 +102,37 @@ async def _start_production_async(production_name=None, handler=None):
102102
def start_production(production_name=None):
103103
if production_name is None or production_name == '':
104104
production_name = _Director.get_default_production()
105-
iris.cls('Ens.Director').StartProduction(production_name)
105+
_iris.get_iris().cls('Ens.Director').StartProduction(production_name)
106106

107107
### stop production
108108
@staticmethod
109109
def stop_production():
110-
iris.cls('Ens.Director').StopProduction()
110+
_iris.get_iris().cls('Ens.Director').StopProduction()
111111

112112
### restart production
113113
@staticmethod
114114
def restart_production():
115-
iris.cls('Ens.Director').RestartProduction()
115+
_iris.get_iris().cls('Ens.Director').RestartProduction()
116116

117117
### shutdown production
118118
@staticmethod
119119
def shutdown_production():
120-
iris.cls('Ens.Director').StopProduction(10,1)
120+
_iris.get_iris().cls('Ens.Director').StopProduction(10,1)
121121

122122
### update production
123123
@staticmethod
124124
def update_production():
125-
iris.cls('Ens.Director').UpdateProduction()
125+
_iris.get_iris().cls('Ens.Director').UpdateProduction()
126126

127127
### list production
128128
@staticmethod
129129
def list_productions():
130-
return iris.cls('IOP.Director').dispatchListProductions()
130+
return _iris.get_iris().cls('IOP.Director').dispatchListProductions()
131131

132132
### status production
133133
@staticmethod
134134
def status_production():
135-
dikt = iris.cls('IOP.Director').StatusProduction()
135+
dikt = _iris.get_iris().cls('IOP.Director').StatusProduction()
136136
if dikt['Production'] is None or dikt['Production'] == '':
137137
dikt['Production'] = _Director.get_default_production()
138138
return dikt
@@ -141,13 +141,13 @@ def status_production():
141141
@staticmethod
142142
def set_default_production(production_name=''):
143143
#set ^Ens.Configuration("SuperUser","LastProduction")
144-
glb = iris.gref("^Ens.Configuration")
144+
glb = _iris.get_iris().gref("^Ens.Configuration")
145145
glb['csp', "LastProduction"] = production_name
146146

147147
### get default production
148148
@staticmethod
149149
def get_default_production():
150-
glb = iris.gref("^Ens.Configuration")
150+
glb = _iris.get_iris().gref("^Ens.Configuration")
151151
default_production_name = glb['csp', "LastProduction"]
152152
if default_production_name is None or default_production_name == '':
153153
default_production_name = 'Not defined'
@@ -257,28 +257,28 @@ def test_component(target,message=None,classname=None,body=None):
257257
body: the body of the message
258258
"""
259259
if not message:
260-
message = iris.cls('Ens.Request')._New()
260+
message = _iris.get_iris().cls('Ens.Request')._New()
261261
if classname:
262262
# if classname start with 'iris.' then create an iris object
263263
if classname.startswith('iris.'):
264264
# strip the iris. prefix
265265
classname = classname[5:]
266266
if body:
267-
message = iris.cls(classname)._New(body)
267+
message = _iris.get_iris().cls(classname)._New(body)
268268
else:
269-
message = iris.cls(classname)._New()
269+
message = _iris.get_iris().cls(classname)._New()
270270
# else create a python object
271271
else:
272272
# python message are casted to Grongier.PEX.Message
273-
message = iris.cls("IOP.Message")._New()
273+
message = _iris.get_iris().cls("IOP.Message")._New()
274274
message.classname = classname
275275
if body:
276276
message.json = body
277277
else:
278278
message.json = _Utils.string_to_stream("{}")
279279
# serialize the message
280280
serial_message = dispatch_serializer(message)
281-
response = iris.cls('IOP.Utils').dispatchTestComponent(target,serial_message)
281+
response = _iris.get_iris().cls('IOP.Utils').dispatchTestComponent(target,serial_message)
282282
try:
283283
deserialized_response = dispatch_deserializer(response)
284284
except ImportError as e:

src/iop/_iris.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import os
2+
3+
def get_iris(namespace:str=None)->'iris':
4+
if namespace:
5+
os.environ['IRISNAMESPACE'] = namespace
6+
import iris
7+
return iris

src/iop/_log_manager.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import traceback
2-
import iris
2+
from . import _iris
33
import logging
44
from typing import Optional, Tuple
55

@@ -41,11 +41,11 @@ def __init__(self, to_console: bool = False):
4141

4242
# Map Python logging levels to IRIS logging methods
4343
self.level_map = {
44-
logging.DEBUG: iris.cls("Ens.Util.Log").LogTrace,
45-
logging.INFO: iris.cls("Ens.Util.Log").LogInfo,
46-
logging.WARNING: iris.cls("Ens.Util.Log").LogWarning,
47-
logging.ERROR: iris.cls("Ens.Util.Log").LogError,
48-
logging.CRITICAL: iris.cls("Ens.Util.Log").LogAlert,
44+
logging.DEBUG: _iris.get_iris().cls("Ens.Util.Log").LogTrace,
45+
logging.INFO: _iris.get_iris().cls("Ens.Util.Log").LogInfo,
46+
logging.WARNING: _iris.get_iris().cls("Ens.Util.Log").LogWarning,
47+
logging.ERROR: _iris.get_iris().cls("Ens.Util.Log").LogError,
48+
logging.CRITICAL: _iris.get_iris().cls("Ens.Util.Log").LogAlert,
4949
}
5050
# Map Python logging levels to IRIS logging Console level
5151
self.level_map_console = {
@@ -76,8 +76,8 @@ def emit(self, record: logging.LogRecord) -> None:
7676
class_name = record.class_name if hasattr(record, "class_name") else record.name
7777
method_name = record.method_name if hasattr(record, "method_name") else record.funcName
7878
if self.to_console or (hasattr(record, "to_console") and record.to_console):
79-
iris.cls("%SYS.System").WriteToConsoleLog(self.format(record),
79+
_iris.get_iris().cls("%SYS.System").WriteToConsoleLog(self.format(record),
8080
0,self.level_map_console.get(record.levelno, 0),class_name+"."+method_name)
8181
else:
82-
log_func = self.level_map.get(record.levelno, iris.cls("Ens.Util.Log").LogInfo)
82+
log_func = self.level_map.get(record.levelno, _iris.get_iris().cls("Ens.Util.Log").LogInfo)
8383
log_func(class_name, method_name, self.format(record))

src/iop/_serialization.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from dataclasses import asdict, is_dataclass
88
from typing import Any, Dict, Type
99

10-
import iris
10+
from . import _iris
1111
from pydantic import BaseModel, TypeAdapter, ValidationError
1212

1313
from iop._message import _PydanticPickleMessage
@@ -37,17 +37,17 @@ def _convert_to_json_safe(obj: Any) -> Any:
3737
raise SerializationError(f"Object {obj} must be a Pydantic model or dataclass")
3838

3939
@staticmethod
40-
def serialize(message: Any, use_pickle: bool = False) -> iris.cls:
40+
def serialize(message: Any, use_pickle: bool = False) -> Any:
4141
"""Serializes a message to IRIS format."""
4242
if isinstance(message, _PydanticPickleMessage) or use_pickle:
4343
return MessageSerializer._serialize_pickle(message)
4444
return MessageSerializer._serialize_json(message)
4545

4646
@staticmethod
47-
def _serialize_json(message: Any) -> iris.cls:
47+
def _serialize_json(message: Any) -> Any:
4848
json_string = MessageSerializer._convert_to_json_safe(message)
4949

50-
msg = iris.cls('IOP.Message')._New()
50+
msg = _iris.get_iris().cls('IOP.Message')._New()
5151
msg.classname = f"{message.__class__.__module__}.{message.__class__.__name__}"
5252

5353
if hasattr(msg, 'buffer') and len(json_string) > msg.buffer:
@@ -57,13 +57,13 @@ def _serialize_json(message: Any) -> iris.cls:
5757
return msg
5858

5959
@staticmethod
60-
def deserialize(serial: iris.cls, use_pickle: bool = False) -> Any:
60+
def deserialize(serial: Any, use_pickle: bool = False) -> Any:
6161
if use_pickle:
6262
return MessageSerializer._deserialize_pickle(serial)
6363
return MessageSerializer._deserialize_json(serial)
6464

6565
@staticmethod
66-
def _deserialize_json(serial: iris.cls) -> Any:
66+
def _deserialize_json(serial: Any) -> Any:
6767
if not serial.classname:
6868
raise SerializationError("JSON message malformed, must include classname")
6969

@@ -88,15 +88,15 @@ def _deserialize_json(serial: iris.cls) -> Any:
8888
raise SerializationError(f"Failed to deserialize JSON: {str(e)}")
8989

9090
@staticmethod
91-
def _serialize_pickle(message: Any) -> iris.cls:
91+
def _serialize_pickle(message: Any) -> Any:
9292
pickle_string = codecs.encode(pickle.dumps(message), "base64").decode()
93-
msg = iris.cls('IOP.PickleMessage')._New()
93+
msg = _iris.get_iris().cls('IOP.PickleMessage')._New()
9494
msg.classname = f"{message.__class__.__module__}.{message.__class__.__name__}"
9595
msg.jstr = _Utils.string_to_stream(pickle_string)
9696
return msg
9797

9898
@staticmethod
99-
def _deserialize_pickle(serial: iris.cls) -> Any:
99+
def _deserialize_pickle(serial: Any) -> Any:
100100
string = _Utils.stream_to_string(serial.jstr)
101101
return pickle.loads(codecs.decode(string.encode(), "base64"))
102102

0 commit comments

Comments
 (0)