code
stringlengths
1
18.2k
def from_parameter(self, parameter): """Set internal raw state from parameter.""" if not isinstance(parameter, Parameter): raise Exception("parameter::from_parameter_wrong_object") self.raw = parameter.raw
def from_int(value): """Create raw out of position vlaue.""" if not isinstance(value, int): raise PyVLXException("value_has_to_be_int") if not Parameter.is_valid_int(value): raise PyVLXException("value_out_of_range") return bytes([value >> 8 & 255, value & 255])
def is_valid_int(value): """Test if value can be rendered out of int.""" if 0 <= value <= Parameter.MAX: # This includes ON and OFF return True if value == Parameter.UNKNOWN_VALUE: return True if value == Parameter.CURRENT_POSITION: return True return False
def from_raw(raw): """Test if raw packets are valid for initialization of Position.""" if not isinstance(raw, bytes): raise PyVLXException("Position::raw_must_be_bytes") if len(raw) != 2: raise PyVLXException("Position::raw_must_be_two_bytes") if raw != Position.from_int(Position.CURRENT_POSITION) and \ raw != Position...
def from_percent(position_percent): """Create raw value out of percent position.""" if not isinstance(position_percent, int): raise PyVLXException("Position::position_percent_has_to_be_int") if position_percent < 0: raise PyVLXException("Position::position_percent_has_to_be_positive") if position_percent > 100: raise P...
def product(self): """Return product as human readable string.""" if self.product_group == 14 and self.product_type == 3: return "KLF 200" return "Unknown Product: {}:{}".format(self.product_group, self.product_type)
def get_payload(self): """Return Payload.""" ret = self._software_version ret += bytes([self.hardware_version, self.product_group, self.product_type]) return ret
def from_payload(self, payload): """Init frame from binary data.""" self._software_version = payload[0:6] self.hardware_version = payload[6] self.product_group = payload[7] self.product_type = payload[8]
def get_payload(self): """Return Payload.""" ret = bytes([self.session_id >> 8 & 255, self.session_id & 255]) ret += bytes([self.originator.value]) ret += bytes([self.priority.value]) ret += bytes([self.scene_id]) ret += bytes([self.velocity.value]) return ret
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.originator = Originator(payload[2]) self.priority = Priority(payload[3]) self.scene_id = payload[4] self.velocity = Velocity(payload[5])
def get_payload(self): """Return Payload.""" ret = bytes([self.status.value]) ret += bytes([self.session_id >> 8 & 255, self.session_id & 255]) return ret
def from_payload(self, payload): """Init frame from binary data.""" self.status = ActivateSceneConfirmationStatus(payload[0]) self.session_id = payload[1]*256 + payload[2]
def get_payload(self): """Return Payload.""" # Session id ret = bytes([self.session_id >> 8 & 255, self.session_id & 255]) ret += bytes([self.originator.value]) ret += bytes([self.priority.value]) ret += bytes([0]) # ParameterActive pointing to main parameter (MP) # FPI 1+2 ret += bytes([0]) ret += bytes([0]) # Main pa...
padding ret += bytes([len(self.node_ids)]) # index array count ret += bytes(self.node_ids) + bytes(20-len(self.node_ids)) # Priority Level Lock ret += bytes([0]) # Priority Level information 1+2 ret += bytes([0, 0]) # Locktime ret += bytes([0]) return ret
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.originator = Originator(payload[2]) self.priority = Priority(payload[3]) len_node_ids = payload[41] if len_node_ids > 20: raise PyVLXException("command_send_request_wrong_node_length") self.node_ids = ...
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.status = CommandSendConfirmationStatus(payload[2])
def get_payload(self): """Return Payload.""" ret = bytes([self.session_id >> 8 & 255, self.session_id & 255]) ret += bytes([self.status_id]) ret += bytes([self.index_id]) ret += bytes([self.node_parameter]) ret += bytes([self.parameter_value >> 8 & 255, self.parameter_value & 255]) # XXX: Missing implementation of run_...
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.status_id = payload[2] self.index_id = payload[3] self.node_parameter = payload[4] self.parameter_value = payload[5]*256 + payload[6]
def get_payload(self): """Return Payload.""" ret = bytes([self.session_id >> 8 & 255, self.session_id & 255]) ret += bytes([self.index_id]) ret += bytes([self.node_parameter]) ret += bytes([self.seconds >> 8 & 255, self.seconds & 255]) return ret
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.index_id = payload[2] self.node_parameter = payload[3] self.seconds = payload[4]*256 + payload[5]
async def main(loop): """Log packets from Bus.""" # Setting debug PYVLXLOG.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) PYVLXLOG.addHandler(stream_handler) # Connecting to KLF 200 pyvlx = PyVLX('pyvlx.yaml', loop=loop) await pyvlx.load_scenes() await pyvlx.load...
async def rename(self, name): """Change name of node.""" set_node_name = SetNodeName(pyvlx=self.pyvlx, node_id=self.node_id, name=name) await set_node_name.do_api_call() if not set_node_name.success: raise PyVLXException("Unable to rename node") self.name = name
async def set_position(self, position, wait_for_completion=True): """Set window to desired position. Parameters: * position: Position object containing the target position. * wait_for_completion: If set, function will return after device has reached target position. """ command_send = CommandSend( pyvlx=self.pyvlx, wai...
async def open(self, wait_for_completion=True): """Open window. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=0), wait_for_completion=wait_for_completion)
async def close(self, wait_for_completion=True): """Close window. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=100), wait_for_completion=wait_for_completion)
async def stop(self, wait_for_completion=True): """Stop window. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=CurrentPosition(), wait_for_completion=wait_for_completion)
def _get_sampleset(model): """Return sampleset of a model or `None` if undefined. Model could be a real model or evaluated sampleset.""" if isinstance(model, Model): if hasattr(model, 'sampleset'): w = model.sampleset() else: w = None else: w = model # Already a sampleset return w
def _merge_sampleset(model1, model2): """Simple merge of samplesets.""" w1 = _get_sampleset(model1) w2 = _get_sampleset(model2) return merge_wavelengths(w1, w2)
def _shift_wavelengths(model1, model2): """One of the models is either ``RedshiftScaleFactor`` or ``Scale``. Possible combos:: RedshiftScaleFactor | Model Scale | Model Model | Scale """ if isinstance(model1, _models.RedshiftScaleFactor): val = _get_sampleset(model2) if val is None: w = val else: w = model1.inverse(val...
def get_waveset(model): """Get optimal wavelengths for sampling a given model. Parameters ---------- model : `~astropy.modeling.Model` Model. Returns ------- waveset : array-like or `None` Optimal wavelengths. `None` if undefined. Raises ------ synphot.exceptions.SynphotError Invalid model. """ if not isinstance(model,...
def _get_meta(model): """Return metadata of a model. Model could be a real model or evaluated metadata.""" if isinstance(model, Model): w = model.meta else: w = model # Already metadata return w
def _merge_meta(model1, model2): """Simple merge of samplesets.""" w1 = _get_meta(model1) w2 = _get_meta(model2) return metadata.merge(w1, w2, metadata_conflicts='silent')
def get_metadata(model): """Get metadata for a given model. Parameters ---------- model : `~astropy.modeling.Model` Model. Returns ------- metadata : dict Metadata for the model. Raises ------ synphot.exceptions.SynphotError Invalid model. """ if not isinstance(model, Model): raise SynphotError('{0} is not a model.'.fo...
def lambda_max(self): """Peak wavelength in Angstrom when the curve is expressed as power density.""" return ((const.b_wien.value / self.temperature) * u.m).to(u.AA).value
def bounding_box(self, factor=10.0): """Tuple defining the default ``bounding_box`` limits, ``(x_low, x_high)``. .. math:: x_{\\textnormal{low}} = 0 x_{\\textnormal{high}} = \\log(\\lambda_{\\textnormal{max}} \\;\ (1 + \\textnormal{factor})) Parameters ---------- factor : float Used to calculate ``x_high``. """ w0 = se...
def sampleset(self, factor_bbox=10.0, num=1000): """Return ``x`` array that samples the feature. Parameters ---------- factor_bbox : float Factor for ``bounding_box`` calculations. num : int Number of points to generate. """ w1, w2 = self.bounding_box(factor=factor_bbox) if self._n_models == 1: w = np.logspace(w1, w2, ...
def evaluate(x, temperature): """Evaluate the model. Parameters ---------- x : number or ndarray Wavelengths in Angstrom. temperature : number Temperature in Kelvin. Returns ------- y : number or ndarray Blackbody radiation in PHOTLAM per steradian. """ if ASTROPY_LT_2_0: from astropy.analytic_functions.blackbody impor...
(bbnu_flux * u.sr).to( units.PHOTLAM, u.spectral_density(wave)) / u.sr # PHOTLAM/sr # Restore Numpy settings np.seterr(**old_np_err_cfg) return bbflux.value
def evaluate(self, x, temperature): """Evaluate the model. Parameters ---------- x : number or ndarray Wavelengths in Angstrom. temperature : number Temperature in Kelvin. Returns ------- y : number or ndarray Blackbody radiation in PHOTLAM. """ bbflux = super(BlackBodyNorm1D, self).evaluate(x, temperature) return bbfl...
def _calc_sampleset(w1, w2, step, minimal): """Calculate sampleset for each model.""" if minimal: arr = [w1 - step, w1, w2, w2 + step] else: arr = np.arange(w1 - step, w2 + step + step, step) return arr
def sampleset(self, step=0.01, minimal=False): """Return ``x`` array that samples the feature. Parameters ---------- step : float Distance of first and last points w.r.t. bounding box. minimal : bool Only return the minimal points needed to define the box; i.e., box edges and a point outside on each side. """ w1, w2 = ...
w = list(map(partial( self._calc_sampleset, step=step, minimal=minimal), w1, w2)) return np.asarray(w)
def evaluate(self, x, *args): """One dimensional constant flux model function. Parameters ---------- x : number or ndarray Wavelengths in Angstrom. Returns ------- y : number or ndarray Flux in PHOTLAM. """ a = (self.amplitude * np.ones_like(x)) * self._flux_unit y = units.convert_flux(x, a, units.PHOTLAM) return y.val...
def _process_neg_flux(self, x, y): """Remove negative flux.""" if self._keep_neg: # Nothing to do return y old_y = None if np.isscalar(y): # pragma: no cover if y < 0: n_neg = 1 old_x = x old_y = y y = 0 else: x = np.asarray(x) # In case input is just pure list y = np.asarray(y) i = np.where(y < 0) n_neg = len(i[0]) if
n_neg > 0: old_x = x[i] old_y = y[i] y[i] = 0 if old_y is not None: warn_str = ('{0} bin(s) contained negative flux or throughput' '; it/they will be set to zero.'.format(n_neg)) warn_str += '\n points: {0}\n lookup_table: {1}'.format( old_x, old_y) # Extra info self.meta['warnings'].update({'NegativeFlux': warn_str}) ...
def evaluate(self, inputs): """Evaluate the model. Parameters ---------- inputs : number or ndarray Wavelengths in same unit as ``points``. Returns ------- y : number or ndarray Flux or throughput in same unit as ``lookup_table``. """ y = super(Empirical1D, self).evaluate(inputs) # Assume NaN at both ends need to be ex...
to ExtinctionModel1D x = np.squeeze(self.points) if np.isscalar(y): # pragma: no cover if inputs < x[0]: y = self.lookup_table[0] elif inputs > x[-1]: y = self.lookup_table[-1] else: y[inputs < x[0]] = self.lookup_table[0] y[inputs > x[-1]] = self.lookup_table[-1] return self._process_neg_flux(inputs, y)
def evaluate(x, amplitude, mean, stddev): """ GaussianAbsorption1D model function. """ return 1.0 - Gaussian1D.evaluate(x, amplitude, mean, stddev)
def fit_deriv(x, amplitude, mean, stddev): """ GaussianAbsorption1D model function derivatives. """ import operator return list(map( operator.neg, Gaussian1D.fit_deriv(x, amplitude, mean, stddev)))
def sampleset(self, factor_step=0.05, **kwargs): """Return ``x`` array that samples the feature. Parameters ---------- factor_step : float Factor for sample step calculation. The step is calculated using ``factor_step * self.fwhm``. kwargs : dict Keyword(s) for ``bounding_box`` calculation. """ w1, w2 = self.bounding_b...
def evaluate(self, x, *args): """Return flux in PHOTLAM. Assume input wavelength is in Angstrom.""" xx = x / self.x_0 y = (self.amplitude * xx ** (-self.alpha)) * self._flux_unit flux = units.convert_flux(x, y, units.PHOTLAM) return flux.value
def sampleset(self): """Return ``x`` array that samples the feature.""" x1, x4 = self.bounding_box dw = self.width * 0.5 x2 = self.x_0 - dw x3 = self.x_0 + dw if self._n_models == 1: w = [x1, x2, x3, x4] else: w = list(zip(x1, x2, x3, x4)) return np.asarray(w)
def get_payment_request(self, cart, request): """ From the given request, add a snippet to the page. """ try: self.charge(cart, request) thank_you_url = OrderModel.objects.get_latest_url() js_expression = 'window.location.href="{}";'.format(thank_you_url) return js_expression except (KeyError, stripe.error.StripeError)...
def charge(self, cart, request): """ Use the Stripe token from the request and charge immediately. This view is invoked by the Javascript function `scope.charge()` delivered by `get_payment_request`. """ token_id = cart.extra['payment_extra_data']['token_id'] if LooseVersion(SHOP_VERSION) < LooseVersion('0.11'): charge...
transfer_group=order.get_number(), description=settings.SHOP_STRIPE['PURCHASE_DESCRIPTION'], ) if charge['status'] == 'succeeded': order.populate_from_cart(cart, request) order.add_stripe_payment(charge) order.save() if charge['status'] != 'succeeded': msg = "Stripe returned status '{status}' for id: {id}" raise stripe...
def refund_payment(self): """ Refund the payment using Stripe's refunding API. """ Money = MoneyMaker(self.currency) filter_kwargs = { 'transaction_id__startswith': 'ch_', 'payment_method': StripePayment.namespace, } for payment in self.orderpayment_set.filter(**filter_kwargs): refund = stripe.Refund.create(charge=paym...
def create(self): """ Create an instance of the US Weather Forecast Service with typical starting settings. """ self.service.create() # Set env vars for immediate use zone_id = predix.config.get_env_key(self.use_class, 'zone_id') zone = self.service.settings.data['zone']['http-header-value'] os.environ[zone_id] = zone ...
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app. """ # Add this service to list of services manifest...
manifest.write_manifest()
def _create_in_progress(self): """ Creating this service is handled asynchronously so this method will simply check if the create is in progress. If it is not in progress, we could probably infer it either failed or succeeded. """ instance = self.service.service.get_instance(self.service.name) if (instance['last_operat...
def create(self, max_wait=180, **kwargs): """ Create an instance of the Predix Cache Service with they typical starting settings. :param max_wait: service is created asynchronously, so will only wait this number of seconds before giving up. """ # Will need to wait for the service to be provisioned before can add # serv...
0: time.sleep(1) max_wait -= 1 # Now get the service env (via service keys) cfg = self.service._get_service_config() self.service.settings.save(cfg) host = predix.config.get_env_key(self.use_class, 'host') os.environ[host] = self.service.settings.data['host'] password = predix.config.get_env_key(self.use_class, 'passwo...
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: A predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app. """ manifest.add_service(self.service.name) host = p...
def _get_uri(self): """ Will return the uri for an existing instance. """ if not self.service.exists(): logging.warning("Service does not yet exist.") return self.service.settings.data['uri']
def _get_zone_id(self): """ Will return the zone id for an existing instance. """ if not self.service.exists(): logging.warning("Service does not yet exist.") return self.service.settings.data['zone']['http-header-value']
def create(self): """ Create an instance of the Access Control Service with the typical starting settings. """ self.service.create() # Set environment variables for immediate use predix.config.set_env_value(self.use_class, 'uri', self._get_uri()) predix.config.set_env_value(self.use_class, 'zone_id', self._get_zone_id(...
def grant_client(self, client_id): """ Grant the given client id all the scopes and authorities needed to work with the access control service. """ zone = self.service.settings.data['zone']['oauth-scope'] scopes = ['openid', zone, 'acs.policies.read', 'acs.attributes.read', 'acs.policies.write', 'acs.attributes.write']...
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app. """ # Add this service to list of services manifest...
manifest.write_manifest()
def get(self, path): """ Generic GET with headers """ uri = self.config.get_target() + path headers = self._get_headers() logging.debug("URI=GET " + str(uri)) logging.debug("HEADERS=" + str(headers)) response = self.session.get(uri, headers=headers) if response.status_code == 200: return response.json() elif response.s...
def post(self, path, data): """ Generic POST with headers """ uri = self.config.get_target() + path headers = self._post_headers() logging.debug("URI=POST " + str(uri)) logging.debug("HEADERS=" + str(headers)) logging.debug("BODY=" + str(data)) response = self.session.post(uri, headers=headers, data=json.dumps(data)) i...
def delete(self, path, data=None, params=None): """ Generic DELETE with headers """ uri = self.config.get_target() + path headers = { 'Authorization': self.config.get_access_token() } logging.debug("URI=DELETE " + str(uri)) logging.debug("HEADERS=" + str(headers)) response = self.session.delete( uri, headers=headers, p...
def get_orgs(self): """ Returns a flat list of the names for the organizations user belongs. """ orgs = [] for resource in self._get_orgs()['resources']: orgs.append(resource['entity']['name']) return orgs
def get_apps(self): """ Returns a flat list of the names for the apps in the organization. """ apps = [] for resource in self._get_apps()['resources']: apps.append(resource['entity']['name']) return apps
def add_user(self, user_name, role='user'): """ Calls CF's associate user with org. Valid roles include `user`, `auditor`, `manager`,`billing_manager` """ role_uri = self._get_role_uri(role=role) return self.api.put(path=role_uri, data={'username': user_name})
def remove_user(self, user_name, role): """ Calls CF's remove user with org """ role_uri = self._get_role_uri(role=role) return self.api.delete(path=role_uri, data={'username': user_name})
def add_message(self, id, body, tags=False): """ add messages to the rx_queue :param id: str message Id :param body: str the message body :param tags: dict[string->string] tags to be associated with the message :return: self """ if not tags: tags = {} try: self._tx_queue_lock.acquire() self._tx_queue.append( EventHub_p...
def publish_queue(self): """ Publish all messages that have been added to the queue for configured protocol :return: None """ self.last_send_time = time.time() try: self._tx_queue_lock.acquire() start_length = len(self._rx_queue) publish_amount = len(self._tx_queue) if self.config.protocol == PublisherConfig.Protocol.G...
self._rx_queue
def ack_generator(self): """ generator for acks to yield messages to the user in a async configuration :return: messages as they come in """ if self.config.is_sync(): logging.warning('cant use generator on a sync publisher') return while self._run_ack_generator: while len(self._rx_queue) != 0: logging.debug('yielding t...
def _auto_send(self): """ auto send blocking function, when the interval or the message size has been reached, publish :return: """ while True: if time.time() - self.last_send_time > self.config.async_auto_send_interval_millis or \ len(self._tx_queue) >= self.config.async_auto_send_amount: self.publish_queue()
def _generate_publish_headers(self): """ generate the headers for the connection to event hub service based on the provided config :return: {} headers """ headers = { 'predix-zone-id': self.eventhub_client.zone_id } token = self.eventhub_client.service._get_bearer_token() if self.config.is_grpc(): headers['authorizatio...
headers['sync-acks'] = 'false' headers['send-acks-interval'] = str(self.config.async_cache_ack_interval_millis) headers['acks'] = str(self.config.async_enable_acks).lower() headers['nacks'] = str(self.config.async_enable_nacks_only).lower() headers['cache-acks'] = str(self.config.async_cache_acks_and_nacks).lower() ret...
def _publisher_callback(self, publish_ack): """ publisher callback that grpc and web socket can pass messages to address the received message onto the queue :param publish_ack: EventHub_pb2.Ack the ack received from either wss or grpc :return: None """ logging.debug("ack received: " + str(publish_ack).replace('\n', ' '...
def _init_grpc_publisher(self): """ initialize the grpc publisher, builds the stub and then starts the grpc manager :return: None """ self._stub = EventHub_pb2_grpc.PublisherStub(channel=self._channel) self.grpc_manager = Eventhub.GrpcManager(stub_call=self._stub.send, on_msg_callback=self._publisher_callback, metadata...
def _publish_queue_grpc(self): """ send the messages in the tx queue to the GRPC manager :return: None """ messages = EventHub_pb2.Messages(msg=self._tx_queue) publish_request = EventHub_pb2.PublishRequest(messages=messages) self.grpc_manager.send_message(publish_request)
def _publish_queue_wss(self): """ send the messages down the web socket connection as a json object :return: None """ msg = [] for m in self._tx_queue: msg.append({'id': m.id, 'body': m.body, 'zone_id': m.zone_id}) self._ws.send(json.dumps(msg), opcode=websocket.ABNF.OPCODE_BINARY)
def _init_publisher_ws(self): """ Create a new web socket connection with proper headers. """ logging.debug("Initializing new web socket connection.") url = ('wss://%s/v1/stream/messages/' % self.eventhub_client.host) headers = self._generate_publish_headers() logging.debug("URL=" + str(url)) logging.debug("HEADERS=" +...
def _on_ws_message(self, ws, message): """ on_message callback of websocket class, load the message into a dict and then update an Ack Object with the results :param ws: web socket connection that the message was received on :param message: web socket message in text form :return: None """ logging.debug(message) json_l...
key, value) self._publisher_callback(ack)
def create(self): """ Create an instance of the Parking Planning Service with the typical starting settings. """ self.service.create() os.environ[self.__module__ + '.uri'] = self.service.settings.data['url'] os.environ[self.__module__ + '.zone_id'] = self.get_predix_zone_id()
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app. """ # Add this service to list of services manifest...
def read_manifest(self, encrypted=None): """ Read an existing manifest. """ with open(self.manifest_path, 'r') as input_file: self.manifest = yaml.safe_load(input_file) if 'env' not in self.manifest: self.manifest['env'] = {} if 'services' not in self.manifest: self.manifest['services'] = [] # If manifest is encrypted,...
f = Fernet(key) for var in self.manifest['env'].keys(): value = f.decrypt(bytes(self.manifest['env'][var], 'utf-8')) self.manifest['env'][var] = value.decode('utf-8') self.app_name = self.manifest['applications'][0]['name'] input_file.close()
def create_manifest(self): """ Create a new manifest and write it to disk. """ self.manifest = {} self.manifest['applications'] = [{'name': self.app_name}] self.manifest['services'] = [] self.manifest['env'] = { 'PREDIXPY_VERSION': str(predix.version), } self.write_manifest()
def _get_encrypted_manifest(self): """ Returns contents of the manifest where environment variables that are secret will be encrypted without modifying the existing state in memory which will remain unencrypted. """ key = predix.config.get_crypt_key(self.manifest_key) f = Fernet(key) manifest = copy.deepcopy(self.manif...
def write_manifest(self, manifest_path=None, encrypted=None): """ Write manifest to disk. :param manifest_path: write to a different location :param encrypted: write with env data encrypted """ manifest_path = manifest_path or self.manifest_path self.manifest['env']['PREDIXPY_VERSION'] = str(predix.version) with open(m...
def add_env_var(self, key, value): """ Add the given key / value as another environment variable. """ self.manifest['env'][key] = value os.environ[key] = str(value)
def add_service(self, service_name): """ Add the given service to the manifest. """ if service_name not in self.manifest['services']: self.manifest['services'].append(service_name)
def set_os_environ(self): """ Will load any environment variables found in the manifest file into the current process for use by applications. When apps run in cloud foundry this would happen automatically. """ for key in self.manifest['env'].keys(): os.environ[key] = str(self.manifest['env'][key])