1
1
import os
2
+ import sys
2
3
import ast
3
4
import iris
4
5
import inspect
5
6
import xmltodict
6
7
import pkg_resources
8
+ import importlib
7
9
8
10
class _Utils ():
9
11
@staticmethod
@@ -186,20 +188,17 @@ def migrate(filename=None,root_path=None):
186
188
* key: the name of the production
187
189
* value: a dictionary containing the settings for the production
188
190
"""
189
- # try to load the settings file
190
- if filename :
191
- import sys
192
- path = None
193
- # check if the filename is absolute or relative
194
- if os .path .isabs (filename ):
195
- path = os .path .dirname (filename )
191
+ try :
192
+ # if the filename is not provided
193
+ if filename is None :
194
+ settings = importlib .import_module ('settings' )
196
195
else :
197
- raise ValueError ( "The filename must be absolute" )
198
- # add the path to the system path to the beginning
199
- sys . path . append ( path )
200
- import settings
201
- # get the path of the settings file
202
- path = os . path . dirname ( inspect . getfile ( settings ))
196
+ # import the settings file
197
+ settings = _Utils . import_module_from_path ( 'settings' , filename )
198
+ # get the path of the settings file
199
+ path = os . path . dirname ( inspect . getfile ( settings ))
200
+ except ModuleNotFoundError as e :
201
+ raise ModuleNotFoundError ( " settings.py not found" ) from e
203
202
try :
204
203
# set the classes settings
205
204
_Utils .set_classes_settings (settings .CLASSES ,path )
@@ -211,7 +210,22 @@ def migrate(filename=None,root_path=None):
211
210
except AttributeError :
212
211
print ("No productions to register" )
213
212
214
-
213
+ @staticmethod
214
+ def import_module_from_path (module_name , file_path ):
215
+ if not os .path .isabs (file_path ):
216
+ file_path = os .path .abspath (file_path )
217
+ # check is a file is persent at the path
218
+ if not os .path .isfile (file_path ):
219
+ # append settings.py to the path
220
+ file_path = os .path .join (file_path ,'settings.py' )
221
+
222
+ spec = importlib .util .spec_from_file_location (module_name , file_path )
223
+ if spec is None :
224
+ raise ImportError (f"Cannot find module named { module_name } at { file_path } " )
225
+
226
+ module = importlib .util .module_from_spec (spec )
227
+ sys .modules [module_name ] = module
228
+ return module
215
229
216
230
@staticmethod
217
231
def set_classes_settings (class_items ,root_path = None ):
0 commit comments