sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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 L...
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`.
entailment
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.ord...
Refund the payment using Stripe's refunding API.
entailment
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.setti...
Create an instance of the US Weather Forecast Service with typical starting settings.
entailment
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...
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.
entailment
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_inst...
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.
entailment
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 t...
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.
entailment
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 ...
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.
entailment
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']
Will return the uri for an existing instance.
entailment
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']
Will return the zone id for an existing instance.
entailment
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.c...
Create an instance of the Access Control Service with the typical starting settings.
entailment
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', '...
Grant the given client id all the scopes and authorities needed to work with the access control service.
entailment
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...
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.
entailment
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) ...
Generic GET with headers
entailment
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)) r...
Generic POST with headers
entailment
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("...
Generic DELETE with headers
entailment
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
Returns a flat list of the names for the organizations user belongs.
entailment
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
Returns a flat list of the names for the apps in the organization.
entailment
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})
Calls CF's associate user with org. Valid roles include `user`, `auditor`, `manager`,`billing_manager`
entailment
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})
Calls CF's remove user with org
entailment
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: ta...
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
entailment
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) publis...
Publish all messages that have been added to the queue for configured protocol :return: None
entailment
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_...
generator for acks to yield messages to the user in a async configuration :return: messages as they come in
entailment
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...
auto send blocking function, when the interval or the message size has been reached, publish :return:
entailment
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...
generate the headers for the connection to event hub service based on the provided config :return: {} headers
entailment
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.deb...
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
entailment
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, ...
initialize the grpc publisher, builds the stub and then starts the grpc manager :return: None
entailment
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_...
send the messages in the tx queue to the GRPC manager :return: None
entailment
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), opcod...
send the messages down the web socket connection as a json object :return: None
entailment
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() ...
Create a new web socket connection with proper headers.
entailment
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 ...
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
entailment
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_pred...
Create an instance of the Parking Planning Service with the typical starting settings.
entailment
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...
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.
entailment
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 'servic...
Read an existing manifest.
entailment
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(pred...
Create a new manifest and write it to disk.
entailment
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) ...
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.
entailment
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['e...
Write manifest to disk. :param manifest_path: write to a different location :param encrypted: write with env data encrypted
entailment
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)
Add the given key / value as another environment variable.
entailment
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)
Add the given service to the manifest.
entailment
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(): ...
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.
entailment
def get_client_id(self): """ Return the client id that should have all the needed scopes and authorities for the services in this manifest. """ self._client_id = predix.config.get_env_value(predix.app.Manifest, 'client_id') return self._client_id
Return the client id that should have all the needed scopes and authorities for the services in this manifest.
entailment
def get_client_secret(self): """ Return the client secret that should correspond with the client id. """ self._client_secret = predix.config.get_env_value(predix.app.Manifest, 'client_secret') return self._client_secret
Return the client secret that should correspond with the client id.
entailment
def get_timeseries(self, *args, **kwargs): """ Returns an instance of the Time Series Service. """ import predix.data.timeseries ts = predix.data.timeseries.TimeSeries(*args, **kwargs) return ts
Returns an instance of the Time Series Service.
entailment
def get_asset(self): """ Returns an instance of the Asset Service. """ import predix.data.asset asset = predix.data.asset.Asset() return asset
Returns an instance of the Asset Service.
entailment
def get_uaa(self): """ Returns an insstance of the UAA Service. """ import predix.security.uaa uaa = predix.security.uaa.UserAccountAuthentication() return uaa
Returns an insstance of the UAA Service.
entailment
def get_acs(self): """ Returns an instance of the Asset Control Service. """ import predix.security.acs acs = predix.security.acs.AccessControl() return acs
Returns an instance of the Asset Control Service.
entailment
def get_weather(self): """ Returns an instance of the Weather Service. """ import predix.data.weather weather = predix.data.weather.WeatherForecast() return weather
Returns an instance of the Weather Service.
entailment
def get_weather_forecast_days(self, latitude, longitude, days=1, frequency=1, reading_type=None): """ Return the weather forecast for a given location. :: results = ws.get_weather_forecast_days(lat, long) for w in results['hits']: print w['st...
Return the weather forecast for a given location. :: results = ws.get_weather_forecast_days(lat, long) for w in results['hits']: print w['start_datetime_local'] print w['reading_type'], w['reading_value'] For description of reading types: ...
entailment
def get_weather_forecast(self, latitude, longitude, start, end, frequency=1, reading_type=None): """ Return the weather forecast for a given location for specific datetime specified in UTC format. :: results = ws.get_weather_forecast(lat, long, start, end) ...
Return the weather forecast for a given location for specific datetime specified in UTC format. :: results = ws.get_weather_forecast(lat, long, start, end) for w in results['hits']: print w['start_datetime_local'] print w['reading_type'], '=', w[...
entailment
def _generate_name(self, space, service_name, plan_name): """ Can generate a name based on the space, service name and plan. """ return str.join('-', [space, service_name, plan_name]).lower()
Can generate a name based on the space, service name and plan.
entailment
def _get_config_path(self): """ Return a sensible configuration path for caching config settings. """ org = self.service.space.org.name space = self.service.space.name name = self.name return "~/.predix/%s/%s/%s.json" % (org, space, name)
Return a sensible configuration path for caching config settings.
entailment
def _create_service(self, parameters={}, **kwargs): """ Create a Cloud Foundry service that has custom parameters. """ logging.debug("_create_service()") logging.debug(str.join(',', [self.service_name, self.plan_name, self.name, str(parameters)])) return self...
Create a Cloud Foundry service that has custom parameters.
entailment
def _delete_service(self, service_only=False): """ Delete a Cloud Foundry service and any associations. """ logging.debug('_delete_service()') return self.service.delete_service(self.service_name)
Delete a Cloud Foundry service and any associations.
entailment
def _get_or_create_service_key(self): """ Get a service key or create one if needed. """ keys = self.service._get_service_keys(self.name) for key in keys['resources']: if key['entity']['name'] == self.service_name: return self.service.get_service_key(s...
Get a service key or create one if needed.
entailment
def _get_service_config(self): """ Will get configuration for the service from a service key. """ key = self._get_or_create_service_key() config = {} config['service_key'] = [{'name': self.name}] config.update(key['entity']['credentials']) return config
Will get configuration for the service from a service key.
entailment
def create(self, parameters={}, create_keys=True, **kwargs): """ Create the service. """ # Create the service cs = self._create_service(parameters=parameters, **kwargs) # Create the service key to get config details and # store in local cache file. if cre...
Create the service.
entailment
def _get_or_create_uaa(self, uaa): """ Returns a valid UAA instance for performing administrative functions on services. """ if isinstance(uaa, predix.admin.uaa.UserAccountAuthentication): return uaa logging.debug("Initializing a new UAA") return pred...
Returns a valid UAA instance for performing administrative functions on services.
entailment
def create(self, parameters={}, **kwargs): """ Create an instance of the US Weather Forecast Service with typical starting settings. """ # Add parameter during create for UAA issuer uri = self.uaa.service.settings.data['uri'] + '/oauth/token' parameters["trustedIs...
Create an instance of the US Weather Forecast Service with typical starting settings.
entailment
def create(self): """ Create an instance of the Time Series Service with the typical starting settings. """ self.service.create() os.environ[predix.config.get_env_key(self.use_class, 'host')] = self.get_eventhub_host() os.environ[predix.config.get_env_key(self.us...
Create an instance of the Time Series Service with the typical starting settings.
entailment
def grant_client(self, client_id, publish=False, subscribe=False, publish_protocol=None, publish_topics=None, subscribe_topics=None, scope_prefix='predix-event-hub', **kwargs): """ Grant the given client id all the scopes and authorities needed to work with the eventhub serv...
Grant the given client id all the scopes and authorities needed to work with the eventhub service.
entailment
def get_eventhub_host(self): """ returns the publish grpc endpoint for ingestion. """ for protocol in self.service.settings.data['publish']['protocol_details']: if protocol['protocol'] == 'grpc': return protocol['uri'][0:protocol['uri'].index(':')]
returns the publish grpc endpoint for ingestion.
entailment
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...
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.
entailment
def _get_host(self): """ Returns the host address for an instance of Blob Store service from environment inspection. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) host = services['predix-blobstore'][0]['credentials...
Returns the host address for an instance of Blob Store service from environment inspection.
entailment
def _get_access_key_id(self): """ Returns the access key for an instance of Blob Store service from environment inspection. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) return services['predix-blobstore'][0]['cred...
Returns the access key for an instance of Blob Store service from environment inspection.
entailment
def list_objects(self, bucket_name=None, **kwargs): """ This method is primarily for illustration and just calls the boto3 client implementation of list_objects but is a common task for first time Predix BlobStore users. """ if not bucket_name: bucket_name = self.bucket_...
This method is primarily for illustration and just calls the boto3 client implementation of list_objects but is a common task for first time Predix BlobStore users.
entailment
def upload_file(self, src_filepath, dest_filename=None, bucket_name=None, **kwargs): """ This method is primarily for illustration and just calls the boto3 client implementation of upload_file but is a common task for first time Predix BlobStore users. """ if...
This method is primarily for illustration and just calls the boto3 client implementation of upload_file but is a common task for first time Predix BlobStore users.
entailment
def _get_cloud_foundry_config(self): """ Reads the local cf CLI cache stored in the users home directory. """ config = os.path.expanduser(self.config_file) if not os.path.exists(config): raise CloudFoundryLoginError('You must run `cf login` to authenticate') ...
Reads the local cf CLI cache stored in the users home directory.
entailment
def get_organization_guid(self): """ Returns the GUID for the organization currently targeted. """ if 'PREDIX_ORGANIZATION_GUID' in os.environ: return os.environ['PREDIX_ORGANIZATION_GUID'] else: info = self._get_organization_info() for key in ...
Returns the GUID for the organization currently targeted.
entailment
def get_space_guid(self): """ Returns the GUID for the space currently targeted. Can be set by environment variable with PREDIX_SPACE_GUID. Can be determined by ~/.cf/config.json. """ if 'PREDIX_SPACE_GUID' in os.environ: return os.environ['PREDIX_SPACE_GUID'...
Returns the GUID for the space currently targeted. Can be set by environment variable with PREDIX_SPACE_GUID. Can be determined by ~/.cf/config.json.
entailment
def get_crypt_key(key_path): """ Get the user's PredixPy manifest key. Generate and store one if not yet generated. """ key_path = os.path.expanduser(key_path) if os.path.exists(key_path): with open(key_path, 'r') as data: key = data.read() else: key = Fernet.gen...
Get the user's PredixPy manifest key. Generate and store one if not yet generated.
entailment
def get_env_key(obj, key=None): """ Return environment variable key to use for lookups within a namespace represented by the package name. For example, any varialbes for predix.security.uaa are stored as PREDIX_SECURITY_UAA_KEY """ return str.join('_', [obj.__module__.replace('.','_').upper...
Return environment variable key to use for lookups within a namespace represented by the package name. For example, any varialbes for predix.security.uaa are stored as PREDIX_SECURITY_UAA_KEY
entailment
def get_env_value(obj, attribute): """ Returns the environment variable value for the attribute of the given object. For example `get_env_value(predix.security.uaa, 'uri')` will return value of environment variable PREDIX_SECURITY_UAA_URI. """ varname = get_env_key(obj, attribute) var ...
Returns the environment variable value for the attribute of the given object. For example `get_env_value(predix.security.uaa, 'uri')` will return value of environment variable PREDIX_SECURITY_UAA_URI.
entailment
def set_env_value(obj, attribute, value): """ Set the environment variable value for the attribute of the given object. For example, `set_env_value(predix.security.uaa, 'uri', 'http://...')` will set the environment variable PREDIX_SECURITY_UAA_URI to the given uri. """ varname = get_en...
Set the environment variable value for the attribute of the given object. For example, `set_env_value(predix.security.uaa, 'uri', 'http://...')` will set the environment variable PREDIX_SECURITY_UAA_URI to the given uri.
entailment
def get_instance_guid(self, service_name): """ Returns the GUID for the service instance with the given name. """ summary = self.space.get_space_summary() for service in summary['services']: if service['name'] == service_name: return service['g...
Returns the GUID for the service instance with the given name.
entailment
def _get_service_bindings(self, service_name): """ Return the service bindings for the service instance. """ instance = self.get_instance(service_name) return self.api.get(instance['service_bindings_url'])
Return the service bindings for the service instance.
entailment
def delete_service_bindings(self, service_name): """ Remove service bindings to applications. """ instance = self.get_instance(service_name) return self.api.delete(instance['service_bindings_url'])
Remove service bindings to applications.
entailment
def _get_service_keys(self, service_name): """ Return the service keys for the given service. """ guid = self.get_instance_guid(service_name) uri = "/v2/service_instances/%s/service_keys" % (guid) return self.api.get(uri)
Return the service keys for the given service.
entailment
def get_service_keys(self, service_name): """ Returns a flat list of the names of the service keys for the given service. """ keys = [] for key in self._get_service_keys(service_name)['resources']: keys.append(key['entity']['name']) return keys
Returns a flat list of the names of the service keys for the given service.
entailment
def get_service_key(self, service_name, key_name): """ Returns the service key details. Similar to `cf service-key`. """ for key in self._get_service_keys(service_name)['resources']: if key_name == key['entity']['name']: guid = key['metadata']['guid']...
Returns the service key details. Similar to `cf service-key`.
entailment
def create_service_key(self, service_name, key_name): """ Create a service key for the given service. """ if self.has_key(service_name, key_name): logging.warning("Reusing existing service key %s" % (key_name)) return self.get_service_key(service_name, key_name) ...
Create a service key for the given service.
entailment
def delete_service_key(self, service_name, key_name): """ Delete a service key for the given service. """ key = self.get_service_key(service_name, key_name) logging.info("Deleting service key %s for service %s" % (key, service_name)) return self.api.delete(key['metadata']...
Delete a service key for the given service.
entailment
def get_instance(self, service_name): """ Retrieves a service instance with the given name. """ for resource in self.space._get_instances(): if resource['entity']['name'] == service_name: return resource['entity']
Retrieves a service instance with the given name.
entailment
def get_service_plan_for_service(self, service_name): """ Return the service plans available for a given service. """ services = self.get_services() for service in services['resources']: if service['entity']['label'] == service_name: response = self.ap...
Return the service plans available for a given service.
entailment
def get_service_plan_guid(self, service_name, plan_name): """ Return the service plan GUID for the given service / plan. """ for plan in self.get_service_plan_for_service(service_name): if plan['entity']['name'] == plan_name: return plan['metadata']['guid'] ...
Return the service plan GUID for the given service / plan.
entailment
def create_service(self, service_type, plan_name, service_name, params, async=False, **kwargs): """ Create a service instance. """ if self.space.has_service_with_name(service_name): logging.warning("Service already exists with that name.") return self....
Create a service instance.
entailment
def delete_service(self, service_name, params=None): """ Delete the service of the given name. It may fail if there are any service keys or app bindings. Use purge() if you want to delete it all. """ if not self.space.has_service_with_name(service_name): log...
Delete the service of the given name. It may fail if there are any service keys or app bindings. Use purge() if you want to delete it all.
entailment
def _get_query_uri(self): """ Returns the URI endpoint for performing queries of a Predix Time Series instance from environment inspection. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) predix_timeseries = services...
Returns the URI endpoint for performing queries of a Predix Time Series instance from environment inspection.
entailment
def _get_query_zone_id(self): """ Returns the ZoneId for performing queries of a Predix Time Series instance from environment inspection. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) predix_timeseries = services['...
Returns the ZoneId for performing queries of a Predix Time Series instance from environment inspection.
entailment
def _get_datapoints(self, params): """ Will make a direct REST call with the given json body payload to get datapoints. """ url = self.query_uri + '/v1/datapoints' return self.service._get(url, params=params)
Will make a direct REST call with the given json body payload to get datapoints.
entailment
def get_values(self, *args, **kwargs): """ Convenience method that for simple single tag queries will return just the values to be iterated on. """ if isinstance(args[0], list): raise ValueError("Can only get_values() for a single tag.") response = self.get_d...
Convenience method that for simple single tag queries will return just the values to be iterated on.
entailment
def get_datapoints(self, tags, start=None, end=None, order=None, limit=None, qualities=None, attributes=None, measurement=None, aggregations=None, post=False): """ Returns all of the datapoints that match the given query. - tags: list or string identifying the name/t...
Returns all of the datapoints that match the given query. - tags: list or string identifying the name/tag (ie. "temp") - start: data after this, absolute or relative (ie. '1w-ago' or 1494015972386) - end: data before this value - order: ascending (asc) or d...
entailment
def _create_connection(self): """ Create a new websocket connection with proper headers. """ logging.debug("Initializing new websocket connection.") headers = { 'Authorization': self.service._get_bearer_token(), 'Predix-Zone-Id': self.ingest_zone_id, ...
Create a new websocket connection with proper headers.
entailment
def _get_websocket(self, reuse=True): """ Reuse existing connection or create a new connection. """ # Check if still connected if self.ws and reuse: if self.ws.connected: return self.ws logging.debug("Stale connection, reconnecting.") ...
Reuse existing connection or create a new connection.
entailment
def _send_to_timeseries(self, message): """ Establish or reuse socket connection and send the given message to the timeseries service. """ logging.debug("MESSAGE=" + str(message)) result = None try: ws = self._get_websocket() ws.send(json....
Establish or reuse socket connection and send the given message to the timeseries service.
entailment
def queue(self, name, value, quality=None, timestamp=None, attributes=None): """ To reduce network traffic, you can buffer datapoints and then flush() anything in the queue. :param name: the name / label / tag for sensor data :param value: the sensor reading or valu...
To reduce network traffic, you can buffer datapoints and then flush() anything in the queue. :param name: the name / label / tag for sensor data :param value: the sensor reading or value to record :param quality: the quality value, use the constants BAD, GOOD, etc. (option...
entailment
def send(self, name=None, value=None, **kwargs): """ Can accept a name/tag and value to be queued and then send anything in the queue to the time series service. Optional parameters include setting quality, timestamp, or attributes. See spec for queue() for complete list of opt...
Can accept a name/tag and value to be queued and then send anything in the queue to the time series service. Optional parameters include setting quality, timestamp, or attributes. See spec for queue() for complete list of options. Example of sending a batch of values: que...
entailment
def execute(self, statement, *args, **kwargs): """ This convenience method will execute the query passed in as is. For more complex functionality you may want to use the sqlalchemy engine directly, but this serves as an example implementation. :param select_query: SQL statement...
This convenience method will execute the query passed in as is. For more complex functionality you may want to use the sqlalchemy engine directly, but this serves as an example implementation. :param select_query: SQL statement to execute that will identify the resultset of interes...
entailment
def shutdown(self): """ Shutdown the client, shutdown the sub clients and stop the health checker :return: None """ self._run_health_checker = False if self.publisher is not None: self.publisher.shutdown() if self.subscriber is not None: s...
Shutdown the client, shutdown the sub clients and stop the health checker :return: None
entailment
def get_service_env_value(self, key): """ Get a env variable as defined by the service admin :param key: the base of the key to use :return: the env if it exists """ service_key = predix.config.get_env_key(self, key) value = os.environ[service_key] if not ...
Get a env variable as defined by the service admin :param key: the base of the key to use :return: the env if it exists
entailment
def _init_channel(self): """ build the grpc channel used for both publisher and subscriber :return: None """ host = self._get_host() port = self._get_grpc_port() if 'TLS_PEM_FILE' in os.environ: with open(os.environ['TLS_PEM_FILE'], mode='rb') as f: ...
build the grpc channel used for both publisher and subscriber :return: None
entailment
def _init_health_checker(self): """ start the health checker stub and start a thread to ping it every 30 seconds :return: None """ stub = Health_pb2_grpc.HealthStub(channel=self._channel) self._health_check = stub.Check health_check_thread = threading.Thread(targe...
start the health checker stub and start a thread to ping it every 30 seconds :return: None
entailment