MCPcopy
hub / github.com/spaceandtimefdn/SxT-Python-SDK / save

Method save

src/spaceandtime/sxtuser.py:306–358  ·  view source on GitHub ↗

Save dotenv (.env) file containing variables: API_URL, USERID, USER_PUBLIC_KEY, USER_PRIVATE_KEY, optionally USER_JOINCODE, USER_KEY_SCHEME, APP_PREFIX. Args: \n dotenv_file -- full path to .env file, defaulting to ./users/{user_id}.env if not supplied. Note: to minimi

(self, dotenv_file:Path = None)

Source from the content-addressed store, hash-verified

304
305
306 def save(self, dotenv_file:Path = None):
307 """Save dotenv (.env) file containing variables: API_URL, USERID, USER_PUBLIC_KEY, USER_PRIVATE_KEY, optionally USER_JOINCODE, USER_KEY_SCHEME, APP_PREFIX.
308
309 Args: \n
310 dotenv_file -- full path to .env file, defaulting to ./users/{user_id}.env if not supplied. Note: to minimize losing keys, overwrites are disallowed.
311
312 Results: \n
313 None
314 """
315 if not dotenv_file: dotenv_file = self.recommended_filename
316 dotenv_file = Path(self.replace_all(str(dotenv_file))).resolve()
317 if dotenv_file.exists():
318 self.logger.error(f'File Exists: {dotenv_file}\nTo minimize lost keys, file over-writes are not allowed.')
319 raise FileExistsError('To minimize lost keys, file over-writes are not allowed.')
320
321 try:
322 fieldmap = { 'api_url':'API_URL'
323 ,'user_id':'USERID'
324 ,'private_key':'USER_PRIVATE_KEY'
325 ,'public_key':'USER_PUBLIC_KEY'
326 }
327
328 # build insert string for env file
329 hdr = '# -------- Below was added by the SxT SDK'
330 lines = [hdr]
331 for pyname, envname in fieldmap.items():
332 lines.append( f'{envname}="{ getattr(self, pyname) }"' )
333
334 dotenv_file = Path(dotenv_file)
335 dotenv_file.parent.mkdir(parents=True, exist_ok=True)
336 i=0
337
338 if dotenv_file.exists():
339 with open(dotenv_file.resolve(), 'r') as fh: # open file
340 for line in fh.readlines(): # read each line
341 val = str(line).split('=')[0].strip() # get text before "="
342 if val and val != hdr and \
343 val not in list(fieldmap.values()): # if text doesn't exist in fieldmap values
344 lines.insert(i,str(line).strip()) # add it, so it gets written to new file
345 i+=1 # preserve the original order of the file
346
347 # create (overwrite) file
348 with open(dotenv_file.resolve(), 'w') as fh:
349 fh.write( '\n'.join(lines) )
350
351 self.logger.debug(f'saved dotenv file to: { dotenv_file }')
352 self.logger.warning('THE SAVED FILE CONTAINS PRIVATE KEYS!')
353 return None
354
355 except Exception as err:
356 msg = f'Attempting to write new .env file to {dotenv_file}\n{ str(err) }'
357 self.logger.error(msg)
358 raise FileNotFoundError(msg)
359
360
361 def replace_all(self, mainstr:str, replace_map:dict = None) -> str:

Callers 2

Calls 2

replace_allMethod · 0.95
existsMethod · 0.45

Tested by 1