partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
TransferCoordinator.add_failure_cleanup
Adds a callback to call upon failure
s3transfer/futures.py
def add_failure_cleanup(self, function, *args, **kwargs): """Adds a callback to call upon failure""" with self._failure_cleanups_lock: self._failure_cleanups.append( FunctionContainer(function, *args, **kwargs))
def add_failure_cleanup(self, function, *args, **kwargs): """Adds a callback to call upon failure""" with self._failure_cleanups_lock: self._failure_cleanups.append( FunctionContainer(function, *args, **kwargs))
[ "Adds", "a", "callback", "to", "call", "upon", "failure" ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/futures.py#L353-L357
[ "def", "add_failure_cleanup", "(", "self", ",", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "self", ".", "_failure_cleanups_lock", ":", "self", ".", "_failure_cleanups", ".", "append", "(", "FunctionContainer", "(", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
TransferCoordinator.announce_done
Announce that future is done running and run associated callbacks This will run any failure cleanups if the transfer failed if not they have not been run, allows the result() to be unblocked, and will run any done callbacks associated to the TransferFuture if they have not already been ran.
s3transfer/futures.py
def announce_done(self): """Announce that future is done running and run associated callbacks This will run any failure cleanups if the transfer failed if not they have not been run, allows the result() to be unblocked, and will run any done callbacks associated to the TransferFuture if they have not already been ran. """ if self.status != 'success': self._run_failure_cleanups() self._done_event.set() self._run_done_callbacks()
def announce_done(self): """Announce that future is done running and run associated callbacks This will run any failure cleanups if the transfer failed if not they have not been run, allows the result() to be unblocked, and will run any done callbacks associated to the TransferFuture if they have not already been ran. """ if self.status != 'success': self._run_failure_cleanups() self._done_event.set() self._run_done_callbacks()
[ "Announce", "that", "future", "is", "done", "running", "and", "run", "associated", "callbacks" ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/futures.py#L359-L370
[ "def", "announce_done", "(", "self", ")", ":", "if", "self", ".", "status", "!=", "'success'", ":", "self", ".", "_run_failure_cleanups", "(", ")", "self", ".", "_done_event", ".", "set", "(", ")", "self", ".", "_run_done_callbacks", "(", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
BoundedExecutor.submit
Submit a task to complete :type task: s3transfer.tasks.Task :param task: The task to run __call__ on :type tag: s3transfer.futures.TaskTag :param tag: An optional tag to associate to the task. This is used to override which semaphore to use. :type block: boolean :param block: True if to wait till it is possible to submit a task. False, if not to wait and raise an error if not able to submit a task. :returns: The future assocaited to the submitted task
s3transfer/futures.py
def submit(self, task, tag=None, block=True): """Submit a task to complete :type task: s3transfer.tasks.Task :param task: The task to run __call__ on :type tag: s3transfer.futures.TaskTag :param tag: An optional tag to associate to the task. This is used to override which semaphore to use. :type block: boolean :param block: True if to wait till it is possible to submit a task. False, if not to wait and raise an error if not able to submit a task. :returns: The future assocaited to the submitted task """ semaphore = self._semaphore # If a tag was provided, use the semaphore associated to that # tag. if tag: semaphore = self._tag_semaphores[tag] # Call acquire on the semaphore. acquire_token = semaphore.acquire(task.transfer_id, block) # Create a callback to invoke when task is done in order to call # release on the semaphore. release_callback = FunctionContainer( semaphore.release, task.transfer_id, acquire_token) # Submit the task to the underlying executor. future = ExecutorFuture(self._executor.submit(task)) # Add the Semaphore.release() callback to the future such that # it is invoked once the future completes. future.add_done_callback(release_callback) return future
def submit(self, task, tag=None, block=True): """Submit a task to complete :type task: s3transfer.tasks.Task :param task: The task to run __call__ on :type tag: s3transfer.futures.TaskTag :param tag: An optional tag to associate to the task. This is used to override which semaphore to use. :type block: boolean :param block: True if to wait till it is possible to submit a task. False, if not to wait and raise an error if not able to submit a task. :returns: The future assocaited to the submitted task """ semaphore = self._semaphore # If a tag was provided, use the semaphore associated to that # tag. if tag: semaphore = self._tag_semaphores[tag] # Call acquire on the semaphore. acquire_token = semaphore.acquire(task.transfer_id, block) # Create a callback to invoke when task is done in order to call # release on the semaphore. release_callback = FunctionContainer( semaphore.release, task.transfer_id, acquire_token) # Submit the task to the underlying executor. future = ExecutorFuture(self._executor.submit(task)) # Add the Semaphore.release() callback to the future such that # it is invoked once the future completes. future.add_done_callback(release_callback) return future
[ "Submit", "a", "task", "to", "complete" ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/futures.py#L436-L471
[ "def", "submit", "(", "self", ",", "task", ",", "tag", "=", "None", ",", "block", "=", "True", ")", ":", "semaphore", "=", "self", ".", "_semaphore", "# If a tag was provided, use the semaphore associated to that", "# tag.", "if", "tag", ":", "semaphore", "=", "self", ".", "_tag_semaphores", "[", "tag", "]", "# Call acquire on the semaphore.", "acquire_token", "=", "semaphore", ".", "acquire", "(", "task", ".", "transfer_id", ",", "block", ")", "# Create a callback to invoke when task is done in order to call", "# release on the semaphore.", "release_callback", "=", "FunctionContainer", "(", "semaphore", ".", "release", ",", "task", ".", "transfer_id", ",", "acquire_token", ")", "# Submit the task to the underlying executor.", "future", "=", "ExecutorFuture", "(", "self", ".", "_executor", ".", "submit", "(", "task", ")", ")", "# Add the Semaphore.release() callback to the future such that", "# it is invoked once the future completes.", "future", ".", "add_done_callback", "(", "release_callback", ")", "return", "future" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
ExecutorFuture.add_done_callback
Adds a callback to be completed once future is done :parm fn: A callable that takes no arguments. Note that is different than concurrent.futures.Future.add_done_callback that requires a single argument for the future.
s3transfer/futures.py
def add_done_callback(self, fn): """Adds a callback to be completed once future is done :parm fn: A callable that takes no arguments. Note that is different than concurrent.futures.Future.add_done_callback that requires a single argument for the future. """ # The done callback for concurrent.futures.Future will always pass a # the future in as the only argument. So we need to create the # proper signature wrapper that will invoke the callback provided. def done_callback(future_passed_to_callback): return fn() self._future.add_done_callback(done_callback)
def add_done_callback(self, fn): """Adds a callback to be completed once future is done :parm fn: A callable that takes no arguments. Note that is different than concurrent.futures.Future.add_done_callback that requires a single argument for the future. """ # The done callback for concurrent.futures.Future will always pass a # the future in as the only argument. So we need to create the # proper signature wrapper that will invoke the callback provided. def done_callback(future_passed_to_callback): return fn() self._future.add_done_callback(done_callback)
[ "Adds", "a", "callback", "to", "be", "completed", "once", "future", "is", "done" ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/futures.py#L494-L506
[ "def", "add_done_callback", "(", "self", ",", "fn", ")", ":", "# The done callback for concurrent.futures.Future will always pass a", "# the future in as the only argument. So we need to create the", "# proper signature wrapper that will invoke the callback provided.", "def", "done_callback", "(", "future_passed_to_callback", ")", ":", "return", "fn", "(", ")", "self", ".", "_future", ".", "add_done_callback", "(", "done_callback", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
DeleteSubmissionTask._submit
:param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associated with the transfer manager :type osutil: s3transfer.utils.OSUtil :param osutil: The os utility associated to the transfer manager :type request_executor: s3transfer.futures.BoundedExecutor :param request_executor: The request executor associated with the transfer manager :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for
s3transfer/delete.py
def _submit(self, client, request_executor, transfer_future, **kwargs): """ :param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associated with the transfer manager :type osutil: s3transfer.utils.OSUtil :param osutil: The os utility associated to the transfer manager :type request_executor: s3transfer.futures.BoundedExecutor :param request_executor: The request executor associated with the transfer manager :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for """ call_args = transfer_future.meta.call_args self._transfer_coordinator.submit( request_executor, DeleteObjectTask( transfer_coordinator=self._transfer_coordinator, main_kwargs={ 'client': client, 'bucket': call_args.bucket, 'key': call_args.key, 'extra_args': call_args.extra_args, }, is_final=True ) )
def _submit(self, client, request_executor, transfer_future, **kwargs): """ :param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associated with the transfer manager :type osutil: s3transfer.utils.OSUtil :param osutil: The os utility associated to the transfer manager :type request_executor: s3transfer.futures.BoundedExecutor :param request_executor: The request executor associated with the transfer manager :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for """ call_args = transfer_future.meta.call_args self._transfer_coordinator.submit( request_executor, DeleteObjectTask( transfer_coordinator=self._transfer_coordinator, main_kwargs={ 'client': client, 'bucket': call_args.bucket, 'key': call_args.key, 'extra_args': call_args.extra_args, }, is_final=True ) )
[ ":", "param", "client", ":", "The", "client", "associated", "with", "the", "transfer", "manager" ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/delete.py#L20-L53
[ "def", "_submit", "(", "self", ",", "client", ",", "request_executor", ",", "transfer_future", ",", "*", "*", "kwargs", ")", ":", "call_args", "=", "transfer_future", ".", "meta", ".", "call_args", "self", ".", "_transfer_coordinator", ".", "submit", "(", "request_executor", ",", "DeleteObjectTask", "(", "transfer_coordinator", "=", "self", ".", "_transfer_coordinator", ",", "main_kwargs", "=", "{", "'client'", ":", "client", ",", "'bucket'", ":", "call_args", ".", "bucket", ",", "'key'", ":", "call_args", ".", "key", ",", "'extra_args'", ":", "call_args", ".", "extra_args", ",", "}", ",", "is_final", "=", "True", ")", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
CopySubmissionTask._submit
:param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associated with the transfer manager :type osutil: s3transfer.utils.OSUtil :param osutil: The os utility associated to the transfer manager :type request_executor: s3transfer.futures.BoundedExecutor :param request_executor: The request executor associated with the transfer manager :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for
s3transfer/copies.py
def _submit(self, client, config, osutil, request_executor, transfer_future): """ :param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associated with the transfer manager :type osutil: s3transfer.utils.OSUtil :param osutil: The os utility associated to the transfer manager :type request_executor: s3transfer.futures.BoundedExecutor :param request_executor: The request executor associated with the transfer manager :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for """ # Determine the size if it was not provided if transfer_future.meta.size is None: # If a size was not provided figure out the size for the # user. Note that we will only use the client provided to # the TransferManager. If the object is outside of the region # of the client, they may have to provide the file size themselves # with a completely new client. call_args = transfer_future.meta.call_args head_object_request = \ self._get_head_object_request_from_copy_source( call_args.copy_source) extra_args = call_args.extra_args # Map any values that may be used in the head object that is # used in the copy object for param, value in extra_args.items(): if param in self.EXTRA_ARGS_TO_HEAD_ARGS_MAPPING: head_object_request[ self.EXTRA_ARGS_TO_HEAD_ARGS_MAPPING[param]] = value response = call_args.source_client.head_object( **head_object_request) transfer_future.meta.provide_transfer_size( response['ContentLength']) # If it is greater than threshold do a multipart copy, otherwise # do a regular copy object. if transfer_future.meta.size < config.multipart_threshold: self._submit_copy_request( client, config, osutil, request_executor, transfer_future) else: self._submit_multipart_request( client, config, osutil, request_executor, transfer_future)
def _submit(self, client, config, osutil, request_executor, transfer_future): """ :param client: The client associated with the transfer manager :type config: s3transfer.manager.TransferConfig :param config: The transfer config associated with the transfer manager :type osutil: s3transfer.utils.OSUtil :param osutil: The os utility associated to the transfer manager :type request_executor: s3transfer.futures.BoundedExecutor :param request_executor: The request executor associated with the transfer manager :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for """ # Determine the size if it was not provided if transfer_future.meta.size is None: # If a size was not provided figure out the size for the # user. Note that we will only use the client provided to # the TransferManager. If the object is outside of the region # of the client, they may have to provide the file size themselves # with a completely new client. call_args = transfer_future.meta.call_args head_object_request = \ self._get_head_object_request_from_copy_source( call_args.copy_source) extra_args = call_args.extra_args # Map any values that may be used in the head object that is # used in the copy object for param, value in extra_args.items(): if param in self.EXTRA_ARGS_TO_HEAD_ARGS_MAPPING: head_object_request[ self.EXTRA_ARGS_TO_HEAD_ARGS_MAPPING[param]] = value response = call_args.source_client.head_object( **head_object_request) transfer_future.meta.provide_transfer_size( response['ContentLength']) # If it is greater than threshold do a multipart copy, otherwise # do a regular copy object. if transfer_future.meta.size < config.multipart_threshold: self._submit_copy_request( client, config, osutil, request_executor, transfer_future) else: self._submit_multipart_request( client, config, osutil, request_executor, transfer_future)
[ ":", "param", "client", ":", "The", "client", "associated", "with", "the", "transfer", "manager" ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/copies.py#L69-L121
[ "def", "_submit", "(", "self", ",", "client", ",", "config", ",", "osutil", ",", "request_executor", ",", "transfer_future", ")", ":", "# Determine the size if it was not provided", "if", "transfer_future", ".", "meta", ".", "size", "is", "None", ":", "# If a size was not provided figure out the size for the", "# user. Note that we will only use the client provided to", "# the TransferManager. If the object is outside of the region", "# of the client, they may have to provide the file size themselves", "# with a completely new client.", "call_args", "=", "transfer_future", ".", "meta", ".", "call_args", "head_object_request", "=", "self", ".", "_get_head_object_request_from_copy_source", "(", "call_args", ".", "copy_source", ")", "extra_args", "=", "call_args", ".", "extra_args", "# Map any values that may be used in the head object that is", "# used in the copy object", "for", "param", ",", "value", "in", "extra_args", ".", "items", "(", ")", ":", "if", "param", "in", "self", ".", "EXTRA_ARGS_TO_HEAD_ARGS_MAPPING", ":", "head_object_request", "[", "self", ".", "EXTRA_ARGS_TO_HEAD_ARGS_MAPPING", "[", "param", "]", "]", "=", "value", "response", "=", "call_args", ".", "source_client", ".", "head_object", "(", "*", "*", "head_object_request", ")", "transfer_future", ".", "meta", ".", "provide_transfer_size", "(", "response", "[", "'ContentLength'", "]", ")", "# If it is greater than threshold do a multipart copy, otherwise", "# do a regular copy object.", "if", "transfer_future", ".", "meta", ".", "size", "<", "config", ".", "multipart_threshold", ":", "self", ".", "_submit_copy_request", "(", "client", ",", "config", ",", "osutil", ",", "request_executor", ",", "transfer_future", ")", "else", ":", "self", ".", "_submit_multipart_request", "(", "client", ",", "config", ",", "osutil", ",", "request_executor", ",", "transfer_future", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
CopyObjectTask._main
:param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to copy to :param key: The name of the key to copy to :param extra_args: A dictionary of any extra arguments that may be used in the upload. :param callbacks: List of callbacks to call after copy :param size: The size of the transfer. This value is passed into the callbacks
s3transfer/copies.py
def _main(self, client, copy_source, bucket, key, extra_args, callbacks, size): """ :param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to copy to :param key: The name of the key to copy to :param extra_args: A dictionary of any extra arguments that may be used in the upload. :param callbacks: List of callbacks to call after copy :param size: The size of the transfer. This value is passed into the callbacks """ client.copy_object( CopySource=copy_source, Bucket=bucket, Key=key, **extra_args) for callback in callbacks: callback(bytes_transferred=size)
def _main(self, client, copy_source, bucket, key, extra_args, callbacks, size): """ :param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to copy to :param key: The name of the key to copy to :param extra_args: A dictionary of any extra arguments that may be used in the upload. :param callbacks: List of callbacks to call after copy :param size: The size of the transfer. This value is passed into the callbacks """ client.copy_object( CopySource=copy_source, Bucket=bucket, Key=key, **extra_args) for callback in callbacks: callback(bytes_transferred=size)
[ ":", "param", "client", ":", "The", "client", "to", "use", "when", "calling", "PutObject", ":", "param", "copy_source", ":", "The", "CopySource", "parameter", "to", "use", ":", "param", "bucket", ":", "The", "name", "of", "the", "bucket", "to", "copy", "to", ":", "param", "key", ":", "The", "name", "of", "the", "key", "to", "copy", "to", ":", "param", "extra_args", ":", "A", "dictionary", "of", "any", "extra", "arguments", "that", "may", "be", "used", "in", "the", "upload", ".", ":", "param", "callbacks", ":", "List", "of", "callbacks", "to", "call", "after", "copy", ":", "param", "size", ":", "The", "size", "of", "the", "transfer", ".", "This", "value", "is", "passed", "into", "the", "callbacks" ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/copies.py#L271-L288
[ "def", "_main", "(", "self", ",", "client", ",", "copy_source", ",", "bucket", ",", "key", ",", "extra_args", ",", "callbacks", ",", "size", ")", ":", "client", ".", "copy_object", "(", "CopySource", "=", "copy_source", ",", "Bucket", "=", "bucket", ",", "Key", "=", "key", ",", "*", "*", "extra_args", ")", "for", "callback", "in", "callbacks", ":", "callback", "(", "bytes_transferred", "=", "size", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
CopyPartTask._main
:param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param part_number: The number representing the part of the multipart upload :param extra_args: A dictionary of any extra arguments that may be used in the upload. :param callbacks: List of callbacks to call after copy part :param size: The size of the transfer. This value is passed into the callbacks :rtype: dict :returns: A dictionary representing a part:: {'Etag': etag_value, 'PartNumber': part_number} This value can be appended to a list to be used to complete the multipart upload.
s3transfer/copies.py
def _main(self, client, copy_source, bucket, key, upload_id, part_number, extra_args, callbacks, size): """ :param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param part_number: The number representing the part of the multipart upload :param extra_args: A dictionary of any extra arguments that may be used in the upload. :param callbacks: List of callbacks to call after copy part :param size: The size of the transfer. This value is passed into the callbacks :rtype: dict :returns: A dictionary representing a part:: {'Etag': etag_value, 'PartNumber': part_number} This value can be appended to a list to be used to complete the multipart upload. """ response = client.upload_part_copy( CopySource=copy_source, Bucket=bucket, Key=key, UploadId=upload_id, PartNumber=part_number, **extra_args) for callback in callbacks: callback(bytes_transferred=size) etag = response['CopyPartResult']['ETag'] return {'ETag': etag, 'PartNumber': part_number}
def _main(self, client, copy_source, bucket, key, upload_id, part_number, extra_args, callbacks, size): """ :param client: The client to use when calling PutObject :param copy_source: The CopySource parameter to use :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param part_number: The number representing the part of the multipart upload :param extra_args: A dictionary of any extra arguments that may be used in the upload. :param callbacks: List of callbacks to call after copy part :param size: The size of the transfer. This value is passed into the callbacks :rtype: dict :returns: A dictionary representing a part:: {'Etag': etag_value, 'PartNumber': part_number} This value can be appended to a list to be used to complete the multipart upload. """ response = client.upload_part_copy( CopySource=copy_source, Bucket=bucket, Key=key, UploadId=upload_id, PartNumber=part_number, **extra_args) for callback in callbacks: callback(bytes_transferred=size) etag = response['CopyPartResult']['ETag'] return {'ETag': etag, 'PartNumber': part_number}
[ ":", "param", "client", ":", "The", "client", "to", "use", "when", "calling", "PutObject", ":", "param", "copy_source", ":", "The", "CopySource", "parameter", "to", "use", ":", "param", "bucket", ":", "The", "name", "of", "the", "bucket", "to", "upload", "to", ":", "param", "key", ":", "The", "name", "of", "the", "key", "to", "upload", "to", ":", "param", "upload_id", ":", "The", "id", "of", "the", "upload", ":", "param", "part_number", ":", "The", "number", "representing", "the", "part", "of", "the", "multipart", "upload", ":", "param", "extra_args", ":", "A", "dictionary", "of", "any", "extra", "arguments", "that", "may", "be", "used", "in", "the", "upload", ".", ":", "param", "callbacks", ":", "List", "of", "callbacks", "to", "call", "after", "copy", "part", ":", "param", "size", ":", "The", "size", "of", "the", "transfer", ".", "This", "value", "is", "passed", "into", "the", "callbacks" ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/copies.py#L293-L323
[ "def", "_main", "(", "self", ",", "client", ",", "copy_source", ",", "bucket", ",", "key", ",", "upload_id", ",", "part_number", ",", "extra_args", ",", "callbacks", ",", "size", ")", ":", "response", "=", "client", ".", "upload_part_copy", "(", "CopySource", "=", "copy_source", ",", "Bucket", "=", "bucket", ",", "Key", "=", "key", ",", "UploadId", "=", "upload_id", ",", "PartNumber", "=", "part_number", ",", "*", "*", "extra_args", ")", "for", "callback", "in", "callbacks", ":", "callback", "(", "bytes_transferred", "=", "size", ")", "etag", "=", "response", "[", "'CopyPartResult'", "]", "[", "'ETag'", "]", "return", "{", "'ETag'", ":", "etag", ",", "'PartNumber'", ":", "part_number", "}" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
ReadFileChunk.from_filename
Convenience factory function to create from a filename. :type start_byte: int :param start_byte: The first byte from which to start reading. :type chunk_size: int :param chunk_size: The max chunk size to read. Trying to read pass the end of the chunk size will behave like you've reached the end of the file. :type full_file_size: int :param full_file_size: The entire content length associated with ``fileobj``. :type callback: function(amount_read) :param callback: Called whenever data is read from this object. :type enable_callback: bool :param enable_callback: Indicate whether to invoke callback during read() calls. :rtype: ``ReadFileChunk`` :return: A new instance of ``ReadFileChunk``
s3transfer/__init__.py
def from_filename(cls, filename, start_byte, chunk_size, callback=None, enable_callback=True): """Convenience factory function to create from a filename. :type start_byte: int :param start_byte: The first byte from which to start reading. :type chunk_size: int :param chunk_size: The max chunk size to read. Trying to read pass the end of the chunk size will behave like you've reached the end of the file. :type full_file_size: int :param full_file_size: The entire content length associated with ``fileobj``. :type callback: function(amount_read) :param callback: Called whenever data is read from this object. :type enable_callback: bool :param enable_callback: Indicate whether to invoke callback during read() calls. :rtype: ``ReadFileChunk`` :return: A new instance of ``ReadFileChunk`` """ f = open(filename, 'rb') file_size = os.fstat(f.fileno()).st_size return cls(f, start_byte, chunk_size, file_size, callback, enable_callback)
def from_filename(cls, filename, start_byte, chunk_size, callback=None, enable_callback=True): """Convenience factory function to create from a filename. :type start_byte: int :param start_byte: The first byte from which to start reading. :type chunk_size: int :param chunk_size: The max chunk size to read. Trying to read pass the end of the chunk size will behave like you've reached the end of the file. :type full_file_size: int :param full_file_size: The entire content length associated with ``fileobj``. :type callback: function(amount_read) :param callback: Called whenever data is read from this object. :type enable_callback: bool :param enable_callback: Indicate whether to invoke callback during read() calls. :rtype: ``ReadFileChunk`` :return: A new instance of ``ReadFileChunk`` """ f = open(filename, 'rb') file_size = os.fstat(f.fileno()).st_size return cls(f, start_byte, chunk_size, file_size, callback, enable_callback)
[ "Convenience", "factory", "function", "to", "create", "from", "a", "filename", "." ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/__init__.py#L225-L255
[ "def", "from_filename", "(", "cls", ",", "filename", ",", "start_byte", ",", "chunk_size", ",", "callback", "=", "None", ",", "enable_callback", "=", "True", ")", ":", "f", "=", "open", "(", "filename", ",", "'rb'", ")", "file_size", "=", "os", ".", "fstat", "(", "f", ".", "fileno", "(", ")", ")", ".", "st_size", "return", "cls", "(", "f", ",", "start_byte", ",", "chunk_size", ",", "file_size", ",", "callback", ",", "enable_callback", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
S3Transfer.upload_file
Upload a file to an S3 object. Variants have also been injected into S3 client, Bucket and Object. You don't have to use S3Transfer.upload_file() directly.
s3transfer/__init__.py
def upload_file(self, filename, bucket, key, callback=None, extra_args=None): """Upload a file to an S3 object. Variants have also been injected into S3 client, Bucket and Object. You don't have to use S3Transfer.upload_file() directly. """ if extra_args is None: extra_args = {} self._validate_all_known_args(extra_args, self.ALLOWED_UPLOAD_ARGS) events = self._client.meta.events events.register_first('request-created.s3', disable_upload_callbacks, unique_id='s3upload-callback-disable') events.register_last('request-created.s3', enable_upload_callbacks, unique_id='s3upload-callback-enable') if self._osutil.get_file_size(filename) >= \ self._config.multipart_threshold: self._multipart_upload(filename, bucket, key, callback, extra_args) else: self._put_object(filename, bucket, key, callback, extra_args)
def upload_file(self, filename, bucket, key, callback=None, extra_args=None): """Upload a file to an S3 object. Variants have also been injected into S3 client, Bucket and Object. You don't have to use S3Transfer.upload_file() directly. """ if extra_args is None: extra_args = {} self._validate_all_known_args(extra_args, self.ALLOWED_UPLOAD_ARGS) events = self._client.meta.events events.register_first('request-created.s3', disable_upload_callbacks, unique_id='s3upload-callback-disable') events.register_last('request-created.s3', enable_upload_callbacks, unique_id='s3upload-callback-enable') if self._osutil.get_file_size(filename) >= \ self._config.multipart_threshold: self._multipart_upload(filename, bucket, key, callback, extra_args) else: self._put_object(filename, bucket, key, callback, extra_args)
[ "Upload", "a", "file", "to", "an", "S3", "object", "." ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/__init__.py#L623-L644
[ "def", "upload_file", "(", "self", ",", "filename", ",", "bucket", ",", "key", ",", "callback", "=", "None", ",", "extra_args", "=", "None", ")", ":", "if", "extra_args", "is", "None", ":", "extra_args", "=", "{", "}", "self", ".", "_validate_all_known_args", "(", "extra_args", ",", "self", ".", "ALLOWED_UPLOAD_ARGS", ")", "events", "=", "self", ".", "_client", ".", "meta", ".", "events", "events", ".", "register_first", "(", "'request-created.s3'", ",", "disable_upload_callbacks", ",", "unique_id", "=", "'s3upload-callback-disable'", ")", "events", ".", "register_last", "(", "'request-created.s3'", ",", "enable_upload_callbacks", ",", "unique_id", "=", "'s3upload-callback-enable'", ")", "if", "self", ".", "_osutil", ".", "get_file_size", "(", "filename", ")", ">=", "self", ".", "_config", ".", "multipart_threshold", ":", "self", ".", "_multipart_upload", "(", "filename", ",", "bucket", ",", "key", ",", "callback", ",", "extra_args", ")", "else", ":", "self", ".", "_put_object", "(", "filename", ",", "bucket", ",", "key", ",", "callback", ",", "extra_args", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
S3Transfer.download_file
Download an S3 object to a file. Variants have also been injected into S3 client, Bucket and Object. You don't have to use S3Transfer.download_file() directly.
s3transfer/__init__.py
def download_file(self, bucket, key, filename, extra_args=None, callback=None): """Download an S3 object to a file. Variants have also been injected into S3 client, Bucket and Object. You don't have to use S3Transfer.download_file() directly. """ # This method will issue a ``head_object`` request to determine # the size of the S3 object. This is used to determine if the # object is downloaded in parallel. if extra_args is None: extra_args = {} self._validate_all_known_args(extra_args, self.ALLOWED_DOWNLOAD_ARGS) object_size = self._object_size(bucket, key, extra_args) temp_filename = filename + os.extsep + random_file_extension() try: self._download_file(bucket, key, temp_filename, object_size, extra_args, callback) except Exception: logger.debug("Exception caught in download_file, removing partial " "file: %s", temp_filename, exc_info=True) self._osutil.remove_file(temp_filename) raise else: self._osutil.rename_file(temp_filename, filename)
def download_file(self, bucket, key, filename, extra_args=None, callback=None): """Download an S3 object to a file. Variants have also been injected into S3 client, Bucket and Object. You don't have to use S3Transfer.download_file() directly. """ # This method will issue a ``head_object`` request to determine # the size of the S3 object. This is used to determine if the # object is downloaded in parallel. if extra_args is None: extra_args = {} self._validate_all_known_args(extra_args, self.ALLOWED_DOWNLOAD_ARGS) object_size = self._object_size(bucket, key, extra_args) temp_filename = filename + os.extsep + random_file_extension() try: self._download_file(bucket, key, temp_filename, object_size, extra_args, callback) except Exception: logger.debug("Exception caught in download_file, removing partial " "file: %s", temp_filename, exc_info=True) self._osutil.remove_file(temp_filename) raise else: self._osutil.rename_file(temp_filename, filename)
[ "Download", "an", "S3", "object", "to", "a", "file", "." ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/__init__.py#L656-L680
[ "def", "download_file", "(", "self", ",", "bucket", ",", "key", ",", "filename", ",", "extra_args", "=", "None", ",", "callback", "=", "None", ")", ":", "# This method will issue a ``head_object`` request to determine", "# the size of the S3 object. This is used to determine if the", "# object is downloaded in parallel.", "if", "extra_args", "is", "None", ":", "extra_args", "=", "{", "}", "self", ".", "_validate_all_known_args", "(", "extra_args", ",", "self", ".", "ALLOWED_DOWNLOAD_ARGS", ")", "object_size", "=", "self", ".", "_object_size", "(", "bucket", ",", "key", ",", "extra_args", ")", "temp_filename", "=", "filename", "+", "os", ".", "extsep", "+", "random_file_extension", "(", ")", "try", ":", "self", ".", "_download_file", "(", "bucket", ",", "key", ",", "temp_filename", ",", "object_size", ",", "extra_args", ",", "callback", ")", "except", "Exception", ":", "logger", ".", "debug", "(", "\"Exception caught in download_file, removing partial \"", "\"file: %s\"", ",", "temp_filename", ",", "exc_info", "=", "True", ")", "self", ".", "_osutil", ".", "remove_file", "(", "temp_filename", ")", "raise", "else", ":", "self", ".", "_osutil", ".", "rename_file", "(", "temp_filename", ",", "filename", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
SubmissionTask._main
:type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for :param kwargs: Any additional kwargs that you may want to pass to the _submit() method
s3transfer/tasks.py
def _main(self, transfer_future, **kwargs): """ :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for :param kwargs: Any additional kwargs that you may want to pass to the _submit() method """ try: self._transfer_coordinator.set_status_to_queued() # Before submitting any tasks, run all of the on_queued callbacks on_queued_callbacks = get_callbacks(transfer_future, 'queued') for on_queued_callback in on_queued_callbacks: on_queued_callback() # Once callbacks have been ran set the status to running. self._transfer_coordinator.set_status_to_running() # Call the submit method to start submitting tasks to execute the # transfer. self._submit(transfer_future=transfer_future, **kwargs) except BaseException as e: # If there was an exception raised during the submission of task # there is a chance that the final task that signals if a transfer # is done and too run the cleanup may never have been submitted in # the first place so we need to account accordingly. # # Note that BaseException is caught, instead of Exception, because # for some implmentations of executors, specifically the serial # implementation, the SubmissionTask is directly exposed to # KeyboardInterupts and so needs to cleanup and signal done # for those as well. # Set the exception, that caused the process to fail. self._log_and_set_exception(e) # Wait for all possibly associated futures that may have spawned # from this submission task have finished before we anounce the # transfer done. self._wait_for_all_submitted_futures_to_complete() # Announce the transfer as done, which will run any cleanups # and done callbacks as well. self._transfer_coordinator.announce_done()
def _main(self, transfer_future, **kwargs): """ :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future associated with the transfer request that tasks are being submitted for :param kwargs: Any additional kwargs that you may want to pass to the _submit() method """ try: self._transfer_coordinator.set_status_to_queued() # Before submitting any tasks, run all of the on_queued callbacks on_queued_callbacks = get_callbacks(transfer_future, 'queued') for on_queued_callback in on_queued_callbacks: on_queued_callback() # Once callbacks have been ran set the status to running. self._transfer_coordinator.set_status_to_running() # Call the submit method to start submitting tasks to execute the # transfer. self._submit(transfer_future=transfer_future, **kwargs) except BaseException as e: # If there was an exception raised during the submission of task # there is a chance that the final task that signals if a transfer # is done and too run the cleanup may never have been submitted in # the first place so we need to account accordingly. # # Note that BaseException is caught, instead of Exception, because # for some implmentations of executors, specifically the serial # implementation, the SubmissionTask is directly exposed to # KeyboardInterupts and so needs to cleanup and signal done # for those as well. # Set the exception, that caused the process to fail. self._log_and_set_exception(e) # Wait for all possibly associated futures that may have spawned # from this submission task have finished before we anounce the # transfer done. self._wait_for_all_submitted_futures_to_complete() # Announce the transfer as done, which will run any cleanups # and done callbacks as well. self._transfer_coordinator.announce_done()
[ ":", "type", "transfer_future", ":", "s3transfer", ".", "futures", ".", "TransferFuture", ":", "param", "transfer_future", ":", "The", "transfer", "future", "associated", "with", "the", "transfer", "request", "that", "tasks", "are", "being", "submitted", "for" ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/tasks.py#L233-L278
[ "def", "_main", "(", "self", ",", "transfer_future", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "_transfer_coordinator", ".", "set_status_to_queued", "(", ")", "# Before submitting any tasks, run all of the on_queued callbacks", "on_queued_callbacks", "=", "get_callbacks", "(", "transfer_future", ",", "'queued'", ")", "for", "on_queued_callback", "in", "on_queued_callbacks", ":", "on_queued_callback", "(", ")", "# Once callbacks have been ran set the status to running.", "self", ".", "_transfer_coordinator", ".", "set_status_to_running", "(", ")", "# Call the submit method to start submitting tasks to execute the", "# transfer.", "self", ".", "_submit", "(", "transfer_future", "=", "transfer_future", ",", "*", "*", "kwargs", ")", "except", "BaseException", "as", "e", ":", "# If there was an exception raised during the submission of task", "# there is a chance that the final task that signals if a transfer", "# is done and too run the cleanup may never have been submitted in", "# the first place so we need to account accordingly.", "#", "# Note that BaseException is caught, instead of Exception, because", "# for some implmentations of executors, specifically the serial", "# implementation, the SubmissionTask is directly exposed to", "# KeyboardInterupts and so needs to cleanup and signal done", "# for those as well.", "# Set the exception, that caused the process to fail.", "self", ".", "_log_and_set_exception", "(", "e", ")", "# Wait for all possibly associated futures that may have spawned", "# from this submission task have finished before we anounce the", "# transfer done.", "self", ".", "_wait_for_all_submitted_futures_to_complete", "(", ")", "# Announce the transfer as done, which will run any cleanups", "# and done callbacks as well.", "self", ".", "_transfer_coordinator", ".", "announce_done", "(", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
CreateMultipartUploadTask._main
:param client: The client to use when calling CreateMultipartUpload :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param extra_args: A dictionary of any extra arguments that may be used in the intialization. :returns: The upload id of the multipart upload
s3transfer/tasks.py
def _main(self, client, bucket, key, extra_args): """ :param client: The client to use when calling CreateMultipartUpload :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param extra_args: A dictionary of any extra arguments that may be used in the intialization. :returns: The upload id of the multipart upload """ # Create the multipart upload. response = client.create_multipart_upload( Bucket=bucket, Key=key, **extra_args) upload_id = response['UploadId'] # Add a cleanup if the multipart upload fails at any point. self._transfer_coordinator.add_failure_cleanup( client.abort_multipart_upload, Bucket=bucket, Key=key, UploadId=upload_id ) return upload_id
def _main(self, client, bucket, key, extra_args): """ :param client: The client to use when calling CreateMultipartUpload :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param extra_args: A dictionary of any extra arguments that may be used in the intialization. :returns: The upload id of the multipart upload """ # Create the multipart upload. response = client.create_multipart_upload( Bucket=bucket, Key=key, **extra_args) upload_id = response['UploadId'] # Add a cleanup if the multipart upload fails at any point. self._transfer_coordinator.add_failure_cleanup( client.abort_multipart_upload, Bucket=bucket, Key=key, UploadId=upload_id ) return upload_id
[ ":", "param", "client", ":", "The", "client", "to", "use", "when", "calling", "CreateMultipartUpload", ":", "param", "bucket", ":", "The", "name", "of", "the", "bucket", "to", "upload", "to", ":", "param", "key", ":", "The", "name", "of", "the", "key", "to", "upload", "to", ":", "param", "extra_args", ":", "A", "dictionary", "of", "any", "extra", "arguments", "that", "may", "be", "used", "in", "the", "intialization", "." ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/tasks.py#L321-L341
[ "def", "_main", "(", "self", ",", "client", ",", "bucket", ",", "key", ",", "extra_args", ")", ":", "# Create the multipart upload.", "response", "=", "client", ".", "create_multipart_upload", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ",", "*", "*", "extra_args", ")", "upload_id", "=", "response", "[", "'UploadId'", "]", "# Add a cleanup if the multipart upload fails at any point.", "self", ".", "_transfer_coordinator", ".", "add_failure_cleanup", "(", "client", ".", "abort_multipart_upload", ",", "Bucket", "=", "bucket", ",", "Key", "=", "key", ",", "UploadId", "=", "upload_id", ")", "return", "upload_id" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
CompleteMultipartUploadTask._main
:param client: The client to use when calling CompleteMultipartUpload :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param parts: A list of parts to use to complete the multipart upload:: [{'Etag': etag_value, 'PartNumber': part_number}, ...] Each element in the list consists of a return value from ``UploadPartTask.main()``. :param extra_args: A dictionary of any extra arguments that may be used in completing the multipart transfer.
s3transfer/tasks.py
def _main(self, client, bucket, key, upload_id, parts, extra_args): """ :param client: The client to use when calling CompleteMultipartUpload :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param parts: A list of parts to use to complete the multipart upload:: [{'Etag': etag_value, 'PartNumber': part_number}, ...] Each element in the list consists of a return value from ``UploadPartTask.main()``. :param extra_args: A dictionary of any extra arguments that may be used in completing the multipart transfer. """ client.complete_multipart_upload( Bucket=bucket, Key=key, UploadId=upload_id, MultipartUpload={'Parts': parts}, **extra_args)
def _main(self, client, bucket, key, upload_id, parts, extra_args): """ :param client: The client to use when calling CompleteMultipartUpload :param bucket: The name of the bucket to upload to :param key: The name of the key to upload to :param upload_id: The id of the upload :param parts: A list of parts to use to complete the multipart upload:: [{'Etag': etag_value, 'PartNumber': part_number}, ...] Each element in the list consists of a return value from ``UploadPartTask.main()``. :param extra_args: A dictionary of any extra arguments that may be used in completing the multipart transfer. """ client.complete_multipart_upload( Bucket=bucket, Key=key, UploadId=upload_id, MultipartUpload={'Parts': parts}, **extra_args)
[ ":", "param", "client", ":", "The", "client", "to", "use", "when", "calling", "CompleteMultipartUpload", ":", "param", "bucket", ":", "The", "name", "of", "the", "bucket", "to", "upload", "to", ":", "param", "key", ":", "The", "name", "of", "the", "key", "to", "upload", "to", ":", "param", "upload_id", ":", "The", "id", "of", "the", "upload", ":", "param", "parts", ":", "A", "list", "of", "parts", "to", "use", "to", "complete", "the", "multipart", "upload", "::" ]
boto/s3transfer
python
https://github.com/boto/s3transfer/blob/2aead638c8385d8ae0b1756b2de17e8fad45fffa/s3transfer/tasks.py#L346-L364
[ "def", "_main", "(", "self", ",", "client", ",", "bucket", ",", "key", ",", "upload_id", ",", "parts", ",", "extra_args", ")", ":", "client", ".", "complete_multipart_upload", "(", "Bucket", "=", "bucket", ",", "Key", "=", "key", ",", "UploadId", "=", "upload_id", ",", "MultipartUpload", "=", "{", "'Parts'", ":", "parts", "}", ",", "*", "*", "extra_args", ")" ]
2aead638c8385d8ae0b1756b2de17e8fad45fffa
test
ParsoPythonFile.parse
Create a PythonFile object with specified file_path and content. If content is None then, it is loaded from the file_path method. Otherwise, file_path is only used for reporting errors.
getgauge/parser_parso.py
def parse(file_path, content=None): """ Create a PythonFile object with specified file_path and content. If content is None then, it is loaded from the file_path method. Otherwise, file_path is only used for reporting errors. """ try: # Parso reads files in binary mode and converts to unicode # using python_bytes_to_unicode() function. As a result, # we no longer have information about original file encoding and # output of module.get_content() can't be converted back to bytes # For now we can make a compromise by reading the file ourselves # and passing content to parse() function. if content is None: with open(file_path) as f: content = f.read() py_tree = _parser.parse( content, path=file_path, error_recovery=False) return ParsoPythonFile(file_path, py_tree) except parso.parser.ParserSyntaxError as ex: logging.error("Failed to parse %s:%d '%s'", file_path, ex.error_leaf.line, ex.error_leaf.get_code())
def parse(file_path, content=None): """ Create a PythonFile object with specified file_path and content. If content is None then, it is loaded from the file_path method. Otherwise, file_path is only used for reporting errors. """ try: # Parso reads files in binary mode and converts to unicode # using python_bytes_to_unicode() function. As a result, # we no longer have information about original file encoding and # output of module.get_content() can't be converted back to bytes # For now we can make a compromise by reading the file ourselves # and passing content to parse() function. if content is None: with open(file_path) as f: content = f.read() py_tree = _parser.parse( content, path=file_path, error_recovery=False) return ParsoPythonFile(file_path, py_tree) except parso.parser.ParserSyntaxError as ex: logging.error("Failed to parse %s:%d '%s'", file_path, ex.error_leaf.line, ex.error_leaf.get_code())
[ "Create", "a", "PythonFile", "object", "with", "specified", "file_path", "and", "content", ".", "If", "content", "is", "None", "then", "it", "is", "loaded", "from", "the", "file_path", "method", ".", "Otherwise", "file_path", "is", "only", "used", "for", "reporting", "errors", "." ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_parso.py#L15-L36
[ "def", "parse", "(", "file_path", ",", "content", "=", "None", ")", ":", "try", ":", "# Parso reads files in binary mode and converts to unicode", "# using python_bytes_to_unicode() function. As a result,", "# we no longer have information about original file encoding and", "# output of module.get_content() can't be converted back to bytes", "# For now we can make a compromise by reading the file ourselves", "# and passing content to parse() function.", "if", "content", "is", "None", ":", "with", "open", "(", "file_path", ")", "as", "f", ":", "content", "=", "f", ".", "read", "(", ")", "py_tree", "=", "_parser", ".", "parse", "(", "content", ",", "path", "=", "file_path", ",", "error_recovery", "=", "False", ")", "return", "ParsoPythonFile", "(", "file_path", ",", "py_tree", ")", "except", "parso", ".", "parser", ".", "ParserSyntaxError", "as", "ex", ":", "logging", ".", "error", "(", "\"Failed to parse %s:%d '%s'\"", ",", "file_path", ",", "ex", ".", "error_leaf", ".", "line", ",", "ex", ".", "error_leaf", ".", "get_code", "(", ")", ")" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
ParsoPythonFile._iter_step_func_decorators
Find functions with step decorator in parsed file
getgauge/parser_parso.py
def _iter_step_func_decorators(self): """Find functions with step decorator in parsed file""" func_defs = [func for func in self.py_tree.iter_funcdefs()] + [func for cls in self.py_tree.iter_classdefs() for func in cls.iter_funcdefs()] for func in func_defs: for decorator in func.get_decorators(): if decorator.children[1].value == 'step': yield func, decorator break
def _iter_step_func_decorators(self): """Find functions with step decorator in parsed file""" func_defs = [func for func in self.py_tree.iter_funcdefs()] + [func for cls in self.py_tree.iter_classdefs() for func in cls.iter_funcdefs()] for func in func_defs: for decorator in func.get_decorators(): if decorator.children[1].value == 'step': yield func, decorator break
[ "Find", "functions", "with", "step", "decorator", "in", "parsed", "file" ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_parso.py#L50-L57
[ "def", "_iter_step_func_decorators", "(", "self", ")", ":", "func_defs", "=", "[", "func", "for", "func", "in", "self", ".", "py_tree", ".", "iter_funcdefs", "(", ")", "]", "+", "[", "func", "for", "cls", "in", "self", ".", "py_tree", ".", "iter_classdefs", "(", ")", "for", "func", "in", "cls", ".", "iter_funcdefs", "(", ")", "]", "for", "func", "in", "func_defs", ":", "for", "decorator", "in", "func", ".", "get_decorators", "(", ")", ":", "if", "decorator", ".", "children", "[", "1", "]", ".", "value", "==", "'step'", ":", "yield", "func", ",", "decorator", "break" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
ParsoPythonFile._step_decorator_args
Get the arguments passed to step decorators converted to python objects.
getgauge/parser_parso.py
def _step_decorator_args(self, decorator): """ Get the arguments passed to step decorators converted to python objects. """ args = decorator.children[3:-2] step = None if len(args) == 1: try: step = ast.literal_eval(args[0].get_code()) except (ValueError, SyntaxError): pass if isinstance(step, six.string_types+(list,)): return step logging.error("Decorator step accepts either a string or a list of strings - %s:%d", self.file_path, decorator.start_pos[0]) else: logging.error("Decorator step accepts only one argument - %s:%d", self.file_path, decorator.start_pos[0])
def _step_decorator_args(self, decorator): """ Get the arguments passed to step decorators converted to python objects. """ args = decorator.children[3:-2] step = None if len(args) == 1: try: step = ast.literal_eval(args[0].get_code()) except (ValueError, SyntaxError): pass if isinstance(step, six.string_types+(list,)): return step logging.error("Decorator step accepts either a string or a list of strings - %s:%d", self.file_path, decorator.start_pos[0]) else: logging.error("Decorator step accepts only one argument - %s:%d", self.file_path, decorator.start_pos[0])
[ "Get", "the", "arguments", "passed", "to", "step", "decorators", "converted", "to", "python", "objects", "." ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_parso.py#L59-L77
[ "def", "_step_decorator_args", "(", "self", ",", "decorator", ")", ":", "args", "=", "decorator", ".", "children", "[", "3", ":", "-", "2", "]", "step", "=", "None", "if", "len", "(", "args", ")", "==", "1", ":", "try", ":", "step", "=", "ast", ".", "literal_eval", "(", "args", "[", "0", "]", ".", "get_code", "(", ")", ")", "except", "(", "ValueError", ",", "SyntaxError", ")", ":", "pass", "if", "isinstance", "(", "step", ",", "six", ".", "string_types", "+", "(", "list", ",", ")", ")", ":", "return", "step", "logging", ".", "error", "(", "\"Decorator step accepts either a string or a list of strings - %s:%d\"", ",", "self", ".", "file_path", ",", "decorator", ".", "start_pos", "[", "0", "]", ")", "else", ":", "logging", ".", "error", "(", "\"Decorator step accepts only one argument - %s:%d\"", ",", "self", ".", "file_path", ",", "decorator", ".", "start_pos", "[", "0", "]", ")" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
ParsoPythonFile.iter_steps
Iterate over steps in the parsed file.
getgauge/parser_parso.py
def iter_steps(self): """Iterate over steps in the parsed file.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) if step: span = self._span_from_pos(decorator.start_pos, func.end_pos) yield step, func.name.value, span
def iter_steps(self): """Iterate over steps in the parsed file.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) if step: span = self._span_from_pos(decorator.start_pos, func.end_pos) yield step, func.name.value, span
[ "Iterate", "over", "steps", "in", "the", "parsed", "file", "." ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_parso.py#L79-L85
[ "def", "iter_steps", "(", "self", ")", ":", "for", "func", ",", "decorator", "in", "self", ".", "_iter_step_func_decorators", "(", ")", ":", "step", "=", "self", ".", "_step_decorator_args", "(", "decorator", ")", "if", "step", ":", "span", "=", "self", ".", "_span_from_pos", "(", "decorator", ".", "start_pos", ",", "func", ".", "end_pos", ")", "yield", "step", ",", "func", ".", "name", ".", "value", ",", "span" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
ParsoPythonFile._find_step_node
Find the ast node which contains the text.
getgauge/parser_parso.py
def _find_step_node(self, step_text): """Find the ast node which contains the text.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) arg_node = decorator.children[3] if step == step_text: return arg_node, func elif isinstance(step, list) and step_text in step: idx = step.index(step_text) step_node = arg_node.children[1].children[idx * 2] return step_node, func return None, None
def _find_step_node(self, step_text): """Find the ast node which contains the text.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) arg_node = decorator.children[3] if step == step_text: return arg_node, func elif isinstance(step, list) and step_text in step: idx = step.index(step_text) step_node = arg_node.children[1].children[idx * 2] return step_node, func return None, None
[ "Find", "the", "ast", "node", "which", "contains", "the", "text", "." ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_parso.py#L87-L98
[ "def", "_find_step_node", "(", "self", ",", "step_text", ")", ":", "for", "func", ",", "decorator", "in", "self", ".", "_iter_step_func_decorators", "(", ")", ":", "step", "=", "self", ".", "_step_decorator_args", "(", "decorator", ")", "arg_node", "=", "decorator", ".", "children", "[", "3", "]", "if", "step", "==", "step_text", ":", "return", "arg_node", ",", "func", "elif", "isinstance", "(", "step", ",", "list", ")", "and", "step_text", "in", "step", ":", "idx", "=", "step", ".", "index", "(", "step_text", ")", "step_node", "=", "arg_node", ".", "children", "[", "1", "]", ".", "children", "[", "idx", "*", "2", "]", "return", "step_node", ",", "func", "return", "None", ",", "None" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
ParsoPythonFile.refactor_step
Find the step with old_text and change it to new_text.The step function parameters are also changed according to move_param_from_idx. Each entry in this list should specify parameter position from old.
getgauge/parser_parso.py
def refactor_step(self, old_text, new_text, move_param_from_idx): """ Find the step with old_text and change it to new_text.The step function parameters are also changed according to move_param_from_idx. Each entry in this list should specify parameter position from old. """ diffs = [] step, func = self._find_step_node(old_text) if step is None: return diffs step_diff = self._refactor_step_text(step, old_text, new_text) diffs.append(step_diff) params_list_node = func.children[2] moved_params = self._move_param_nodes( params_list_node.children, move_param_from_idx) if params_list_node.children is not moved_params: # Record original parameter list span excluding braces params_span = self._span_from_pos( params_list_node.children[0].end_pos, params_list_node.children[-1].start_pos) params_list_node.children = moved_params # Get code for moved paramters excluding braces param_code = ''.join(p.get_code() for p in moved_params[1:-1]) diffs.append((params_span, param_code)) return diffs
def refactor_step(self, old_text, new_text, move_param_from_idx): """ Find the step with old_text and change it to new_text.The step function parameters are also changed according to move_param_from_idx. Each entry in this list should specify parameter position from old. """ diffs = [] step, func = self._find_step_node(old_text) if step is None: return diffs step_diff = self._refactor_step_text(step, old_text, new_text) diffs.append(step_diff) params_list_node = func.children[2] moved_params = self._move_param_nodes( params_list_node.children, move_param_from_idx) if params_list_node.children is not moved_params: # Record original parameter list span excluding braces params_span = self._span_from_pos( params_list_node.children[0].end_pos, params_list_node.children[-1].start_pos) params_list_node.children = moved_params # Get code for moved paramters excluding braces param_code = ''.join(p.get_code() for p in moved_params[1:-1]) diffs.append((params_span, param_code)) return diffs
[ "Find", "the", "step", "with", "old_text", "and", "change", "it", "to", "new_text", ".", "The", "step", "function", "parameters", "are", "also", "changed", "according", "to", "move_param_from_idx", ".", "Each", "entry", "in", "this", "list", "should", "specify", "parameter", "position", "from", "old", "." ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_parso.py#L140-L164
[ "def", "refactor_step", "(", "self", ",", "old_text", ",", "new_text", ",", "move_param_from_idx", ")", ":", "diffs", "=", "[", "]", "step", ",", "func", "=", "self", ".", "_find_step_node", "(", "old_text", ")", "if", "step", "is", "None", ":", "return", "diffs", "step_diff", "=", "self", ".", "_refactor_step_text", "(", "step", ",", "old_text", ",", "new_text", ")", "diffs", ".", "append", "(", "step_diff", ")", "params_list_node", "=", "func", ".", "children", "[", "2", "]", "moved_params", "=", "self", ".", "_move_param_nodes", "(", "params_list_node", ".", "children", ",", "move_param_from_idx", ")", "if", "params_list_node", ".", "children", "is", "not", "moved_params", ":", "# Record original parameter list span excluding braces", "params_span", "=", "self", ".", "_span_from_pos", "(", "params_list_node", ".", "children", "[", "0", "]", ".", "end_pos", ",", "params_list_node", ".", "children", "[", "-", "1", "]", ".", "start_pos", ")", "params_list_node", ".", "children", "=", "moved_params", "# Get code for moved paramters excluding braces", "param_code", "=", "''", ".", "join", "(", "p", ".", "get_code", "(", ")", "for", "p", "in", "moved_params", "[", "1", ":", "-", "1", "]", ")", "diffs", ".", "append", "(", "(", "params_span", ",", "param_code", ")", ")", "return", "diffs" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
RedbaronPythonFile.parse
Create a PythonFile object with specified file_path and content. If content is None then, it is loaded from the file_path method. Otherwise, file_path is only used for reporting errors.
getgauge/parser_redbaron.py
def parse(file_path, content=None): """ Create a PythonFile object with specified file_path and content. If content is None then, it is loaded from the file_path method. Otherwise, file_path is only used for reporting errors. """ try: if content is None: with open(file_path) as f: content = f.read() py_tree = RedBaron(content) return RedbaronPythonFile(file_path, py_tree) except Exception as ex: # Trim parsing error message to only include failure location msg = str(ex) marker = "<---- here\n" marker_pos = msg.find(marker) if marker_pos > 0: msg = msg[:marker_pos + len(marker)] logging.error("Failed to parse {}: {}".format(file_path, msg))
def parse(file_path, content=None): """ Create a PythonFile object with specified file_path and content. If content is None then, it is loaded from the file_path method. Otherwise, file_path is only used for reporting errors. """ try: if content is None: with open(file_path) as f: content = f.read() py_tree = RedBaron(content) return RedbaronPythonFile(file_path, py_tree) except Exception as ex: # Trim parsing error message to only include failure location msg = str(ex) marker = "<---- here\n" marker_pos = msg.find(marker) if marker_pos > 0: msg = msg[:marker_pos + len(marker)] logging.error("Failed to parse {}: {}".format(file_path, msg))
[ "Create", "a", "PythonFile", "object", "with", "specified", "file_path", "and", "content", ".", "If", "content", "is", "None", "then", "it", "is", "loaded", "from", "the", "file_path", "method", ".", "Otherwise", "file_path", "is", "only", "used", "for", "reporting", "errors", "." ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_redbaron.py#L9-L28
[ "def", "parse", "(", "file_path", ",", "content", "=", "None", ")", ":", "try", ":", "if", "content", "is", "None", ":", "with", "open", "(", "file_path", ")", "as", "f", ":", "content", "=", "f", ".", "read", "(", ")", "py_tree", "=", "RedBaron", "(", "content", ")", "return", "RedbaronPythonFile", "(", "file_path", ",", "py_tree", ")", "except", "Exception", "as", "ex", ":", "# Trim parsing error message to only include failure location", "msg", "=", "str", "(", "ex", ")", "marker", "=", "\"<---- here\\n\"", "marker_pos", "=", "msg", ".", "find", "(", "marker", ")", "if", "marker_pos", ">", "0", ":", "msg", "=", "msg", "[", ":", "marker_pos", "+", "len", "(", "marker", ")", "]", "logging", ".", "error", "(", "\"Failed to parse {}: {}\"", ".", "format", "(", "file_path", ",", "msg", ")", ")" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
RedbaronPythonFile._iter_step_func_decorators
Find functions with step decorator in parsed file.
getgauge/parser_redbaron.py
def _iter_step_func_decorators(self): """Find functions with step decorator in parsed file.""" for node in self.py_tree.find_all('def'): for decorator in node.decorators: if decorator.name.value == 'step': yield node, decorator break
def _iter_step_func_decorators(self): """Find functions with step decorator in parsed file.""" for node in self.py_tree.find_all('def'): for decorator in node.decorators: if decorator.name.value == 'step': yield node, decorator break
[ "Find", "functions", "with", "step", "decorator", "in", "parsed", "file", "." ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_redbaron.py#L54-L60
[ "def", "_iter_step_func_decorators", "(", "self", ")", ":", "for", "node", "in", "self", ".", "py_tree", ".", "find_all", "(", "'def'", ")", ":", "for", "decorator", "in", "node", ".", "decorators", ":", "if", "decorator", ".", "name", ".", "value", "==", "'step'", ":", "yield", "node", ",", "decorator", "break" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
RedbaronPythonFile._step_decorator_args
Get arguments passed to step decorators converted to python objects.
getgauge/parser_redbaron.py
def _step_decorator_args(self, decorator): """ Get arguments passed to step decorators converted to python objects. """ args = decorator.call.value step = None if len(args) == 1: try: step = args[0].value.to_python() except (ValueError, SyntaxError): pass if isinstance(step, six.string_types + (list,)): return step logging.error("Decorator step accepts either a string or a list of \ strings - %s", self.file_path) else: logging.error("Decorator step accepts only one argument - %s", self.file_path)
def _step_decorator_args(self, decorator): """ Get arguments passed to step decorators converted to python objects. """ args = decorator.call.value step = None if len(args) == 1: try: step = args[0].value.to_python() except (ValueError, SyntaxError): pass if isinstance(step, six.string_types + (list,)): return step logging.error("Decorator step accepts either a string or a list of \ strings - %s", self.file_path) else: logging.error("Decorator step accepts only one argument - %s", self.file_path)
[ "Get", "arguments", "passed", "to", "step", "decorators", "converted", "to", "python", "objects", "." ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_redbaron.py#L62-L80
[ "def", "_step_decorator_args", "(", "self", ",", "decorator", ")", ":", "args", "=", "decorator", ".", "call", ".", "value", "step", "=", "None", "if", "len", "(", "args", ")", "==", "1", ":", "try", ":", "step", "=", "args", "[", "0", "]", ".", "value", ".", "to_python", "(", ")", "except", "(", "ValueError", ",", "SyntaxError", ")", ":", "pass", "if", "isinstance", "(", "step", ",", "six", ".", "string_types", "+", "(", "list", ",", ")", ")", ":", "return", "step", "logging", ".", "error", "(", "\"Decorator step accepts either a string or a list of \\\n strings - %s\"", ",", "self", ".", "file_path", ")", "else", ":", "logging", ".", "error", "(", "\"Decorator step accepts only one argument - %s\"", ",", "self", ".", "file_path", ")" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
RedbaronPythonFile.iter_steps
Iterate over steps in the parsed file.
getgauge/parser_redbaron.py
def iter_steps(self): """Iterate over steps in the parsed file.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) if step: yield step, func.name, self._span_for_node(func, True)
def iter_steps(self): """Iterate over steps in the parsed file.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) if step: yield step, func.name, self._span_for_node(func, True)
[ "Iterate", "over", "steps", "in", "the", "parsed", "file", "." ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_redbaron.py#L82-L87
[ "def", "iter_steps", "(", "self", ")", ":", "for", "func", ",", "decorator", "in", "self", ".", "_iter_step_func_decorators", "(", ")", ":", "step", "=", "self", ".", "_step_decorator_args", "(", "decorator", ")", "if", "step", ":", "yield", "step", ",", "func", ".", "name", ",", "self", ".", "_span_for_node", "(", "func", ",", "True", ")" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
RedbaronPythonFile._find_step_node
Find the ast node which contains the text.
getgauge/parser_redbaron.py
def _find_step_node(self, step_text): """Find the ast node which contains the text.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) arg_node = decorator.call.value[0].value if step == step_text: return arg_node, func elif isinstance(step, list) and step_text in step: step_node = arg_node[step.index(step_text)] return step_node, func return None, None
def _find_step_node(self, step_text): """Find the ast node which contains the text.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) arg_node = decorator.call.value[0].value if step == step_text: return arg_node, func elif isinstance(step, list) and step_text in step: step_node = arg_node[step.index(step_text)] return step_node, func return None, None
[ "Find", "the", "ast", "node", "which", "contains", "the", "text", "." ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_redbaron.py#L89-L99
[ "def", "_find_step_node", "(", "self", ",", "step_text", ")", ":", "for", "func", ",", "decorator", "in", "self", ".", "_iter_step_func_decorators", "(", ")", ":", "step", "=", "self", ".", "_step_decorator_args", "(", "decorator", ")", "arg_node", "=", "decorator", ".", "call", ".", "value", "[", "0", "]", ".", "value", "if", "step", "==", "step_text", ":", "return", "arg_node", ",", "func", "elif", "isinstance", "(", "step", ",", "list", ")", "and", "step_text", "in", "step", ":", "step_node", "=", "arg_node", "[", "step", ".", "index", "(", "step_text", ")", "]", "return", "step_node", ",", "func", "return", "None", ",", "None" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
RedbaronPythonFile.refactor_step
Find the step with old_text and change it to new_text. The step function parameters are also changed according to move_param_from_idx. Each entry in this list should specify parameter position from old
getgauge/parser_redbaron.py
def refactor_step(self, old_text, new_text, move_param_from_idx): """ Find the step with old_text and change it to new_text. The step function parameters are also changed according to move_param_from_idx. Each entry in this list should specify parameter position from old """ diffs = [] step, func = self._find_step_node(old_text) if step is None: return diffs step_diff = self._refactor_step_text(step, old_text, new_text) diffs.append(step_diff) moved_params = self._move_params(func.arguments, move_param_from_idx) if func.arguments is not moved_params: params_span = self._span_for_node(func.arguments, False) func.arguments = moved_params diffs.append((params_span, func.arguments.dumps())) return diffs
def refactor_step(self, old_text, new_text, move_param_from_idx): """ Find the step with old_text and change it to new_text. The step function parameters are also changed according to move_param_from_idx. Each entry in this list should specify parameter position from old """ diffs = [] step, func = self._find_step_node(old_text) if step is None: return diffs step_diff = self._refactor_step_text(step, old_text, new_text) diffs.append(step_diff) moved_params = self._move_params(func.arguments, move_param_from_idx) if func.arguments is not moved_params: params_span = self._span_for_node(func.arguments, False) func.arguments = moved_params diffs.append((params_span, func.arguments.dumps())) return diffs
[ "Find", "the", "step", "with", "old_text", "and", "change", "it", "to", "new_text", ".", "The", "step", "function", "parameters", "are", "also", "changed", "according", "to", "move_param_from_idx", ".", "Each", "entry", "in", "this", "list", "should", "specify", "parameter", "position", "from", "old" ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser_redbaron.py#L125-L143
[ "def", "refactor_step", "(", "self", ",", "old_text", ",", "new_text", ",", "move_param_from_idx", ")", ":", "diffs", "=", "[", "]", "step", ",", "func", "=", "self", ".", "_find_step_node", "(", "old_text", ")", "if", "step", "is", "None", ":", "return", "diffs", "step_diff", "=", "self", ".", "_refactor_step_text", "(", "step", ",", "old_text", ",", "new_text", ")", "diffs", ".", "append", "(", "step_diff", ")", "moved_params", "=", "self", ".", "_move_params", "(", "func", ".", "arguments", ",", "move_param_from_idx", ")", "if", "func", ".", "arguments", "is", "not", "moved_params", ":", "params_span", "=", "self", ".", "_span_for_node", "(", "func", ".", "arguments", ",", "False", ")", "func", ".", "arguments", "=", "moved_params", "diffs", ".", "append", "(", "(", "params_span", ",", "func", ".", "arguments", ".", "dumps", "(", ")", ")", ")", "return", "diffs" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
PythonFile.select_python_parser
Select default parser for loading and refactoring steps. Passing `redbaron` as argument will select the old paring engine from v0.3.3 Replacing the redbaron parser was necessary to support Python 3 syntax. We have tried our best to make sure there is no user impact on users. However, there may be regressions with new parser backend. To revert to the old parser implementation, add `GETGAUGE_USE_0_3_3_PARSER=true` property to the `python.properties` file in the `<PROJECT_DIR>/env/default directory. This property along with the redbaron parser will be removed in future releases.
getgauge/parser.py
def select_python_parser(parser=None): """ Select default parser for loading and refactoring steps. Passing `redbaron` as argument will select the old paring engine from v0.3.3 Replacing the redbaron parser was necessary to support Python 3 syntax. We have tried our best to make sure there is no user impact on users. However, there may be regressions with new parser backend. To revert to the old parser implementation, add `GETGAUGE_USE_0_3_3_PARSER=true` property to the `python.properties` file in the `<PROJECT_DIR>/env/default directory. This property along with the redbaron parser will be removed in future releases. """ if parser == 'redbaron' or os.environ.get('GETGAUGE_USE_0_3_3_PARSER'): PythonFile.Class = RedbaronPythonFile else: PythonFile.Class = ParsoPythonFile
def select_python_parser(parser=None): """ Select default parser for loading and refactoring steps. Passing `redbaron` as argument will select the old paring engine from v0.3.3 Replacing the redbaron parser was necessary to support Python 3 syntax. We have tried our best to make sure there is no user impact on users. However, there may be regressions with new parser backend. To revert to the old parser implementation, add `GETGAUGE_USE_0_3_3_PARSER=true` property to the `python.properties` file in the `<PROJECT_DIR>/env/default directory. This property along with the redbaron parser will be removed in future releases. """ if parser == 'redbaron' or os.environ.get('GETGAUGE_USE_0_3_3_PARSER'): PythonFile.Class = RedbaronPythonFile else: PythonFile.Class = ParsoPythonFile
[ "Select", "default", "parser", "for", "loading", "and", "refactoring", "steps", ".", "Passing", "redbaron", "as", "argument", "will", "select", "the", "old", "paring", "engine", "from", "v0", ".", "3", ".", "3" ]
getgauge/gauge-python
python
https://github.com/getgauge/gauge-python/blob/90f3547dcfd2d16d51f116cdd4e53527eeab1a57/getgauge/parser.py#L21-L38
[ "def", "select_python_parser", "(", "parser", "=", "None", ")", ":", "if", "parser", "==", "'redbaron'", "or", "os", ".", "environ", ".", "get", "(", "'GETGAUGE_USE_0_3_3_PARSER'", ")", ":", "PythonFile", ".", "Class", "=", "RedbaronPythonFile", "else", ":", "PythonFile", ".", "Class", "=", "ParsoPythonFile" ]
90f3547dcfd2d16d51f116cdd4e53527eeab1a57
test
TeamMembershipsAPI.list
List team memberships for a team, by ID. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all team memberships returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: teamId(basestring): List team memberships for a team, by ID. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the team memberships returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/team_memberships.py
def list(self, teamId, max=None, **request_parameters): """List team memberships for a team, by ID. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all team memberships returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: teamId(basestring): List team memberships for a team, by ID. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the team memberships returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring, may_be_none=False) check_type(max, int) params = dict_from_items_with_values( request_parameters, teamId=teamId, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield team membership objects created from the returned items JSON # objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
def list(self, teamId, max=None, **request_parameters): """List team memberships for a team, by ID. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all team memberships returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: teamId(basestring): List team memberships for a team, by ID. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the team memberships returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring, may_be_none=False) check_type(max, int) params = dict_from_items_with_values( request_parameters, teamId=teamId, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield team membership objects created from the returned items JSON # objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
[ "List", "team", "memberships", "for", "a", "team", "by", "ID", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/team_memberships.py#L76-L120
[ "def", "list", "(", "self", ",", "teamId", ",", "max", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "teamId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "max", ",", "int", ")", "params", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "teamId", "=", "teamId", ",", "max", "=", "max", ",", ")", "# API request - get items", "items", "=", "self", ".", "_session", ".", "get_items", "(", "API_ENDPOINT", ",", "params", "=", "params", ")", "# Yield team membership objects created from the returned items JSON", "# objects", "for", "item", "in", "items", ":", "yield", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "item", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
TeamMembershipsAPI.create
Add someone to a team by Person ID or email address. Add someone to a team by Person ID or email address; optionally making them a moderator. Args: teamId(basestring): The team ID. personId(basestring): The person ID. personEmail(basestring): The email address of the person. isModerator(bool): Set to True to make the person a team moderator. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: TeamMembership: A TeamMembership object with the details of the created team membership. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/team_memberships.py
def create(self, teamId, personId=None, personEmail=None, isModerator=False, **request_parameters): """Add someone to a team by Person ID or email address. Add someone to a team by Person ID or email address; optionally making them a moderator. Args: teamId(basestring): The team ID. personId(basestring): The person ID. personEmail(basestring): The email address of the person. isModerator(bool): Set to True to make the person a team moderator. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: TeamMembership: A TeamMembership object with the details of the created team membership. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring, may_be_none=False) check_type(personId, basestring) check_type(personEmail, basestring) check_type(isModerator, bool) post_data = dict_from_items_with_values( request_parameters, teamId=teamId, personId=personId, personEmail=personEmail, isModerator=isModerator, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a team membership object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def create(self, teamId, personId=None, personEmail=None, isModerator=False, **request_parameters): """Add someone to a team by Person ID or email address. Add someone to a team by Person ID or email address; optionally making them a moderator. Args: teamId(basestring): The team ID. personId(basestring): The person ID. personEmail(basestring): The email address of the person. isModerator(bool): Set to True to make the person a team moderator. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: TeamMembership: A TeamMembership object with the details of the created team membership. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring, may_be_none=False) check_type(personId, basestring) check_type(personEmail, basestring) check_type(isModerator, bool) post_data = dict_from_items_with_values( request_parameters, teamId=teamId, personId=personId, personEmail=personEmail, isModerator=isModerator, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a team membership object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Add", "someone", "to", "a", "team", "by", "Person", "ID", "or", "email", "address", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/team_memberships.py#L122-L163
[ "def", "create", "(", "self", ",", "teamId", ",", "personId", "=", "None", ",", "personEmail", "=", "None", ",", "isModerator", "=", "False", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "teamId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "personId", ",", "basestring", ")", "check_type", "(", "personEmail", ",", "basestring", ")", "check_type", "(", "isModerator", ",", "bool", ")", "post_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "teamId", "=", "teamId", ",", "personId", "=", "personId", ",", "personEmail", "=", "personEmail", ",", "isModerator", "=", "isModerator", ",", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "post", "(", "API_ENDPOINT", ",", "json", "=", "post_data", ")", "# Return a team membership object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
TeamMembershipsAPI.update
Update a team membership, by ID. Args: membershipId(basestring): The team membership ID. isModerator(bool): Set to True to make the person a team moderator. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: TeamMembership: A TeamMembership object with the updated Webex Teams team-membership details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/team_memberships.py
def update(self, membershipId, isModerator=None, **request_parameters): """Update a team membership, by ID. Args: membershipId(basestring): The team membership ID. isModerator(bool): Set to True to make the person a team moderator. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: TeamMembership: A TeamMembership object with the updated Webex Teams team-membership details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(membershipId, basestring, may_be_none=False) check_type(isModerator, bool) put_data = dict_from_items_with_values( request_parameters, isModerator=isModerator, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + membershipId, json=put_data) # Return a team membership object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def update(self, membershipId, isModerator=None, **request_parameters): """Update a team membership, by ID. Args: membershipId(basestring): The team membership ID. isModerator(bool): Set to True to make the person a team moderator. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: TeamMembership: A TeamMembership object with the updated Webex Teams team-membership details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(membershipId, basestring, may_be_none=False) check_type(isModerator, bool) put_data = dict_from_items_with_values( request_parameters, isModerator=isModerator, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + membershipId, json=put_data) # Return a team membership object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Update", "a", "team", "membership", "by", "ID", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/team_memberships.py#L188-L219
[ "def", "update", "(", "self", ",", "membershipId", ",", "isModerator", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "membershipId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "isModerator", ",", "bool", ")", "put_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "isModerator", "=", "isModerator", ",", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "put", "(", "API_ENDPOINT", "+", "'/'", "+", "membershipId", ",", "json", "=", "put_data", ")", "# Return a team membership object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
TeamMembershipsAPI.delete
Delete a team membership, by ID. Args: membershipId(basestring): The team membership ID. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/team_memberships.py
def delete(self, membershipId): """Delete a team membership, by ID. Args: membershipId(basestring): The team membership ID. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(membershipId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + membershipId)
def delete(self, membershipId): """Delete a team membership, by ID. Args: membershipId(basestring): The team membership ID. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(membershipId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + membershipId)
[ "Delete", "a", "team", "membership", "by", "ID", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/team_memberships.py#L221-L235
[ "def", "delete", "(", "self", ",", "membershipId", ")", ":", "check_type", "(", "membershipId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "# API request", "self", ".", "_session", ".", "delete", "(", "API_ENDPOINT", "+", "'/'", "+", "membershipId", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
get_catfact
Get a cat fact from catfact.ninja and return it as a string. Functions for Soundhound, Google, IBM Watson, or other APIs can be added to create the desired functionality into this bot.
examples/bot-example-webpy.py
def get_catfact(): """Get a cat fact from catfact.ninja and return it as a string. Functions for Soundhound, Google, IBM Watson, or other APIs can be added to create the desired functionality into this bot. """ response = requests.get(CAT_FACTS_URL, verify=False) response.raise_for_status() json_data = response.json() return json_data['fact']
def get_catfact(): """Get a cat fact from catfact.ninja and return it as a string. Functions for Soundhound, Google, IBM Watson, or other APIs can be added to create the desired functionality into this bot. """ response = requests.get(CAT_FACTS_URL, verify=False) response.raise_for_status() json_data = response.json() return json_data['fact']
[ "Get", "a", "cat", "fact", "from", "catfact", ".", "ninja", "and", "return", "it", "as", "a", "string", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/examples/bot-example-webpy.py#L83-L93
[ "def", "get_catfact", "(", ")", ":", "response", "=", "requests", ".", "get", "(", "CAT_FACTS_URL", ",", "verify", "=", "False", ")", "response", ".", "raise_for_status", "(", ")", "json_data", "=", "response", ".", "json", "(", ")", "return", "json_data", "[", "'fact'", "]" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
webhook.POST
Respond to inbound webhook JSON HTTP POSTs from Webex Teams.
examples/bot-example-webpy.py
def POST(self): """Respond to inbound webhook JSON HTTP POSTs from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = web.data() print("\nWEBHOOK POST RECEIVED:") print(json_data, "\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # Message was sent by someone else; parse message and respond. if "/CAT" in message.text: print("FOUND '/CAT'") # Get a cat fact cat_fact = get_catfact() print("SENDING CAT FACT '{}'".format(cat_fact)) # Post the fact to the room where the request was received api.messages.create(room.id, text=cat_fact) return 'OK'
def POST(self): """Respond to inbound webhook JSON HTTP POSTs from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = web.data() print("\nWEBHOOK POST RECEIVED:") print(json_data, "\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # Message was sent by someone else; parse message and respond. if "/CAT" in message.text: print("FOUND '/CAT'") # Get a cat fact cat_fact = get_catfact() print("SENDING CAT FACT '{}'".format(cat_fact)) # Post the fact to the room where the request was received api.messages.create(room.id, text=cat_fact) return 'OK'
[ "Respond", "to", "inbound", "webhook", "JSON", "HTTP", "POSTs", "from", "Webex", "Teams", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/examples/bot-example-webpy.py#L97-L133
[ "def", "POST", "(", "self", ")", ":", "# Get the POST data sent from Webex Teams", "json_data", "=", "web", ".", "data", "(", ")", "print", "(", "\"\\nWEBHOOK POST RECEIVED:\"", ")", "print", "(", "json_data", ",", "\"\\n\"", ")", "# Create a Webhook object from the JSON data", "webhook_obj", "=", "Webhook", "(", "json_data", ")", "# Get the room details", "room", "=", "api", ".", "rooms", ".", "get", "(", "webhook_obj", ".", "data", ".", "roomId", ")", "# Get the message details", "message", "=", "api", ".", "messages", ".", "get", "(", "webhook_obj", ".", "data", ".", "id", ")", "# Get the sender's details", "person", "=", "api", ".", "people", ".", "get", "(", "message", ".", "personId", ")", "print", "(", "\"NEW MESSAGE IN ROOM '{}'\"", ".", "format", "(", "room", ".", "title", ")", ")", "print", "(", "\"FROM '{}'\"", ".", "format", "(", "person", ".", "displayName", ")", ")", "print", "(", "\"MESSAGE '{}'\\n\"", ".", "format", "(", "message", ".", "text", ")", ")", "# This is a VERY IMPORTANT loop prevention control step.", "# If you respond to all messages... You will respond to the messages", "# that the bot posts and thereby create a loop condition.", "me", "=", "api", ".", "people", ".", "me", "(", ")", "if", "message", ".", "personId", "==", "me", ".", "id", ":", "# Message was sent by me (bot); do not respond.", "return", "'OK'", "else", ":", "# Message was sent by someone else; parse message and respond.", "if", "\"/CAT\"", "in", "message", ".", "text", ":", "print", "(", "\"FOUND '/CAT'\"", ")", "# Get a cat fact", "cat_fact", "=", "get_catfact", "(", ")", "print", "(", "\"SENDING CAT FACT '{}'\"", ".", "format", "(", "cat_fact", ")", ")", "# Post the fact to the room where the request was received", "api", ".", "messages", ".", "create", "(", "room", ".", "id", ",", "text", "=", "cat_fact", ")", "return", "'OK'" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
MembershipsAPI.list
List room memberships. By default, lists memberships for rooms to which the authenticated user belongs. Use query parameters to filter the response. Use `roomId` to list memberships for a room, by ID. Use either `personId` or `personEmail` to filter the results. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all memberships returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: roomId(basestring): Limit results to a specific room, by ID. personId(basestring): Limit results to a specific person, by ID. personEmail(basestring): Limit results to a specific person, by email address. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the memberships returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/memberships.py
def list(self, roomId=None, personId=None, personEmail=None, max=None, **request_parameters): """List room memberships. By default, lists memberships for rooms to which the authenticated user belongs. Use query parameters to filter the response. Use `roomId` to list memberships for a room, by ID. Use either `personId` or `personEmail` to filter the results. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all memberships returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: roomId(basestring): Limit results to a specific room, by ID. personId(basestring): Limit results to a specific person, by ID. personEmail(basestring): Limit results to a specific person, by email address. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the memberships returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(roomId, basestring) check_type(personId, basestring) check_type(personEmail, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, roomId=roomId, personId=personId, personEmail=personEmail, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield membership objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
def list(self, roomId=None, personId=None, personEmail=None, max=None, **request_parameters): """List room memberships. By default, lists memberships for rooms to which the authenticated user belongs. Use query parameters to filter the response. Use `roomId` to list memberships for a room, by ID. Use either `personId` or `personEmail` to filter the results. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all memberships returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: roomId(basestring): Limit results to a specific room, by ID. personId(basestring): Limit results to a specific person, by ID. personEmail(basestring): Limit results to a specific person, by email address. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the memberships returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(roomId, basestring) check_type(personId, basestring) check_type(personEmail, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, roomId=roomId, personId=personId, personEmail=personEmail, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield membership objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
[ "List", "room", "memberships", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/memberships.py#L76-L136
[ "def", "list", "(", "self", ",", "roomId", "=", "None", ",", "personId", "=", "None", ",", "personEmail", "=", "None", ",", "max", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "roomId", ",", "basestring", ")", "check_type", "(", "personId", ",", "basestring", ")", "check_type", "(", "personEmail", ",", "basestring", ")", "check_type", "(", "max", ",", "int", ")", "params", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "roomId", "=", "roomId", ",", "personId", "=", "personId", ",", "personEmail", "=", "personEmail", ",", "max", "=", "max", ",", ")", "# API request - get items", "items", "=", "self", ".", "_session", ".", "get_items", "(", "API_ENDPOINT", ",", "params", "=", "params", ")", "# Yield membership objects created from the returned items JSON objects", "for", "item", "in", "items", ":", "yield", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "item", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
MembershipsAPI.delete
Delete a membership, by ID. Args: membershipId(basestring): The membership ID. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/memberships.py
def delete(self, membershipId): """Delete a membership, by ID. Args: membershipId(basestring): The membership ID. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(membershipId, basestring) # API request self._session.delete(API_ENDPOINT + '/' + membershipId)
def delete(self, membershipId): """Delete a membership, by ID. Args: membershipId(basestring): The membership ID. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(membershipId, basestring) # API request self._session.delete(API_ENDPOINT + '/' + membershipId)
[ "Delete", "a", "membership", "by", "ID", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/memberships.py#L237-L251
[ "def", "delete", "(", "self", ",", "membershipId", ")", ":", "check_type", "(", "membershipId", ",", "basestring", ")", "# API request", "self", ".", "_session", ".", "delete", "(", "API_ENDPOINT", "+", "'/'", "+", "membershipId", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
to_unicode
Convert a string (bytes, str or unicode) to unicode.
webexteamssdk/utils.py
def to_unicode(string): """Convert a string (bytes, str or unicode) to unicode.""" assert isinstance(string, basestring) if sys.version_info[0] >= 3: if isinstance(string, bytes): return string.decode('utf-8') else: return string else: if isinstance(string, str): return string.decode('utf-8') else: return string
def to_unicode(string): """Convert a string (bytes, str or unicode) to unicode.""" assert isinstance(string, basestring) if sys.version_info[0] >= 3: if isinstance(string, bytes): return string.decode('utf-8') else: return string else: if isinstance(string, str): return string.decode('utf-8') else: return string
[ "Convert", "a", "string", "(", "bytes", "str", "or", "unicode", ")", "to", "unicode", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L59-L71
[ "def", "to_unicode", "(", "string", ")", ":", "assert", "isinstance", "(", "string", ",", "basestring", ")", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "if", "isinstance", "(", "string", ",", "bytes", ")", ":", "return", "string", ".", "decode", "(", "'utf-8'", ")", "else", ":", "return", "string", "else", ":", "if", "isinstance", "(", "string", ",", "str", ")", ":", "return", "string", ".", "decode", "(", "'utf-8'", ")", "else", ":", "return", "string" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
to_bytes
Convert a string (bytes, str or unicode) to bytes.
webexteamssdk/utils.py
def to_bytes(string): """Convert a string (bytes, str or unicode) to bytes.""" assert isinstance(string, basestring) if sys.version_info[0] >= 3: if isinstance(string, str): return string.encode('utf-8') else: return string else: if isinstance(string, unicode): return string.encode('utf-8') else: return string
def to_bytes(string): """Convert a string (bytes, str or unicode) to bytes.""" assert isinstance(string, basestring) if sys.version_info[0] >= 3: if isinstance(string, str): return string.encode('utf-8') else: return string else: if isinstance(string, unicode): return string.encode('utf-8') else: return string
[ "Convert", "a", "string", "(", "bytes", "str", "or", "unicode", ")", "to", "bytes", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L74-L86
[ "def", "to_bytes", "(", "string", ")", ":", "assert", "isinstance", "(", "string", ",", "basestring", ")", "if", "sys", ".", "version_info", "[", "0", "]", ">=", "3", ":", "if", "isinstance", "(", "string", ",", "str", ")", ":", "return", "string", ".", "encode", "(", "'utf-8'", ")", "else", ":", "return", "string", "else", ":", "if", "isinstance", "(", "string", ",", "unicode", ")", ":", "return", "string", ".", "encode", "(", "'utf-8'", ")", "else", ":", "return", "string" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
validate_base_url
Verify that base_url specifies a protocol and network location.
webexteamssdk/utils.py
def validate_base_url(base_url): """Verify that base_url specifies a protocol and network location.""" parsed_url = urllib.parse.urlparse(base_url) if parsed_url.scheme and parsed_url.netloc: return parsed_url.geturl() else: error_message = "base_url must contain a valid scheme (protocol " \ "specifier) and network location (hostname)" raise ValueError(error_message)
def validate_base_url(base_url): """Verify that base_url specifies a protocol and network location.""" parsed_url = urllib.parse.urlparse(base_url) if parsed_url.scheme and parsed_url.netloc: return parsed_url.geturl() else: error_message = "base_url must contain a valid scheme (protocol " \ "specifier) and network location (hostname)" raise ValueError(error_message)
[ "Verify", "that", "base_url", "specifies", "a", "protocol", "and", "network", "location", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L89-L97
[ "def", "validate_base_url", "(", "base_url", ")", ":", "parsed_url", "=", "urllib", ".", "parse", ".", "urlparse", "(", "base_url", ")", "if", "parsed_url", ".", "scheme", "and", "parsed_url", ".", "netloc", ":", "return", "parsed_url", ".", "geturl", "(", ")", "else", ":", "error_message", "=", "\"base_url must contain a valid scheme (protocol \"", "\"specifier) and network location (hostname)\"", "raise", "ValueError", "(", "error_message", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
is_web_url
Check to see if string is an validly-formatted web url.
webexteamssdk/utils.py
def is_web_url(string): """Check to see if string is an validly-formatted web url.""" assert isinstance(string, basestring) parsed_url = urllib.parse.urlparse(string) return ( ( parsed_url.scheme.lower() == 'http' or parsed_url.scheme.lower() == 'https' ) and parsed_url.netloc )
def is_web_url(string): """Check to see if string is an validly-formatted web url.""" assert isinstance(string, basestring) parsed_url = urllib.parse.urlparse(string) return ( ( parsed_url.scheme.lower() == 'http' or parsed_url.scheme.lower() == 'https' ) and parsed_url.netloc )
[ "Check", "to", "see", "if", "string", "is", "an", "validly", "-", "formatted", "web", "url", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L100-L110
[ "def", "is_web_url", "(", "string", ")", ":", "assert", "isinstance", "(", "string", ",", "basestring", ")", "parsed_url", "=", "urllib", ".", "parse", ".", "urlparse", "(", "string", ")", "return", "(", "(", "parsed_url", ".", "scheme", ".", "lower", "(", ")", "==", "'http'", "or", "parsed_url", ".", "scheme", ".", "lower", "(", ")", "==", "'https'", ")", "and", "parsed_url", ".", "netloc", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
open_local_file
Open the file and return an EncodableFile tuple.
webexteamssdk/utils.py
def open_local_file(file_path): """Open the file and return an EncodableFile tuple.""" assert isinstance(file_path, basestring) assert is_local_file(file_path) file_name = os.path.basename(file_path) file_object = open(file_path, 'rb') content_type = mimetypes.guess_type(file_name)[0] or 'text/plain' return EncodableFile(file_name=file_name, file_object=file_object, content_type=content_type)
def open_local_file(file_path): """Open the file and return an EncodableFile tuple.""" assert isinstance(file_path, basestring) assert is_local_file(file_path) file_name = os.path.basename(file_path) file_object = open(file_path, 'rb') content_type = mimetypes.guess_type(file_name)[0] or 'text/plain' return EncodableFile(file_name=file_name, file_object=file_object, content_type=content_type)
[ "Open", "the", "file", "and", "return", "an", "EncodableFile", "tuple", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L119-L128
[ "def", "open_local_file", "(", "file_path", ")", ":", "assert", "isinstance", "(", "file_path", ",", "basestring", ")", "assert", "is_local_file", "(", "file_path", ")", "file_name", "=", "os", ".", "path", ".", "basename", "(", "file_path", ")", "file_object", "=", "open", "(", "file_path", ",", "'rb'", ")", "content_type", "=", "mimetypes", ".", "guess_type", "(", "file_name", ")", "[", "0", "]", "or", "'text/plain'", "return", "EncodableFile", "(", "file_name", "=", "file_name", ",", "file_object", "=", "file_object", ",", "content_type", "=", "content_type", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
check_type
Object is an instance of one of the acceptable types or None. Args: o: The object to be inspected. acceptable_types: A type or tuple of acceptable types. may_be_none(bool): Whether or not the object may be None. Raises: TypeError: If the object is None and may_be_none=False, or if the object is not an instance of one of the acceptable types.
webexteamssdk/utils.py
def check_type(o, acceptable_types, may_be_none=True): """Object is an instance of one of the acceptable types or None. Args: o: The object to be inspected. acceptable_types: A type or tuple of acceptable types. may_be_none(bool): Whether or not the object may be None. Raises: TypeError: If the object is None and may_be_none=False, or if the object is not an instance of one of the acceptable types. """ if not isinstance(acceptable_types, tuple): acceptable_types = (acceptable_types,) if may_be_none and o is None: # Object is None, and that is OK! pass elif isinstance(o, acceptable_types): # Object is an instance of an acceptable type. pass else: # Object is something else. error_message = ( "We were expecting to receive an instance of one of the following " "types: {types}{none}; but instead we received {o} which is a " "{o_type}.".format( types=", ".join([repr(t.__name__) for t in acceptable_types]), none="or 'None'" if may_be_none else "", o=o, o_type=repr(type(o).__name__) ) ) raise TypeError(error_message)
def check_type(o, acceptable_types, may_be_none=True): """Object is an instance of one of the acceptable types or None. Args: o: The object to be inspected. acceptable_types: A type or tuple of acceptable types. may_be_none(bool): Whether or not the object may be None. Raises: TypeError: If the object is None and may_be_none=False, or if the object is not an instance of one of the acceptable types. """ if not isinstance(acceptable_types, tuple): acceptable_types = (acceptable_types,) if may_be_none and o is None: # Object is None, and that is OK! pass elif isinstance(o, acceptable_types): # Object is an instance of an acceptable type. pass else: # Object is something else. error_message = ( "We were expecting to receive an instance of one of the following " "types: {types}{none}; but instead we received {o} which is a " "{o_type}.".format( types=", ".join([repr(t.__name__) for t in acceptable_types]), none="or 'None'" if may_be_none else "", o=o, o_type=repr(type(o).__name__) ) ) raise TypeError(error_message)
[ "Object", "is", "an", "instance", "of", "one", "of", "the", "acceptable", "types", "or", "None", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L131-L165
[ "def", "check_type", "(", "o", ",", "acceptable_types", ",", "may_be_none", "=", "True", ")", ":", "if", "not", "isinstance", "(", "acceptable_types", ",", "tuple", ")", ":", "acceptable_types", "=", "(", "acceptable_types", ",", ")", "if", "may_be_none", "and", "o", "is", "None", ":", "# Object is None, and that is OK!", "pass", "elif", "isinstance", "(", "o", ",", "acceptable_types", ")", ":", "# Object is an instance of an acceptable type.", "pass", "else", ":", "# Object is something else.", "error_message", "=", "(", "\"We were expecting to receive an instance of one of the following \"", "\"types: {types}{none}; but instead we received {o} which is a \"", "\"{o_type}.\"", ".", "format", "(", "types", "=", "\", \"", ".", "join", "(", "[", "repr", "(", "t", ".", "__name__", ")", "for", "t", "in", "acceptable_types", "]", ")", ",", "none", "=", "\"or 'None'\"", "if", "may_be_none", "else", "\"\"", ",", "o", "=", "o", ",", "o_type", "=", "repr", "(", "type", "(", "o", ")", ".", "__name__", ")", ")", ")", "raise", "TypeError", "(", "error_message", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
dict_from_items_with_values
Creates a dict with the inputted items; pruning any that are `None`. Args: *dictionaries(dict): Dictionaries of items to be pruned and included. **items: Items to be pruned and included. Returns: dict: A dictionary containing all of the items with a 'non-None' value.
webexteamssdk/utils.py
def dict_from_items_with_values(*dictionaries, **items): """Creates a dict with the inputted items; pruning any that are `None`. Args: *dictionaries(dict): Dictionaries of items to be pruned and included. **items: Items to be pruned and included. Returns: dict: A dictionary containing all of the items with a 'non-None' value. """ dict_list = list(dictionaries) dict_list.append(items) result = {} for d in dict_list: for key, value in d.items(): if value is not None: result[key] = value return result
def dict_from_items_with_values(*dictionaries, **items): """Creates a dict with the inputted items; pruning any that are `None`. Args: *dictionaries(dict): Dictionaries of items to be pruned and included. **items: Items to be pruned and included. Returns: dict: A dictionary containing all of the items with a 'non-None' value. """ dict_list = list(dictionaries) dict_list.append(items) result = {} for d in dict_list: for key, value in d.items(): if value is not None: result[key] = value return result
[ "Creates", "a", "dict", "with", "the", "inputted", "items", ";", "pruning", "any", "that", "are", "None", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L168-L186
[ "def", "dict_from_items_with_values", "(", "*", "dictionaries", ",", "*", "*", "items", ")", ":", "dict_list", "=", "list", "(", "dictionaries", ")", "dict_list", ".", "append", "(", "items", ")", "result", "=", "{", "}", "for", "d", "in", "dict_list", ":", "for", "key", ",", "value", "in", "d", ".", "items", "(", ")", ":", "if", "value", "is", "not", "None", ":", "result", "[", "key", "]", "=", "value", "return", "result" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
check_response_code
Check response code against the expected code; raise ApiError. Checks the requests.response.status_code against the provided expected response code (erc), and raises a ApiError if they do not match. Args: response(requests.response): The response object returned by a request using the requests package. expected_response_code(int): The expected response code (HTTP response code). Raises: ApiError: If the requests.response.status_code does not match the provided expected response code (erc).
webexteamssdk/utils.py
def check_response_code(response, expected_response_code): """Check response code against the expected code; raise ApiError. Checks the requests.response.status_code against the provided expected response code (erc), and raises a ApiError if they do not match. Args: response(requests.response): The response object returned by a request using the requests package. expected_response_code(int): The expected response code (HTTP response code). Raises: ApiError: If the requests.response.status_code does not match the provided expected response code (erc). """ if response.status_code == expected_response_code: pass elif response.status_code == RATE_LIMIT_RESPONSE_CODE: raise RateLimitError(response) else: raise ApiError(response)
def check_response_code(response, expected_response_code): """Check response code against the expected code; raise ApiError. Checks the requests.response.status_code against the provided expected response code (erc), and raises a ApiError if they do not match. Args: response(requests.response): The response object returned by a request using the requests package. expected_response_code(int): The expected response code (HTTP response code). Raises: ApiError: If the requests.response.status_code does not match the provided expected response code (erc). """ if response.status_code == expected_response_code: pass elif response.status_code == RATE_LIMIT_RESPONSE_CODE: raise RateLimitError(response) else: raise ApiError(response)
[ "Check", "response", "code", "against", "the", "expected", "code", ";", "raise", "ApiError", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L195-L217
[ "def", "check_response_code", "(", "response", ",", "expected_response_code", ")", ":", "if", "response", ".", "status_code", "==", "expected_response_code", ":", "pass", "elif", "response", ".", "status_code", "==", "RATE_LIMIT_RESPONSE_CODE", ":", "raise", "RateLimitError", "(", "response", ")", "else", ":", "raise", "ApiError", "(", "response", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
json_dict
Given a dictionary or JSON string; return a dictionary. Args: json_data(dict, str): Input JSON object. Returns: A Python dictionary with the contents of the JSON object. Raises: TypeError: If the input object is not a dictionary or string.
webexteamssdk/utils.py
def json_dict(json_data): """Given a dictionary or JSON string; return a dictionary. Args: json_data(dict, str): Input JSON object. Returns: A Python dictionary with the contents of the JSON object. Raises: TypeError: If the input object is not a dictionary or string. """ if isinstance(json_data, dict): return json_data elif isinstance(json_data, basestring): return json.loads(json_data, object_hook=OrderedDict) else: raise TypeError( "'json_data' must be a dictionary or valid JSON string; " "received: {!r}".format(json_data) )
def json_dict(json_data): """Given a dictionary or JSON string; return a dictionary. Args: json_data(dict, str): Input JSON object. Returns: A Python dictionary with the contents of the JSON object. Raises: TypeError: If the input object is not a dictionary or string. """ if isinstance(json_data, dict): return json_data elif isinstance(json_data, basestring): return json.loads(json_data, object_hook=OrderedDict) else: raise TypeError( "'json_data' must be a dictionary or valid JSON string; " "received: {!r}".format(json_data) )
[ "Given", "a", "dictionary", "or", "JSON", "string", ";", "return", "a", "dictionary", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L234-L255
[ "def", "json_dict", "(", "json_data", ")", ":", "if", "isinstance", "(", "json_data", ",", "dict", ")", ":", "return", "json_data", "elif", "isinstance", "(", "json_data", ",", "basestring", ")", ":", "return", "json", ".", "loads", "(", "json_data", ",", "object_hook", "=", "OrderedDict", ")", "else", ":", "raise", "TypeError", "(", "\"'json_data' must be a dictionary or valid JSON string; \"", "\"received: {!r}\"", ".", "format", "(", "json_data", ")", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
WebexTeamsDateTime.strptime
strptime with the Webex Teams DateTime format as the default.
webexteamssdk/utils.py
def strptime(cls, date_string, format=WEBEX_TEAMS_DATETIME_FORMAT): """strptime with the Webex Teams DateTime format as the default.""" return super(WebexTeamsDateTime, cls).strptime( date_string, format ).replace(tzinfo=ZuluTimeZone())
def strptime(cls, date_string, format=WEBEX_TEAMS_DATETIME_FORMAT): """strptime with the Webex Teams DateTime format as the default.""" return super(WebexTeamsDateTime, cls).strptime( date_string, format ).replace(tzinfo=ZuluTimeZone())
[ "strptime", "with", "the", "Webex", "Teams", "DateTime", "format", "as", "the", "default", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/utils.py#L279-L283
[ "def", "strptime", "(", "cls", ",", "date_string", ",", "format", "=", "WEBEX_TEAMS_DATETIME_FORMAT", ")", ":", "return", "super", "(", "WebexTeamsDateTime", ",", "cls", ")", ".", "strptime", "(", "date_string", ",", "format", ")", ".", "replace", "(", "tzinfo", "=", "ZuluTimeZone", "(", ")", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RoomsAPI.list
List rooms. By default, lists rooms to which the authenticated user belongs. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all rooms returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: teamId(basestring): Limit the rooms to those associated with a team, by ID. type(basestring): 'direct' returns all 1-to-1 rooms. `group` returns all group rooms. If not specified or values not matched, will return all room types. sortBy(basestring): Sort results by room ID (`id`), most recent activity (`lastactivity`), or most recently created (`created`). max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the rooms returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/rooms.py
def list(self, teamId=None, type=None, sortBy=None, max=None, **request_parameters): """List rooms. By default, lists rooms to which the authenticated user belongs. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all rooms returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: teamId(basestring): Limit the rooms to those associated with a team, by ID. type(basestring): 'direct' returns all 1-to-1 rooms. `group` returns all group rooms. If not specified or values not matched, will return all room types. sortBy(basestring): Sort results by room ID (`id`), most recent activity (`lastactivity`), or most recently created (`created`). max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the rooms returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring) check_type(type, basestring) check_type(sortBy, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, teamId=teamId, type=type, sortBy=sortBy, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield room objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
def list(self, teamId=None, type=None, sortBy=None, max=None, **request_parameters): """List rooms. By default, lists rooms to which the authenticated user belongs. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all rooms returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: teamId(basestring): Limit the rooms to those associated with a team, by ID. type(basestring): 'direct' returns all 1-to-1 rooms. `group` returns all group rooms. If not specified or values not matched, will return all room types. sortBy(basestring): Sort results by room ID (`id`), most recent activity (`lastactivity`), or most recently created (`created`). max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the rooms returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring) check_type(type, basestring) check_type(sortBy, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, teamId=teamId, type=type, sortBy=sortBy, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield room objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
[ "List", "rooms", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/rooms.py#L76-L133
[ "def", "list", "(", "self", ",", "teamId", "=", "None", ",", "type", "=", "None", ",", "sortBy", "=", "None", ",", "max", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "teamId", ",", "basestring", ")", "check_type", "(", "type", ",", "basestring", ")", "check_type", "(", "sortBy", ",", "basestring", ")", "check_type", "(", "max", ",", "int", ")", "params", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "teamId", "=", "teamId", ",", "type", "=", "type", ",", "sortBy", "=", "sortBy", ",", "max", "=", "max", ",", ")", "# API request - get items", "items", "=", "self", ".", "_session", ".", "get_items", "(", "API_ENDPOINT", ",", "params", "=", "params", ")", "# Yield room objects created from the returned items JSON objects", "for", "item", "in", "items", ":", "yield", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "item", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RoomsAPI.create
Create a room. The authenticated user is automatically added as a member of the room. Args: title(basestring): A user-friendly name for the room. teamId(basestring): The team ID with which this room is associated. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Room: A Room with the details of the created room. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/rooms.py
def create(self, title, teamId=None, **request_parameters): """Create a room. The authenticated user is automatically added as a member of the room. Args: title(basestring): A user-friendly name for the room. teamId(basestring): The team ID with which this room is associated. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Room: A Room with the details of the created room. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(title, basestring) check_type(teamId, basestring) post_data = dict_from_items_with_values( request_parameters, title=title, teamId=teamId, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a room object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def create(self, title, teamId=None, **request_parameters): """Create a room. The authenticated user is automatically added as a member of the room. Args: title(basestring): A user-friendly name for the room. teamId(basestring): The team ID with which this room is associated. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Room: A Room with the details of the created room. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(title, basestring) check_type(teamId, basestring) post_data = dict_from_items_with_values( request_parameters, title=title, teamId=teamId, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a room object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Create", "a", "room", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/rooms.py#L135-L168
[ "def", "create", "(", "self", ",", "title", ",", "teamId", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "title", ",", "basestring", ")", "check_type", "(", "teamId", ",", "basestring", ")", "post_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "title", "=", "title", ",", "teamId", "=", "teamId", ",", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "post", "(", "API_ENDPOINT", ",", "json", "=", "post_data", ")", "# Return a room object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RoomsAPI.update
Update details for a room, by ID. Args: roomId(basestring): The room ID. title(basestring): A user-friendly name for the room. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Room: A Room object with the updated Webex Teams room details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/rooms.py
def update(self, roomId, title=None, **request_parameters): """Update details for a room, by ID. Args: roomId(basestring): The room ID. title(basestring): A user-friendly name for the room. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Room: A Room object with the updated Webex Teams room details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(roomId, basestring, may_be_none=False) check_type(roomId, basestring) put_data = dict_from_items_with_values( request_parameters, title=title, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + roomId, json=put_data) # Return a room object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def update(self, roomId, title=None, **request_parameters): """Update details for a room, by ID. Args: roomId(basestring): The room ID. title(basestring): A user-friendly name for the room. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Room: A Room object with the updated Webex Teams room details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(roomId, basestring, may_be_none=False) check_type(roomId, basestring) put_data = dict_from_items_with_values( request_parameters, title=title, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + roomId, json=put_data) # Return a room object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Update", "details", "for", "a", "room", "by", "ID", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/rooms.py#L192-L222
[ "def", "update", "(", "self", ",", "roomId", ",", "title", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "roomId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "roomId", ",", "basestring", ")", "put_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "title", "=", "title", ",", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "put", "(", "API_ENDPOINT", "+", "'/'", "+", "roomId", ",", "json", "=", "put_data", ")", "# Return a room object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RoomsAPI.delete
Delete a room. Args: roomId(basestring): The ID of the room to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/rooms.py
def delete(self, roomId): """Delete a room. Args: roomId(basestring): The ID of the room to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(roomId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + roomId)
def delete(self, roomId): """Delete a room. Args: roomId(basestring): The ID of the room to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(roomId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + roomId)
[ "Delete", "a", "room", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/rooms.py#L224-L238
[ "def", "delete", "(", "self", ",", "roomId", ")", ":", "check_type", "(", "roomId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "# API request", "self", ".", "_session", ".", "delete", "(", "API_ENDPOINT", "+", "'/'", "+", "roomId", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
LicensesAPI.list
List all licenses for a given organization. If no orgId is specified, the default is the organization of the authenticated user. Args: orgId(basestring): Specify the organization, by ID. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the licenses returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/licenses.py
def list(self, orgId=None, **request_parameters): """List all licenses for a given organization. If no orgId is specified, the default is the organization of the authenticated user. Args: orgId(basestring): Specify the organization, by ID. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the licenses returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(orgId, basestring) params = dict_from_items_with_values( request_parameters, orgId=orgId, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield license objects created from the returned JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
def list(self, orgId=None, **request_parameters): """List all licenses for a given organization. If no orgId is specified, the default is the organization of the authenticated user. Args: orgId(basestring): Specify the organization, by ID. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the licenses returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(orgId, basestring) params = dict_from_items_with_values( request_parameters, orgId=orgId, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield license objects created from the returned JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
[ "List", "all", "licenses", "for", "a", "given", "organization", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/licenses.py#L76-L108
[ "def", "list", "(", "self", ",", "orgId", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "orgId", ",", "basestring", ")", "params", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "orgId", "=", "orgId", ",", ")", "# API request - get items", "items", "=", "self", ".", "_session", ".", "get_items", "(", "API_ENDPOINT", ",", "params", "=", "params", ")", "# Yield license objects created from the returned JSON objects", "for", "item", "in", "items", ":", "yield", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "item", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
WebhookBasicPropertiesMixin.created
Creation date and time in ISO8601 format.
webexteamssdk/models/mixins/webhook.py
def created(self): """Creation date and time in ISO8601 format.""" created = self._json_data.get('created') if created: return WebexTeamsDateTime.strptime(created) else: return None
def created(self): """Creation date and time in ISO8601 format.""" created = self._json_data.get('created') if created: return WebexTeamsDateTime.strptime(created) else: return None
[ "Creation", "date", "and", "time", "in", "ISO8601", "format", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/models/mixins/webhook.py#L113-L119
[ "def", "created", "(", "self", ")", ":", "created", "=", "self", ".", "_json_data", ".", "get", "(", "'created'", ")", "if", "created", ":", "return", "WebexTeamsDateTime", ".", "strptime", "(", "created", ")", "else", ":", "return", "None" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
generator_container
Function Decorator: Containerize calls to a generator function. Args: generator_function(func): The generator function being containerized. Returns: func: A wrapper function that containerizes the calls to the generator function.
webexteamssdk/generator_containers.py
def generator_container(generator_function): """Function Decorator: Containerize calls to a generator function. Args: generator_function(func): The generator function being containerized. Returns: func: A wrapper function that containerizes the calls to the generator function. """ @functools.wraps(generator_function) def generator_container_wrapper(*args, **kwargs): """Store a generator call in a container and return the container. Args: *args: The arguments passed to the generator function. **kwargs: The keyword arguments passed to the generator function. Returns: GeneratorContainer: A container wrapping the call to the generator. """ return GeneratorContainer(generator_function, *args, **kwargs) return generator_container_wrapper
def generator_container(generator_function): """Function Decorator: Containerize calls to a generator function. Args: generator_function(func): The generator function being containerized. Returns: func: A wrapper function that containerizes the calls to the generator function. """ @functools.wraps(generator_function) def generator_container_wrapper(*args, **kwargs): """Store a generator call in a container and return the container. Args: *args: The arguments passed to the generator function. **kwargs: The keyword arguments passed to the generator function. Returns: GeneratorContainer: A container wrapping the call to the generator. """ return GeneratorContainer(generator_function, *args, **kwargs) return generator_container_wrapper
[ "Function", "Decorator", ":", "Containerize", "calls", "to", "a", "generator", "function", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/generator_containers.py#L140-L166
[ "def", "generator_container", "(", "generator_function", ")", ":", "@", "functools", ".", "wraps", "(", "generator_function", ")", "def", "generator_container_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Store a generator call in a container and return the container.\n\n Args:\n *args: The arguments passed to the generator function.\n **kwargs: The keyword arguments passed to the generator function.\n\n Returns:\n GeneratorContainer: A container wrapping the call to the generator.\n\n \"\"\"", "return", "GeneratorContainer", "(", "generator_function", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "generator_container_wrapper" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
webex_teams_webhook_events
Processes incoming requests to the '/events' URI.
examples/bot-example-flask.py
def webex_teams_webhook_events(): """Processes incoming requests to the '/events' URI.""" if request.method == 'GET': return ("""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Webex Teams Bot served via Flask</title> </head> <body> <p> <strong>Your Flask web server is up and running!</strong> </p> <p> Here is a nice Cat Fact for you: </p> <blockquote>{}</blockquote> </body> </html> """.format(get_catfact())) elif request.method == 'POST': """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # Message was sent by someone else; parse message and respond. if "/CAT" in message.text: print("FOUND '/CAT'") # Get a cat fact cat_fact = get_catfact() print("SENDING CAT FACT '{}'".format(cat_fact)) # Post the fact to the room where the request was received api.messages.create(room.id, text=cat_fact) return 'OK'
def webex_teams_webhook_events(): """Processes incoming requests to the '/events' URI.""" if request.method == 'GET': return ("""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Webex Teams Bot served via Flask</title> </head> <body> <p> <strong>Your Flask web server is up and running!</strong> </p> <p> Here is a nice Cat Fact for you: </p> <blockquote>{}</blockquote> </body> </html> """.format(get_catfact())) elif request.method == 'POST': """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json print("\n") print("WEBHOOK POST RECEIVED:") print(json_data) print("\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) print("NEW MESSAGE IN ROOM '{}'".format(room.title)) print("FROM '{}'".format(person.displayName)) print("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return 'OK' else: # Message was sent by someone else; parse message and respond. if "/CAT" in message.text: print("FOUND '/CAT'") # Get a cat fact cat_fact = get_catfact() print("SENDING CAT FACT '{}'".format(cat_fact)) # Post the fact to the room where the request was received api.messages.create(room.id, text=cat_fact) return 'OK'
[ "Processes", "incoming", "requests", "to", "the", "/", "events", "URI", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/examples/bot-example-flask.py#L98-L158
[ "def", "webex_teams_webhook_events", "(", ")", ":", "if", "request", ".", "method", "==", "'GET'", ":", "return", "(", "\"\"\"<!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>Webex Teams Bot served via Flask</title>\n </head>\n <body>\n <p>\n <strong>Your Flask web server is up and running!</strong>\n </p>\n <p>\n Here is a nice Cat Fact for you:\n </p>\n <blockquote>{}</blockquote>\n </body>\n </html>\n \"\"\"", ".", "format", "(", "get_catfact", "(", ")", ")", ")", "elif", "request", ".", "method", "==", "'POST'", ":", "\"\"\"Respond to inbound webhook JSON HTTP POST from Webex Teams.\"\"\"", "# Get the POST data sent from Webex Teams", "json_data", "=", "request", ".", "json", "print", "(", "\"\\n\"", ")", "print", "(", "\"WEBHOOK POST RECEIVED:\"", ")", "print", "(", "json_data", ")", "print", "(", "\"\\n\"", ")", "# Create a Webhook object from the JSON data", "webhook_obj", "=", "Webhook", "(", "json_data", ")", "# Get the room details", "room", "=", "api", ".", "rooms", ".", "get", "(", "webhook_obj", ".", "data", ".", "roomId", ")", "# Get the message details", "message", "=", "api", ".", "messages", ".", "get", "(", "webhook_obj", ".", "data", ".", "id", ")", "# Get the sender's details", "person", "=", "api", ".", "people", ".", "get", "(", "message", ".", "personId", ")", "print", "(", "\"NEW MESSAGE IN ROOM '{}'\"", ".", "format", "(", "room", ".", "title", ")", ")", "print", "(", "\"FROM '{}'\"", ".", "format", "(", "person", ".", "displayName", ")", ")", "print", "(", "\"MESSAGE '{}'\\n\"", ".", "format", "(", "message", ".", "text", ")", ")", "# This is a VERY IMPORTANT loop prevention control step.", "# If you respond to all messages... You will respond to the messages", "# that the bot posts and thereby create a loop condition.", "me", "=", "api", ".", "people", ".", "me", "(", ")", "if", "message", ".", "personId", "==", "me", ".", "id", ":", "# Message was sent by me (bot); do not respond.", "return", "'OK'", "else", ":", "# Message was sent by someone else; parse message and respond.", "if", "\"/CAT\"", "in", "message", ".", "text", ":", "print", "(", "\"FOUND '/CAT'\"", ")", "# Get a cat fact", "cat_fact", "=", "get_catfact", "(", ")", "print", "(", "\"SENDING CAT FACT '{}'\"", ".", "format", "(", "cat_fact", ")", ")", "# Post the fact to the room where the request was received", "api", ".", "messages", ".", "create", "(", "room", ".", "id", ",", "text", "=", "cat_fact", ")", "return", "'OK'" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
_get_access_token
Attempt to get the access token from the environment. Try using the current and legacy environment variables. If the access token is found in a legacy environment variable, raise a deprecation warning. Returns: The access token found in the environment (str), or None.
webexteamssdk/environment.py
def _get_access_token(): """Attempt to get the access token from the environment. Try using the current and legacy environment variables. If the access token is found in a legacy environment variable, raise a deprecation warning. Returns: The access token found in the environment (str), or None. """ access_token = os.environ.get(ACCESS_TOKEN_ENVIRONMENT_VARIABLE) if access_token: return access_token else: for access_token_variable in LEGACY_ACCESS_TOKEN_ENVIRONMENT_VARIABLES: access_token = os.environ.get(access_token_variable) if access_token: env_var_deprecation_warning = PendingDeprecationWarning( "Use of the `{legacy}` environment variable will be " "deprecated in the future. Please update your " "environment(s) to use the new `{new}` environment " "variable.".format( legacy=access_token, new=ACCESS_TOKEN_ENVIRONMENT_VARIABLE, ) ) warnings.warn(env_var_deprecation_warning) return access_token
def _get_access_token(): """Attempt to get the access token from the environment. Try using the current and legacy environment variables. If the access token is found in a legacy environment variable, raise a deprecation warning. Returns: The access token found in the environment (str), or None. """ access_token = os.environ.get(ACCESS_TOKEN_ENVIRONMENT_VARIABLE) if access_token: return access_token else: for access_token_variable in LEGACY_ACCESS_TOKEN_ENVIRONMENT_VARIABLES: access_token = os.environ.get(access_token_variable) if access_token: env_var_deprecation_warning = PendingDeprecationWarning( "Use of the `{legacy}` environment variable will be " "deprecated in the future. Please update your " "environment(s) to use the new `{new}` environment " "variable.".format( legacy=access_token, new=ACCESS_TOKEN_ENVIRONMENT_VARIABLE, ) ) warnings.warn(env_var_deprecation_warning) return access_token
[ "Attempt", "to", "get", "the", "access", "token", "from", "the", "environment", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/environment.py#L36-L63
[ "def", "_get_access_token", "(", ")", ":", "access_token", "=", "os", ".", "environ", ".", "get", "(", "ACCESS_TOKEN_ENVIRONMENT_VARIABLE", ")", "if", "access_token", ":", "return", "access_token", "else", ":", "for", "access_token_variable", "in", "LEGACY_ACCESS_TOKEN_ENVIRONMENT_VARIABLES", ":", "access_token", "=", "os", ".", "environ", ".", "get", "(", "access_token_variable", ")", "if", "access_token", ":", "env_var_deprecation_warning", "=", "PendingDeprecationWarning", "(", "\"Use of the `{legacy}` environment variable will be \"", "\"deprecated in the future. Please update your \"", "\"environment(s) to use the new `{new}` environment \"", "\"variable.\"", ".", "format", "(", "legacy", "=", "access_token", ",", "new", "=", "ACCESS_TOKEN_ENVIRONMENT_VARIABLE", ",", ")", ")", "warnings", ".", "warn", "(", "env_var_deprecation_warning", ")", "return", "access_token" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
WebhooksAPI.create
Create a webhook. Args: name(basestring): A user-friendly name for this webhook. targetUrl(basestring): The URL that receives POST requests for each event. resource(basestring): The resource type for the webhook. event(basestring): The event type for the webhook. filter(basestring): The filter that defines the webhook scope. secret(basestring): The secret used to generate payload signature. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Webhook: A Webhook object with the details of the created webhook. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/webhooks.py
def create(self, name, targetUrl, resource, event, filter=None, secret=None, **request_parameters): """Create a webhook. Args: name(basestring): A user-friendly name for this webhook. targetUrl(basestring): The URL that receives POST requests for each event. resource(basestring): The resource type for the webhook. event(basestring): The event type for the webhook. filter(basestring): The filter that defines the webhook scope. secret(basestring): The secret used to generate payload signature. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Webhook: A Webhook object with the details of the created webhook. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(name, basestring, may_be_none=False) check_type(targetUrl, basestring, may_be_none=False) check_type(resource, basestring, may_be_none=False) check_type(event, basestring, may_be_none=False) check_type(filter, basestring) check_type(secret, basestring) post_data = dict_from_items_with_values( request_parameters, name=name, targetUrl=targetUrl, resource=resource, event=event, filter=filter, secret=secret, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a webhook object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def create(self, name, targetUrl, resource, event, filter=None, secret=None, **request_parameters): """Create a webhook. Args: name(basestring): A user-friendly name for this webhook. targetUrl(basestring): The URL that receives POST requests for each event. resource(basestring): The resource type for the webhook. event(basestring): The event type for the webhook. filter(basestring): The filter that defines the webhook scope. secret(basestring): The secret used to generate payload signature. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Webhook: A Webhook object with the details of the created webhook. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(name, basestring, may_be_none=False) check_type(targetUrl, basestring, may_be_none=False) check_type(resource, basestring, may_be_none=False) check_type(event, basestring, may_be_none=False) check_type(filter, basestring) check_type(secret, basestring) post_data = dict_from_items_with_values( request_parameters, name=name, targetUrl=targetUrl, resource=resource, event=event, filter=filter, secret=secret, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a webhook object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Create", "a", "webhook", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/webhooks.py#L118-L162
[ "def", "create", "(", "self", ",", "name", ",", "targetUrl", ",", "resource", ",", "event", ",", "filter", "=", "None", ",", "secret", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "name", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "targetUrl", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "resource", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "event", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "filter", ",", "basestring", ")", "check_type", "(", "secret", ",", "basestring", ")", "post_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "name", "=", "name", ",", "targetUrl", "=", "targetUrl", ",", "resource", "=", "resource", ",", "event", "=", "event", ",", "filter", "=", "filter", ",", "secret", "=", "secret", ",", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "post", "(", "API_ENDPOINT", ",", "json", "=", "post_data", ")", "# Return a webhook object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
WebhooksAPI.update
Update a webhook, by ID. Args: webhookId(basestring): The webhook ID. name(basestring): A user-friendly name for this webhook. targetUrl(basestring): The URL that receives POST requests for each event. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Webhook: A Webhook object with the updated Webex Teams webhook details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/webhooks.py
def update(self, webhookId, name=None, targetUrl=None, **request_parameters): """Update a webhook, by ID. Args: webhookId(basestring): The webhook ID. name(basestring): A user-friendly name for this webhook. targetUrl(basestring): The URL that receives POST requests for each event. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Webhook: A Webhook object with the updated Webex Teams webhook details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(webhookId, basestring, may_be_none=False) check_type(name, basestring) check_type(targetUrl, basestring) put_data = dict_from_items_with_values( request_parameters, name=name, targetUrl=targetUrl, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + webhookId, json=put_data) # Return a webhook object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def update(self, webhookId, name=None, targetUrl=None, **request_parameters): """Update a webhook, by ID. Args: webhookId(basestring): The webhook ID. name(basestring): A user-friendly name for this webhook. targetUrl(basestring): The URL that receives POST requests for each event. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Webhook: A Webhook object with the updated Webex Teams webhook details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(webhookId, basestring, may_be_none=False) check_type(name, basestring) check_type(targetUrl, basestring) put_data = dict_from_items_with_values( request_parameters, name=name, targetUrl=targetUrl, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + webhookId, json=put_data) # Return a webhook object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Update", "a", "webhook", "by", "ID", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/webhooks.py#L187-L223
[ "def", "update", "(", "self", ",", "webhookId", ",", "name", "=", "None", ",", "targetUrl", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "webhookId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "name", ",", "basestring", ")", "check_type", "(", "targetUrl", ",", "basestring", ")", "put_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "name", "=", "name", ",", "targetUrl", "=", "targetUrl", ",", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "put", "(", "API_ENDPOINT", "+", "'/'", "+", "webhookId", ",", "json", "=", "put_data", ")", "# Return a webhook object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
WebhooksAPI.delete
Delete a webhook, by ID. Args: webhookId(basestring): The ID of the webhook to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/webhooks.py
def delete(self, webhookId): """Delete a webhook, by ID. Args: webhookId(basestring): The ID of the webhook to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(webhookId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + webhookId)
def delete(self, webhookId): """Delete a webhook, by ID. Args: webhookId(basestring): The ID of the webhook to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(webhookId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + webhookId)
[ "Delete", "a", "webhook", "by", "ID", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/webhooks.py#L225-L239
[ "def", "delete", "(", "self", ",", "webhookId", ")", ":", "check_type", "(", "webhookId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "# API request", "self", ".", "_session", ".", "delete", "(", "API_ENDPOINT", "+", "'/'", "+", "webhookId", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
_fix_next_url
Remove max=null parameter from URL. Patch for Webex Teams Defect: 'next' URL returned in the Link headers of the responses contain an errant 'max=null' parameter, which causes the next request (to this URL) to fail if the URL is requested as-is. This patch parses the next_url to remove the max=null parameter. Args: next_url(basestring): The 'next' URL to be parsed and cleaned. Returns: basestring: The clean URL to be used for the 'next' request. Raises: AssertionError: If the parameter types are incorrect. ValueError: If 'next_url' does not contain a valid API endpoint URL (scheme, netloc and path).
webexteamssdk/restsession.py
def _fix_next_url(next_url): """Remove max=null parameter from URL. Patch for Webex Teams Defect: 'next' URL returned in the Link headers of the responses contain an errant 'max=null' parameter, which causes the next request (to this URL) to fail if the URL is requested as-is. This patch parses the next_url to remove the max=null parameter. Args: next_url(basestring): The 'next' URL to be parsed and cleaned. Returns: basestring: The clean URL to be used for the 'next' request. Raises: AssertionError: If the parameter types are incorrect. ValueError: If 'next_url' does not contain a valid API endpoint URL (scheme, netloc and path). """ next_url = str(next_url) parsed_url = urllib.parse.urlparse(next_url) if not parsed_url.scheme or not parsed_url.netloc or not parsed_url.path: raise ValueError( "'next_url' must be a valid API endpoint URL, minimally " "containing a scheme, netloc and path." ) if parsed_url.query: query_list = parsed_url.query.split('&') if 'max=null' in query_list: query_list.remove('max=null') warnings.warn("`max=null` still present in next-URL returned " "from Webex Teams", RuntimeWarning) new_query = '&'.join(query_list) parsed_url = list(parsed_url) parsed_url[4] = new_query return urllib.parse.urlunparse(parsed_url)
def _fix_next_url(next_url): """Remove max=null parameter from URL. Patch for Webex Teams Defect: 'next' URL returned in the Link headers of the responses contain an errant 'max=null' parameter, which causes the next request (to this URL) to fail if the URL is requested as-is. This patch parses the next_url to remove the max=null parameter. Args: next_url(basestring): The 'next' URL to be parsed and cleaned. Returns: basestring: The clean URL to be used for the 'next' request. Raises: AssertionError: If the parameter types are incorrect. ValueError: If 'next_url' does not contain a valid API endpoint URL (scheme, netloc and path). """ next_url = str(next_url) parsed_url = urllib.parse.urlparse(next_url) if not parsed_url.scheme or not parsed_url.netloc or not parsed_url.path: raise ValueError( "'next_url' must be a valid API endpoint URL, minimally " "containing a scheme, netloc and path." ) if parsed_url.query: query_list = parsed_url.query.split('&') if 'max=null' in query_list: query_list.remove('max=null') warnings.warn("`max=null` still present in next-URL returned " "from Webex Teams", RuntimeWarning) new_query = '&'.join(query_list) parsed_url = list(parsed_url) parsed_url[4] = new_query return urllib.parse.urlunparse(parsed_url)
[ "Remove", "max", "=", "null", "parameter", "from", "URL", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L53-L93
[ "def", "_fix_next_url", "(", "next_url", ")", ":", "next_url", "=", "str", "(", "next_url", ")", "parsed_url", "=", "urllib", ".", "parse", ".", "urlparse", "(", "next_url", ")", "if", "not", "parsed_url", ".", "scheme", "or", "not", "parsed_url", ".", "netloc", "or", "not", "parsed_url", ".", "path", ":", "raise", "ValueError", "(", "\"'next_url' must be a valid API endpoint URL, minimally \"", "\"containing a scheme, netloc and path.\"", ")", "if", "parsed_url", ".", "query", ":", "query_list", "=", "parsed_url", ".", "query", ".", "split", "(", "'&'", ")", "if", "'max=null'", "in", "query_list", ":", "query_list", ".", "remove", "(", "'max=null'", ")", "warnings", ".", "warn", "(", "\"`max=null` still present in next-URL returned \"", "\"from Webex Teams\"", ",", "RuntimeWarning", ")", "new_query", "=", "'&'", ".", "join", "(", "query_list", ")", "parsed_url", "=", "list", "(", "parsed_url", ")", "parsed_url", "[", "4", "]", "=", "new_query", "return", "urllib", ".", "parse", ".", "urlunparse", "(", "parsed_url", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RestSession.single_request_timeout
The timeout (seconds) for a single HTTP REST API request.
webexteamssdk/restsession.py
def single_request_timeout(self, value): """The timeout (seconds) for a single HTTP REST API request.""" check_type(value, int) assert value is None or value > 0 self._single_request_timeout = value
def single_request_timeout(self, value): """The timeout (seconds) for a single HTTP REST API request.""" check_type(value, int) assert value is None or value > 0 self._single_request_timeout = value
[ "The", "timeout", "(", "seconds", ")", "for", "a", "single", "HTTP", "REST", "API", "request", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L155-L159
[ "def", "single_request_timeout", "(", "self", ",", "value", ")", ":", "check_type", "(", "value", ",", "int", ")", "assert", "value", "is", "None", "or", "value", ">", "0", "self", ".", "_single_request_timeout", "=", "value" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RestSession.wait_on_rate_limit
Enable or disable automatic rate-limit handling.
webexteamssdk/restsession.py
def wait_on_rate_limit(self, value): """Enable or disable automatic rate-limit handling.""" check_type(value, bool, may_be_none=False) self._wait_on_rate_limit = value
def wait_on_rate_limit(self, value): """Enable or disable automatic rate-limit handling.""" check_type(value, bool, may_be_none=False) self._wait_on_rate_limit = value
[ "Enable", "or", "disable", "automatic", "rate", "-", "limit", "handling", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L174-L177
[ "def", "wait_on_rate_limit", "(", "self", ",", "value", ")", ":", "check_type", "(", "value", ",", "bool", ",", "may_be_none", "=", "False", ")", "self", ".", "_wait_on_rate_limit", "=", "value" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RestSession.update_headers
Update the HTTP headers used for requests in this session. Note: Updates provided by the dictionary passed as the `headers` parameter to this method are merged into the session headers by adding new key-value pairs and/or updating the values of existing keys. The session headers are not replaced by the provided dictionary. Args: headers(dict): Updates to the current session headers.
webexteamssdk/restsession.py
def update_headers(self, headers): """Update the HTTP headers used for requests in this session. Note: Updates provided by the dictionary passed as the `headers` parameter to this method are merged into the session headers by adding new key-value pairs and/or updating the values of existing keys. The session headers are not replaced by the provided dictionary. Args: headers(dict): Updates to the current session headers. """ check_type(headers, dict, may_be_none=False) self._req_session.headers.update(headers)
def update_headers(self, headers): """Update the HTTP headers used for requests in this session. Note: Updates provided by the dictionary passed as the `headers` parameter to this method are merged into the session headers by adding new key-value pairs and/or updating the values of existing keys. The session headers are not replaced by the provided dictionary. Args: headers(dict): Updates to the current session headers. """ check_type(headers, dict, may_be_none=False) self._req_session.headers.update(headers)
[ "Update", "the", "HTTP", "headers", "used", "for", "requests", "in", "this", "session", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L184-L197
[ "def", "update_headers", "(", "self", ",", "headers", ")", ":", "check_type", "(", "headers", ",", "dict", ",", "may_be_none", "=", "False", ")", "self", ".", "_req_session", ".", "headers", ".", "update", "(", "headers", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RestSession.abs_url
Given a relative or absolute URL; return an absolute URL. Args: url(basestring): A relative or absolute URL. Returns: str: An absolute URL.
webexteamssdk/restsession.py
def abs_url(self, url): """Given a relative or absolute URL; return an absolute URL. Args: url(basestring): A relative or absolute URL. Returns: str: An absolute URL. """ parsed_url = urllib.parse.urlparse(url) if not parsed_url.scheme and not parsed_url.netloc: # url is a relative URL; combine with base_url return urllib.parse.urljoin(str(self.base_url), str(url)) else: # url is already an absolute URL; return as is return url
def abs_url(self, url): """Given a relative or absolute URL; return an absolute URL. Args: url(basestring): A relative or absolute URL. Returns: str: An absolute URL. """ parsed_url = urllib.parse.urlparse(url) if not parsed_url.scheme and not parsed_url.netloc: # url is a relative URL; combine with base_url return urllib.parse.urljoin(str(self.base_url), str(url)) else: # url is already an absolute URL; return as is return url
[ "Given", "a", "relative", "or", "absolute", "URL", ";", "return", "an", "absolute", "URL", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L199-L215
[ "def", "abs_url", "(", "self", ",", "url", ")", ":", "parsed_url", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "if", "not", "parsed_url", ".", "scheme", "and", "not", "parsed_url", ".", "netloc", ":", "# url is a relative URL; combine with base_url", "return", "urllib", ".", "parse", ".", "urljoin", "(", "str", "(", "self", ".", "base_url", ")", ",", "str", "(", "url", ")", ")", "else", ":", "# url is already an absolute URL; return as is", "return", "url" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RestSession.request
Abstract base method for making requests to the Webex Teams APIs. This base method: * Expands the API endpoint URL to an absolute URL * Makes the actual HTTP request to the API endpoint * Provides support for Webex Teams rate-limiting * Inspects response codes and raises exceptions as appropriate Args: method(basestring): The request-method type ('GET', 'POST', etc.). url(basestring): The URL of the API endpoint to be called. erc(int): The expected response code that should be returned by the Webex Teams API endpoint to indicate success. **kwargs: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint.
webexteamssdk/restsession.py
def request(self, method, url, erc, **kwargs): """Abstract base method for making requests to the Webex Teams APIs. This base method: * Expands the API endpoint URL to an absolute URL * Makes the actual HTTP request to the API endpoint * Provides support for Webex Teams rate-limiting * Inspects response codes and raises exceptions as appropriate Args: method(basestring): The request-method type ('GET', 'POST', etc.). url(basestring): The URL of the API endpoint to be called. erc(int): The expected response code that should be returned by the Webex Teams API endpoint to indicate success. **kwargs: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ # Ensure the url is an absolute URL abs_url = self.abs_url(url) # Update request kwargs with session defaults kwargs.setdefault('timeout', self.single_request_timeout) while True: # Make the HTTP request to the API endpoint response = self._req_session.request(method, abs_url, **kwargs) try: # Check the response code for error conditions check_response_code(response, erc) except RateLimitError as e: # Catch rate-limit errors # Wait and retry if automatic rate-limit handling is enabled if self.wait_on_rate_limit: warnings.warn(RateLimitWarning(response)) time.sleep(e.retry_after) continue else: # Re-raise the RateLimitError raise else: return response
def request(self, method, url, erc, **kwargs): """Abstract base method for making requests to the Webex Teams APIs. This base method: * Expands the API endpoint URL to an absolute URL * Makes the actual HTTP request to the API endpoint * Provides support for Webex Teams rate-limiting * Inspects response codes and raises exceptions as appropriate Args: method(basestring): The request-method type ('GET', 'POST', etc.). url(basestring): The URL of the API endpoint to be called. erc(int): The expected response code that should be returned by the Webex Teams API endpoint to indicate success. **kwargs: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ # Ensure the url is an absolute URL abs_url = self.abs_url(url) # Update request kwargs with session defaults kwargs.setdefault('timeout', self.single_request_timeout) while True: # Make the HTTP request to the API endpoint response = self._req_session.request(method, abs_url, **kwargs) try: # Check the response code for error conditions check_response_code(response, erc) except RateLimitError as e: # Catch rate-limit errors # Wait and retry if automatic rate-limit handling is enabled if self.wait_on_rate_limit: warnings.warn(RateLimitWarning(response)) time.sleep(e.retry_after) continue else: # Re-raise the RateLimitError raise else: return response
[ "Abstract", "base", "method", "for", "making", "requests", "to", "the", "Webex", "Teams", "APIs", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L217-L262
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "erc", ",", "*", "*", "kwargs", ")", ":", "# Ensure the url is an absolute URL", "abs_url", "=", "self", ".", "abs_url", "(", "url", ")", "# Update request kwargs with session defaults", "kwargs", ".", "setdefault", "(", "'timeout'", ",", "self", ".", "single_request_timeout", ")", "while", "True", ":", "# Make the HTTP request to the API endpoint", "response", "=", "self", ".", "_req_session", ".", "request", "(", "method", ",", "abs_url", ",", "*", "*", "kwargs", ")", "try", ":", "# Check the response code for error conditions", "check_response_code", "(", "response", ",", "erc", ")", "except", "RateLimitError", "as", "e", ":", "# Catch rate-limit errors", "# Wait and retry if automatic rate-limit handling is enabled", "if", "self", ".", "wait_on_rate_limit", ":", "warnings", ".", "warn", "(", "RateLimitWarning", "(", "response", ")", ")", "time", ".", "sleep", "(", "e", ".", "retry_after", ")", "continue", "else", ":", "# Re-raise the RateLimitError", "raise", "else", ":", "return", "response" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RestSession.get
Sends a GET request. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint.
webexteamssdk/restsession.py
def get(self, url, params=None, **kwargs): """Sends a GET request. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) check_type(params, dict) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['GET']) response = self.request('GET', url, erc, params=params, **kwargs) return extract_and_parse_json(response)
def get(self, url, params=None, **kwargs): """Sends a GET request. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) check_type(params, dict) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['GET']) response = self.request('GET', url, erc, params=params, **kwargs) return extract_and_parse_json(response)
[ "Sends", "a", "GET", "request", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L264-L286
[ "def", "get", "(", "self", ",", "url", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "check_type", "(", "url", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "params", ",", "dict", ")", "# Expected response code", "erc", "=", "kwargs", ".", "pop", "(", "'erc'", ",", "EXPECTED_RESPONSE_CODE", "[", "'GET'", "]", ")", "response", "=", "self", ".", "request", "(", "'GET'", ",", "url", ",", "erc", ",", "params", "=", "params", ",", "*", "*", "kwargs", ")", "return", "extract_and_parse_json", "(", "response", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RestSession.get_pages
Return a generator that GETs and yields pages of data. Provides native support for RFC5988 Web Linking. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint.
webexteamssdk/restsession.py
def get_pages(self, url, params=None, **kwargs): """Return a generator that GETs and yields pages of data. Provides native support for RFC5988 Web Linking. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) check_type(params, dict) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['GET']) # First request response = self.request('GET', url, erc, params=params, **kwargs) while True: yield extract_and_parse_json(response) if response.links.get('next'): next_url = response.links.get('next').get('url') # Patch for Webex Teams 'max=null' in next URL bug. # Testing shows that patch is no longer needed; raising a # warnning if it is still taking effect; # considering for future removal next_url = _fix_next_url(next_url) # Subsequent requests response = self.request('GET', next_url, erc, **kwargs) else: break
def get_pages(self, url, params=None, **kwargs): """Return a generator that GETs and yields pages of data. Provides native support for RFC5988 Web Linking. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) check_type(params, dict) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['GET']) # First request response = self.request('GET', url, erc, params=params, **kwargs) while True: yield extract_and_parse_json(response) if response.links.get('next'): next_url = response.links.get('next').get('url') # Patch for Webex Teams 'max=null' in next URL bug. # Testing shows that patch is no longer needed; raising a # warnning if it is still taking effect; # considering for future removal next_url = _fix_next_url(next_url) # Subsequent requests response = self.request('GET', next_url, erc, **kwargs) else: break
[ "Return", "a", "generator", "that", "GETs", "and", "yields", "pages", "of", "data", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L288-L330
[ "def", "get_pages", "(", "self", ",", "url", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "check_type", "(", "url", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "params", ",", "dict", ")", "# Expected response code", "erc", "=", "kwargs", ".", "pop", "(", "'erc'", ",", "EXPECTED_RESPONSE_CODE", "[", "'GET'", "]", ")", "# First request", "response", "=", "self", ".", "request", "(", "'GET'", ",", "url", ",", "erc", ",", "params", "=", "params", ",", "*", "*", "kwargs", ")", "while", "True", ":", "yield", "extract_and_parse_json", "(", "response", ")", "if", "response", ".", "links", ".", "get", "(", "'next'", ")", ":", "next_url", "=", "response", ".", "links", ".", "get", "(", "'next'", ")", ".", "get", "(", "'url'", ")", "# Patch for Webex Teams 'max=null' in next URL bug.", "# Testing shows that patch is no longer needed; raising a", "# warnning if it is still taking effect;", "# considering for future removal", "next_url", "=", "_fix_next_url", "(", "next_url", ")", "# Subsequent requests", "response", "=", "self", ".", "request", "(", "'GET'", ",", "next_url", ",", "erc", ",", "*", "*", "kwargs", ")", "else", ":", "break" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RestSession.get_items
Return a generator that GETs and yields individual JSON `items`. Yields individual `items` from Webex Teams's top-level {'items': [...]} JSON objects. Provides native support for RFC5988 Web Linking. The generator will request additional pages as needed until all items have been returned. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. MalformedResponse: If the returned response does not contain a top-level dictionary with an 'items' key.
webexteamssdk/restsession.py
def get_items(self, url, params=None, **kwargs): """Return a generator that GETs and yields individual JSON `items`. Yields individual `items` from Webex Teams's top-level {'items': [...]} JSON objects. Provides native support for RFC5988 Web Linking. The generator will request additional pages as needed until all items have been returned. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. MalformedResponse: If the returned response does not contain a top-level dictionary with an 'items' key. """ # Get generator for pages of JSON data pages = self.get_pages(url, params=params, **kwargs) for json_page in pages: assert isinstance(json_page, dict) items = json_page.get('items') if items is None: error_message = "'items' key not found in JSON data: " \ "{!r}".format(json_page) raise MalformedResponse(error_message) else: for item in items: yield item
def get_items(self, url, params=None, **kwargs): """Return a generator that GETs and yields individual JSON `items`. Yields individual `items` from Webex Teams's top-level {'items': [...]} JSON objects. Provides native support for RFC5988 Web Linking. The generator will request additional pages as needed until all items have been returned. Args: url(basestring): The URL of the API endpoint. params(dict): The parameters for the HTTP GET request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. MalformedResponse: If the returned response does not contain a top-level dictionary with an 'items' key. """ # Get generator for pages of JSON data pages = self.get_pages(url, params=params, **kwargs) for json_page in pages: assert isinstance(json_page, dict) items = json_page.get('items') if items is None: error_message = "'items' key not found in JSON data: " \ "{!r}".format(json_page) raise MalformedResponse(error_message) else: for item in items: yield item
[ "Return", "a", "generator", "that", "GETs", "and", "yields", "individual", "JSON", "items", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L332-L369
[ "def", "get_items", "(", "self", ",", "url", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Get generator for pages of JSON data", "pages", "=", "self", ".", "get_pages", "(", "url", ",", "params", "=", "params", ",", "*", "*", "kwargs", ")", "for", "json_page", "in", "pages", ":", "assert", "isinstance", "(", "json_page", ",", "dict", ")", "items", "=", "json_page", ".", "get", "(", "'items'", ")", "if", "items", "is", "None", ":", "error_message", "=", "\"'items' key not found in JSON data: \"", "\"{!r}\"", ".", "format", "(", "json_page", ")", "raise", "MalformedResponse", "(", "error_message", ")", "else", ":", "for", "item", "in", "items", ":", "yield", "item" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RestSession.put
Sends a PUT request. Args: url(basestring): The URL of the API endpoint. json: Data to be sent in JSON format in tbe body of the request. data: Data to be sent in the body of the request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint.
webexteamssdk/restsession.py
def put(self, url, json=None, data=None, **kwargs): """Sends a PUT request. Args: url(basestring): The URL of the API endpoint. json: Data to be sent in JSON format in tbe body of the request. data: Data to be sent in the body of the request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['PUT']) response = self.request('PUT', url, erc, json=json, data=data, **kwargs) return extract_and_parse_json(response)
def put(self, url, json=None, data=None, **kwargs): """Sends a PUT request. Args: url(basestring): The URL of the API endpoint. json: Data to be sent in JSON format in tbe body of the request. data: Data to be sent in the body of the request. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['PUT']) response = self.request('PUT', url, erc, json=json, data=data, **kwargs) return extract_and_parse_json(response)
[ "Sends", "a", "PUT", "request", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L396-L419
[ "def", "put", "(", "self", ",", "url", ",", "json", "=", "None", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "check_type", "(", "url", ",", "basestring", ",", "may_be_none", "=", "False", ")", "# Expected response code", "erc", "=", "kwargs", ".", "pop", "(", "'erc'", ",", "EXPECTED_RESPONSE_CODE", "[", "'PUT'", "]", ")", "response", "=", "self", ".", "request", "(", "'PUT'", ",", "url", ",", "erc", ",", "json", "=", "json", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")", "return", "extract_and_parse_json", "(", "response", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RestSession.delete
Sends a DELETE request. Args: url(basestring): The URL of the API endpoint. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint.
webexteamssdk/restsession.py
def delete(self, url, **kwargs): """Sends a DELETE request. Args: url(basestring): The URL of the API endpoint. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['DELETE']) self.request('DELETE', url, erc, **kwargs)
def delete(self, url, **kwargs): """Sends a DELETE request. Args: url(basestring): The URL of the API endpoint. **kwargs: erc(int): The expected (success) response code for the request. others: Passed on to the requests package. Raises: ApiError: If anything other than the expected response code is returned by the Webex Teams API endpoint. """ check_type(url, basestring, may_be_none=False) # Expected response code erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['DELETE']) self.request('DELETE', url, erc, **kwargs)
[ "Sends", "a", "DELETE", "request", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/restsession.py#L421-L440
[ "def", "delete", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "check_type", "(", "url", ",", "basestring", ",", "may_be_none", "=", "False", ")", "# Expected response code", "erc", "=", "kwargs", ".", "pop", "(", "'erc'", ",", "EXPECTED_RESPONSE_CODE", "[", "'DELETE'", "]", ")", "self", ".", "request", "(", "'DELETE'", ",", "url", ",", "erc", ",", "*", "*", "kwargs", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
GuestIssuerAPI.create
Create a new guest issuer using the provided issuer token. This function returns a guest issuer with an api access token. Args: subject(basestring): Unique and public identifier displayName(basestring): Display Name of the guest user issuerToken(basestring): Issuer token from developer hub expiration(basestring): Expiration time as a unix timestamp secret(basestring): The secret used to sign your guest issuers Returns: GuestIssuerToken: A Guest Issuer with a valid access token. Raises: TypeError: If the parameter types are incorrect ApiError: If the webex teams cloud returns an error.
webexteamssdk/api/guest_issuer.py
def create(self, subject, displayName, issuerToken, expiration, secret): """Create a new guest issuer using the provided issuer token. This function returns a guest issuer with an api access token. Args: subject(basestring): Unique and public identifier displayName(basestring): Display Name of the guest user issuerToken(basestring): Issuer token from developer hub expiration(basestring): Expiration time as a unix timestamp secret(basestring): The secret used to sign your guest issuers Returns: GuestIssuerToken: A Guest Issuer with a valid access token. Raises: TypeError: If the parameter types are incorrect ApiError: If the webex teams cloud returns an error. """ check_type(subject, basestring) check_type(displayName, basestring) check_type(issuerToken, basestring) check_type(expiration, basestring) check_type(secret, basestring) payload = { "sub": subject, "name": displayName, "iss": issuerToken, "exp": expiration } key = base64.b64decode(secret) jwt_token = jwt.encode(payload, key, algorithm='HS256') url = self._session.base_url + API_ENDPOINT + "/" + "login" headers = { 'Authorization': "Bearer " + jwt_token.decode('utf-8') } response = requests.post(url, headers=headers) check_response_code(response, EXPECTED_RESPONSE_CODE['GET']) return self._object_factory(OBJECT_TYPE, response.json())
def create(self, subject, displayName, issuerToken, expiration, secret): """Create a new guest issuer using the provided issuer token. This function returns a guest issuer with an api access token. Args: subject(basestring): Unique and public identifier displayName(basestring): Display Name of the guest user issuerToken(basestring): Issuer token from developer hub expiration(basestring): Expiration time as a unix timestamp secret(basestring): The secret used to sign your guest issuers Returns: GuestIssuerToken: A Guest Issuer with a valid access token. Raises: TypeError: If the parameter types are incorrect ApiError: If the webex teams cloud returns an error. """ check_type(subject, basestring) check_type(displayName, basestring) check_type(issuerToken, basestring) check_type(expiration, basestring) check_type(secret, basestring) payload = { "sub": subject, "name": displayName, "iss": issuerToken, "exp": expiration } key = base64.b64decode(secret) jwt_token = jwt.encode(payload, key, algorithm='HS256') url = self._session.base_url + API_ENDPOINT + "/" + "login" headers = { 'Authorization': "Bearer " + jwt_token.decode('utf-8') } response = requests.post(url, headers=headers) check_response_code(response, EXPECTED_RESPONSE_CODE['GET']) return self._object_factory(OBJECT_TYPE, response.json())
[ "Create", "a", "new", "guest", "issuer", "using", "the", "provided", "issuer", "token", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/guest_issuer.py#L79-L121
[ "def", "create", "(", "self", ",", "subject", ",", "displayName", ",", "issuerToken", ",", "expiration", ",", "secret", ")", ":", "check_type", "(", "subject", ",", "basestring", ")", "check_type", "(", "displayName", ",", "basestring", ")", "check_type", "(", "issuerToken", ",", "basestring", ")", "check_type", "(", "expiration", ",", "basestring", ")", "check_type", "(", "secret", ",", "basestring", ")", "payload", "=", "{", "\"sub\"", ":", "subject", ",", "\"name\"", ":", "displayName", ",", "\"iss\"", ":", "issuerToken", ",", "\"exp\"", ":", "expiration", "}", "key", "=", "base64", ".", "b64decode", "(", "secret", ")", "jwt_token", "=", "jwt", ".", "encode", "(", "payload", ",", "key", ",", "algorithm", "=", "'HS256'", ")", "url", "=", "self", ".", "_session", ".", "base_url", "+", "API_ENDPOINT", "+", "\"/\"", "+", "\"login\"", "headers", "=", "{", "'Authorization'", ":", "\"Bearer \"", "+", "jwt_token", ".", "decode", "(", "'utf-8'", ")", "}", "response", "=", "requests", ".", "post", "(", "url", ",", "headers", "=", "headers", ")", "check_response_code", "(", "response", ",", "EXPECTED_RESPONSE_CODE", "[", "'GET'", "]", ")", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "response", ".", "json", "(", ")", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
MessagesAPI.list
Lists messages in a room. Each message will include content attachments if present. The list API sorts the messages in descending order by creation date. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all messages returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: roomId(basestring): List messages for a room, by ID. mentionedPeople(basestring): List messages where the caller is mentioned by specifying "me" or the caller `personId`. before(basestring): List messages sent before a date and time, in ISO8601 format. beforeMessage(basestring): List messages sent before a message, by ID. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the messages returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/messages.py
def list(self, roomId, mentionedPeople=None, before=None, beforeMessage=None, max=None, **request_parameters): """Lists messages in a room. Each message will include content attachments if present. The list API sorts the messages in descending order by creation date. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all messages returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: roomId(basestring): List messages for a room, by ID. mentionedPeople(basestring): List messages where the caller is mentioned by specifying "me" or the caller `personId`. before(basestring): List messages sent before a date and time, in ISO8601 format. beforeMessage(basestring): List messages sent before a message, by ID. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the messages returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(roomId, basestring, may_be_none=False) check_type(mentionedPeople, basestring) check_type(before, basestring) check_type(beforeMessage, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, roomId=roomId, mentionedPeople=mentionedPeople, before=before, beforeMessage=beforeMessage, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield message objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
def list(self, roomId, mentionedPeople=None, before=None, beforeMessage=None, max=None, **request_parameters): """Lists messages in a room. Each message will include content attachments if present. The list API sorts the messages in descending order by creation date. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all messages returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: roomId(basestring): List messages for a room, by ID. mentionedPeople(basestring): List messages where the caller is mentioned by specifying "me" or the caller `personId`. before(basestring): List messages sent before a date and time, in ISO8601 format. beforeMessage(basestring): List messages sent before a message, by ID. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the messages returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(roomId, basestring, may_be_none=False) check_type(mentionedPeople, basestring) check_type(before, basestring) check_type(beforeMessage, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, roomId=roomId, mentionedPeople=mentionedPeople, before=before, beforeMessage=beforeMessage, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield message objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
[ "Lists", "messages", "in", "a", "room", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/messages.py#L75-L135
[ "def", "list", "(", "self", ",", "roomId", ",", "mentionedPeople", "=", "None", ",", "before", "=", "None", ",", "beforeMessage", "=", "None", ",", "max", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "roomId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "mentionedPeople", ",", "basestring", ")", "check_type", "(", "before", ",", "basestring", ")", "check_type", "(", "beforeMessage", ",", "basestring", ")", "check_type", "(", "max", ",", "int", ")", "params", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "roomId", "=", "roomId", ",", "mentionedPeople", "=", "mentionedPeople", ",", "before", "=", "before", ",", "beforeMessage", "=", "beforeMessage", ",", "max", "=", "max", ",", ")", "# API request - get items", "items", "=", "self", ".", "_session", ".", "get_items", "(", "API_ENDPOINT", ",", "params", "=", "params", ")", "# Yield message objects created from the returned items JSON objects", "for", "item", "in", "items", ":", "yield", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "item", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
MessagesAPI.create
Post a message, and optionally a attachment, to a room. The files parameter is a list, which accepts multiple values to allow for future expansion, but currently only one file may be included with the message. Args: roomId(basestring): The room ID. toPersonId(basestring): The ID of the recipient when sending a private 1:1 message. toPersonEmail(basestring): The email address of the recipient when sending a private 1:1 message. text(basestring): The message, in plain text. If `markdown` is specified this parameter may be optionally used to provide alternate text for UI clients that do not support rich text. markdown(basestring): The message, in markdown format. files(`list`): A list of public URL(s) or local path(s) to files to be posted into the room. Only one file is allowed per message. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Message: A Message object with the details of the created message. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. ValueError: If the files parameter is a list of length > 1, or if the string in the list (the only element in the list) does not contain a valid URL or path to a local file.
webexteamssdk/api/messages.py
def create(self, roomId=None, toPersonId=None, toPersonEmail=None, text=None, markdown=None, files=None, **request_parameters): """Post a message, and optionally a attachment, to a room. The files parameter is a list, which accepts multiple values to allow for future expansion, but currently only one file may be included with the message. Args: roomId(basestring): The room ID. toPersonId(basestring): The ID of the recipient when sending a private 1:1 message. toPersonEmail(basestring): The email address of the recipient when sending a private 1:1 message. text(basestring): The message, in plain text. If `markdown` is specified this parameter may be optionally used to provide alternate text for UI clients that do not support rich text. markdown(basestring): The message, in markdown format. files(`list`): A list of public URL(s) or local path(s) to files to be posted into the room. Only one file is allowed per message. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Message: A Message object with the details of the created message. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. ValueError: If the files parameter is a list of length > 1, or if the string in the list (the only element in the list) does not contain a valid URL or path to a local file. """ check_type(roomId, basestring) check_type(toPersonId, basestring) check_type(toPersonEmail, basestring) check_type(text, basestring) check_type(markdown, basestring) check_type(files, list) if files: if len(files) != 1: raise ValueError("The length of the `files` list is greater " "than one (1). The files parameter is a " "list, which accepts multiple values to " "allow for future expansion, but currently " "only one file may be included with the " "message.") check_type(files[0], basestring) post_data = dict_from_items_with_values( request_parameters, roomId=roomId, toPersonId=toPersonId, toPersonEmail=toPersonEmail, text=text, markdown=markdown, files=files, ) # API request if not files or is_web_url(files[0]): # Standard JSON post json_data = self._session.post(API_ENDPOINT, json=post_data) elif is_local_file(files[0]): # Multipart MIME post try: post_data['files'] = open_local_file(files[0]) multipart_data = MultipartEncoder(post_data) headers = {'Content-type': multipart_data.content_type} json_data = self._session.post(API_ENDPOINT, headers=headers, data=multipart_data) finally: post_data['files'].file_object.close() else: raise ValueError("The `files` parameter does not contain a vaild " "URL or path to a local file.") # Return a message object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def create(self, roomId=None, toPersonId=None, toPersonEmail=None, text=None, markdown=None, files=None, **request_parameters): """Post a message, and optionally a attachment, to a room. The files parameter is a list, which accepts multiple values to allow for future expansion, but currently only one file may be included with the message. Args: roomId(basestring): The room ID. toPersonId(basestring): The ID of the recipient when sending a private 1:1 message. toPersonEmail(basestring): The email address of the recipient when sending a private 1:1 message. text(basestring): The message, in plain text. If `markdown` is specified this parameter may be optionally used to provide alternate text for UI clients that do not support rich text. markdown(basestring): The message, in markdown format. files(`list`): A list of public URL(s) or local path(s) to files to be posted into the room. Only one file is allowed per message. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Message: A Message object with the details of the created message. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. ValueError: If the files parameter is a list of length > 1, or if the string in the list (the only element in the list) does not contain a valid URL or path to a local file. """ check_type(roomId, basestring) check_type(toPersonId, basestring) check_type(toPersonEmail, basestring) check_type(text, basestring) check_type(markdown, basestring) check_type(files, list) if files: if len(files) != 1: raise ValueError("The length of the `files` list is greater " "than one (1). The files parameter is a " "list, which accepts multiple values to " "allow for future expansion, but currently " "only one file may be included with the " "message.") check_type(files[0], basestring) post_data = dict_from_items_with_values( request_parameters, roomId=roomId, toPersonId=toPersonId, toPersonEmail=toPersonEmail, text=text, markdown=markdown, files=files, ) # API request if not files or is_web_url(files[0]): # Standard JSON post json_data = self._session.post(API_ENDPOINT, json=post_data) elif is_local_file(files[0]): # Multipart MIME post try: post_data['files'] = open_local_file(files[0]) multipart_data = MultipartEncoder(post_data) headers = {'Content-type': multipart_data.content_type} json_data = self._session.post(API_ENDPOINT, headers=headers, data=multipart_data) finally: post_data['files'].file_object.close() else: raise ValueError("The `files` parameter does not contain a vaild " "URL or path to a local file.") # Return a message object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Post", "a", "message", "and", "optionally", "a", "attachment", "to", "a", "room", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/messages.py#L137-L219
[ "def", "create", "(", "self", ",", "roomId", "=", "None", ",", "toPersonId", "=", "None", ",", "toPersonEmail", "=", "None", ",", "text", "=", "None", ",", "markdown", "=", "None", ",", "files", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "roomId", ",", "basestring", ")", "check_type", "(", "toPersonId", ",", "basestring", ")", "check_type", "(", "toPersonEmail", ",", "basestring", ")", "check_type", "(", "text", ",", "basestring", ")", "check_type", "(", "markdown", ",", "basestring", ")", "check_type", "(", "files", ",", "list", ")", "if", "files", ":", "if", "len", "(", "files", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"The length of the `files` list is greater \"", "\"than one (1). The files parameter is a \"", "\"list, which accepts multiple values to \"", "\"allow for future expansion, but currently \"", "\"only one file may be included with the \"", "\"message.\"", ")", "check_type", "(", "files", "[", "0", "]", ",", "basestring", ")", "post_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "roomId", "=", "roomId", ",", "toPersonId", "=", "toPersonId", ",", "toPersonEmail", "=", "toPersonEmail", ",", "text", "=", "text", ",", "markdown", "=", "markdown", ",", "files", "=", "files", ",", ")", "# API request", "if", "not", "files", "or", "is_web_url", "(", "files", "[", "0", "]", ")", ":", "# Standard JSON post", "json_data", "=", "self", ".", "_session", ".", "post", "(", "API_ENDPOINT", ",", "json", "=", "post_data", ")", "elif", "is_local_file", "(", "files", "[", "0", "]", ")", ":", "# Multipart MIME post", "try", ":", "post_data", "[", "'files'", "]", "=", "open_local_file", "(", "files", "[", "0", "]", ")", "multipart_data", "=", "MultipartEncoder", "(", "post_data", ")", "headers", "=", "{", "'Content-type'", ":", "multipart_data", ".", "content_type", "}", "json_data", "=", "self", ".", "_session", ".", "post", "(", "API_ENDPOINT", ",", "headers", "=", "headers", ",", "data", "=", "multipart_data", ")", "finally", ":", "post_data", "[", "'files'", "]", ".", "file_object", ".", "close", "(", ")", "else", ":", "raise", "ValueError", "(", "\"The `files` parameter does not contain a vaild \"", "\"URL or path to a local file.\"", ")", "# Return a message object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
MessagesAPI.delete
Delete a message. Args: messageId(basestring): The ID of the message to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/messages.py
def delete(self, messageId): """Delete a message. Args: messageId(basestring): The ID of the message to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(messageId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + messageId)
def delete(self, messageId): """Delete a message. Args: messageId(basestring): The ID of the message to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(messageId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + messageId)
[ "Delete", "a", "message", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/messages.py#L244-L258
[ "def", "delete", "(", "self", ",", "messageId", ")", ":", "check_type", "(", "messageId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "# API request", "self", ".", "_session", ".", "delete", "(", "API_ENDPOINT", "+", "'/'", "+", "messageId", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
PeopleAPI.list
List people This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all people returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: email(basestring): The e-mail address of the person to be found. displayName(basestring): The complete or beginning portion of the displayName to be searched. id(basestring): List people by ID. Accepts up to 85 person IDs separated by commas. orgId(basestring): The organization ID. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the people returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/people.py
def list(self, email=None, displayName=None, id=None, orgId=None, max=None, **request_parameters): """List people This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all people returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: email(basestring): The e-mail address of the person to be found. displayName(basestring): The complete or beginning portion of the displayName to be searched. id(basestring): List people by ID. Accepts up to 85 person IDs separated by commas. orgId(basestring): The organization ID. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the people returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(id, basestring) check_type(email, basestring) check_type(displayName, basestring) check_type(orgId, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, id=id, email=email, displayName=displayName, orgId=orgId, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield person objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
def list(self, email=None, displayName=None, id=None, orgId=None, max=None, **request_parameters): """List people This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all people returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: email(basestring): The e-mail address of the person to be found. displayName(basestring): The complete or beginning portion of the displayName to be searched. id(basestring): List people by ID. Accepts up to 85 person IDs separated by commas. orgId(basestring): The organization ID. max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the people returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(id, basestring) check_type(email, basestring) check_type(displayName, basestring) check_type(orgId, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, id=id, email=email, displayName=displayName, orgId=orgId, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield person objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
[ "List", "people" ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/people.py#L76-L131
[ "def", "list", "(", "self", ",", "email", "=", "None", ",", "displayName", "=", "None", ",", "id", "=", "None", ",", "orgId", "=", "None", ",", "max", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "id", ",", "basestring", ")", "check_type", "(", "email", ",", "basestring", ")", "check_type", "(", "displayName", ",", "basestring", ")", "check_type", "(", "orgId", ",", "basestring", ")", "check_type", "(", "max", ",", "int", ")", "params", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "id", "=", "id", ",", "email", "=", "email", ",", "displayName", "=", "displayName", ",", "orgId", "=", "orgId", ",", "max", "=", "max", ",", ")", "# API request - get items", "items", "=", "self", ".", "_session", ".", "get_items", "(", "API_ENDPOINT", ",", "params", "=", "params", ")", "# Yield person objects created from the returned items JSON objects", "for", "item", "in", "items", ":", "yield", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "item", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
PeopleAPI.create
Create a new user account for a given organization Only an admin can create a new user account. Args: emails(`list`): Email address(es) of the person (list of strings). displayName(basestring): Full name of the person. firstName(basestring): First name of the person. lastName(basestring): Last name of the person. avatar(basestring): URL to the person's avatar in PNG format. orgId(basestring): ID of the organization to which this person belongs. roles(`list`): Roles of the person (list of strings containing the role IDs to be assigned to the person). licenses(`list`): Licenses allocated to the person (list of strings - containing the license IDs to be allocated to the person). **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Person: A Person object with the details of the created person. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/people.py
def create(self, emails, displayName=None, firstName=None, lastName=None, avatar=None, orgId=None, roles=None, licenses=None, **request_parameters): """Create a new user account for a given organization Only an admin can create a new user account. Args: emails(`list`): Email address(es) of the person (list of strings). displayName(basestring): Full name of the person. firstName(basestring): First name of the person. lastName(basestring): Last name of the person. avatar(basestring): URL to the person's avatar in PNG format. orgId(basestring): ID of the organization to which this person belongs. roles(`list`): Roles of the person (list of strings containing the role IDs to be assigned to the person). licenses(`list`): Licenses allocated to the person (list of strings - containing the license IDs to be allocated to the person). **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Person: A Person object with the details of the created person. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(emails, list, may_be_none=False) check_type(displayName, basestring) check_type(firstName, basestring) check_type(lastName, basestring) check_type(avatar, basestring) check_type(orgId, basestring) check_type(roles, list) check_type(licenses, list) post_data = dict_from_items_with_values( request_parameters, emails=emails, displayName=displayName, firstName=firstName, lastName=lastName, avatar=avatar, orgId=orgId, roles=roles, licenses=licenses, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a person object created from the returned JSON object return self._object_factory(OBJECT_TYPE, json_data)
def create(self, emails, displayName=None, firstName=None, lastName=None, avatar=None, orgId=None, roles=None, licenses=None, **request_parameters): """Create a new user account for a given organization Only an admin can create a new user account. Args: emails(`list`): Email address(es) of the person (list of strings). displayName(basestring): Full name of the person. firstName(basestring): First name of the person. lastName(basestring): Last name of the person. avatar(basestring): URL to the person's avatar in PNG format. orgId(basestring): ID of the organization to which this person belongs. roles(`list`): Roles of the person (list of strings containing the role IDs to be assigned to the person). licenses(`list`): Licenses allocated to the person (list of strings - containing the license IDs to be allocated to the person). **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Person: A Person object with the details of the created person. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(emails, list, may_be_none=False) check_type(displayName, basestring) check_type(firstName, basestring) check_type(lastName, basestring) check_type(avatar, basestring) check_type(orgId, basestring) check_type(roles, list) check_type(licenses, list) post_data = dict_from_items_with_values( request_parameters, emails=emails, displayName=displayName, firstName=firstName, lastName=lastName, avatar=avatar, orgId=orgId, roles=roles, licenses=licenses, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a person object created from the returned JSON object return self._object_factory(OBJECT_TYPE, json_data)
[ "Create", "a", "new", "user", "account", "for", "a", "given", "organization" ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/people.py#L133-L189
[ "def", "create", "(", "self", ",", "emails", ",", "displayName", "=", "None", ",", "firstName", "=", "None", ",", "lastName", "=", "None", ",", "avatar", "=", "None", ",", "orgId", "=", "None", ",", "roles", "=", "None", ",", "licenses", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "emails", ",", "list", ",", "may_be_none", "=", "False", ")", "check_type", "(", "displayName", ",", "basestring", ")", "check_type", "(", "firstName", ",", "basestring", ")", "check_type", "(", "lastName", ",", "basestring", ")", "check_type", "(", "avatar", ",", "basestring", ")", "check_type", "(", "orgId", ",", "basestring", ")", "check_type", "(", "roles", ",", "list", ")", "check_type", "(", "licenses", ",", "list", ")", "post_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "emails", "=", "emails", ",", "displayName", "=", "displayName", ",", "firstName", "=", "firstName", ",", "lastName", "=", "lastName", ",", "avatar", "=", "avatar", ",", "orgId", "=", "orgId", ",", "roles", "=", "roles", ",", "licenses", "=", "licenses", ",", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "post", "(", "API_ENDPOINT", ",", "json", "=", "post_data", ")", "# Return a person object created from the returned JSON object", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
PeopleAPI.get
Get a person's details, by ID. Args: personId(basestring): The ID of the person to be retrieved. Returns: Person: A Person object with the details of the requested person. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/people.py
def get(self, personId): """Get a person's details, by ID. Args: personId(basestring): The ID of the person to be retrieved. Returns: Person: A Person object with the details of the requested person. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(personId, basestring, may_be_none=False) # API request json_data = self._session.get(API_ENDPOINT + '/' + personId) # Return a person object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def get(self, personId): """Get a person's details, by ID. Args: personId(basestring): The ID of the person to be retrieved. Returns: Person: A Person object with the details of the requested person. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(personId, basestring, may_be_none=False) # API request json_data = self._session.get(API_ENDPOINT + '/' + personId) # Return a person object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Get", "a", "person", "s", "details", "by", "ID", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/people.py#L191-L211
[ "def", "get", "(", "self", ",", "personId", ")", ":", "check_type", "(", "personId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "get", "(", "API_ENDPOINT", "+", "'/'", "+", "personId", ")", "# Return a person object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
PeopleAPI.update
Update details for a person, by ID. Only an admin can update a person's details. Email addresses for a person cannot be changed via the Webex Teams API. Include all details for the person. This action expects all user details to be present in the request. A common approach is to first GET the person's details, make changes, then PUT both the changed and unchanged values. Args: personId(basestring): The person ID. emails(`list`): Email address(es) of the person (list of strings). displayName(basestring): Full name of the person. firstName(basestring): First name of the person. lastName(basestring): Last name of the person. avatar(basestring): URL to the person's avatar in PNG format. orgId(basestring): ID of the organization to which this person belongs. roles(`list`): Roles of the person (list of strings containing the role IDs to be assigned to the person). licenses(`list`): Licenses allocated to the person (list of strings - containing the license IDs to be allocated to the person). **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Person: A Person object with the updated details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/people.py
def update(self, personId, emails=None, displayName=None, firstName=None, lastName=None, avatar=None, orgId=None, roles=None, licenses=None, **request_parameters): """Update details for a person, by ID. Only an admin can update a person's details. Email addresses for a person cannot be changed via the Webex Teams API. Include all details for the person. This action expects all user details to be present in the request. A common approach is to first GET the person's details, make changes, then PUT both the changed and unchanged values. Args: personId(basestring): The person ID. emails(`list`): Email address(es) of the person (list of strings). displayName(basestring): Full name of the person. firstName(basestring): First name of the person. lastName(basestring): Last name of the person. avatar(basestring): URL to the person's avatar in PNG format. orgId(basestring): ID of the organization to which this person belongs. roles(`list`): Roles of the person (list of strings containing the role IDs to be assigned to the person). licenses(`list`): Licenses allocated to the person (list of strings - containing the license IDs to be allocated to the person). **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Person: A Person object with the updated details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(emails, list) check_type(displayName, basestring) check_type(firstName, basestring) check_type(lastName, basestring) check_type(avatar, basestring) check_type(orgId, basestring) check_type(roles, list) check_type(licenses, list) put_data = dict_from_items_with_values( request_parameters, emails=emails, displayName=displayName, firstName=firstName, lastName=lastName, avatar=avatar, orgId=orgId, roles=roles, licenses=licenses, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + personId, json=put_data) # Return a person object created from the returned JSON object return self._object_factory(OBJECT_TYPE, json_data)
def update(self, personId, emails=None, displayName=None, firstName=None, lastName=None, avatar=None, orgId=None, roles=None, licenses=None, **request_parameters): """Update details for a person, by ID. Only an admin can update a person's details. Email addresses for a person cannot be changed via the Webex Teams API. Include all details for the person. This action expects all user details to be present in the request. A common approach is to first GET the person's details, make changes, then PUT both the changed and unchanged values. Args: personId(basestring): The person ID. emails(`list`): Email address(es) of the person (list of strings). displayName(basestring): Full name of the person. firstName(basestring): First name of the person. lastName(basestring): Last name of the person. avatar(basestring): URL to the person's avatar in PNG format. orgId(basestring): ID of the organization to which this person belongs. roles(`list`): Roles of the person (list of strings containing the role IDs to be assigned to the person). licenses(`list`): Licenses allocated to the person (list of strings - containing the license IDs to be allocated to the person). **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Person: A Person object with the updated details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(emails, list) check_type(displayName, basestring) check_type(firstName, basestring) check_type(lastName, basestring) check_type(avatar, basestring) check_type(orgId, basestring) check_type(roles, list) check_type(licenses, list) put_data = dict_from_items_with_values( request_parameters, emails=emails, displayName=displayName, firstName=firstName, lastName=lastName, avatar=avatar, orgId=orgId, roles=roles, licenses=licenses, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + personId, json=put_data) # Return a person object created from the returned JSON object return self._object_factory(OBJECT_TYPE, json_data)
[ "Update", "details", "for", "a", "person", "by", "ID", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/people.py#L213-L278
[ "def", "update", "(", "self", ",", "personId", ",", "emails", "=", "None", ",", "displayName", "=", "None", ",", "firstName", "=", "None", ",", "lastName", "=", "None", ",", "avatar", "=", "None", ",", "orgId", "=", "None", ",", "roles", "=", "None", ",", "licenses", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "emails", ",", "list", ")", "check_type", "(", "displayName", ",", "basestring", ")", "check_type", "(", "firstName", ",", "basestring", ")", "check_type", "(", "lastName", ",", "basestring", ")", "check_type", "(", "avatar", ",", "basestring", ")", "check_type", "(", "orgId", ",", "basestring", ")", "check_type", "(", "roles", ",", "list", ")", "check_type", "(", "licenses", ",", "list", ")", "put_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "emails", "=", "emails", ",", "displayName", "=", "displayName", ",", "firstName", "=", "firstName", ",", "lastName", "=", "lastName", ",", "avatar", "=", "avatar", ",", "orgId", "=", "orgId", ",", "roles", "=", "roles", ",", "licenses", "=", "licenses", ",", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "put", "(", "API_ENDPOINT", "+", "'/'", "+", "personId", ",", "json", "=", "put_data", ")", "# Return a person object created from the returned JSON object", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
PeopleAPI.delete
Remove a person from the system. Only an admin can remove a person. Args: personId(basestring): The ID of the person to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/people.py
def delete(self, personId): """Remove a person from the system. Only an admin can remove a person. Args: personId(basestring): The ID of the person to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(personId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + personId)
def delete(self, personId): """Remove a person from the system. Only an admin can remove a person. Args: personId(basestring): The ID of the person to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(personId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + personId)
[ "Remove", "a", "person", "from", "the", "system", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/people.py#L280-L296
[ "def", "delete", "(", "self", ",", "personId", ")", ":", "check_type", "(", "personId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "# API request", "self", ".", "_session", ".", "delete", "(", "API_ENDPOINT", "+", "'/'", "+", "personId", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
PeopleAPI.me
Get the details of the person accessing the API. Raises: ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/people.py
def me(self): """Get the details of the person accessing the API. Raises: ApiError: If the Webex Teams cloud returns an error. """ # API request json_data = self._session.get(API_ENDPOINT + '/me') # Return a person object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def me(self): """Get the details of the person accessing the API. Raises: ApiError: If the Webex Teams cloud returns an error. """ # API request json_data = self._session.get(API_ENDPOINT + '/me') # Return a person object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Get", "the", "details", "of", "the", "person", "accessing", "the", "API", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/people.py#L298-L309
[ "def", "me", "(", "self", ")", ":", "# API request", "json_data", "=", "self", ".", "_session", ".", "get", "(", "API_ENDPOINT", "+", "'/me'", ")", "# Return a person object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
RolesAPI.list
List all roles. Args: **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the roles returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/roles.py
def list(self, **request_parameters): """List all roles. Args: **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the roles returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ # API request - get items items = self._session.get_items( API_ENDPOINT, params=request_parameters ) # Yield role objects created from the returned JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
def list(self, **request_parameters): """List all roles. Args: **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the roles returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ # API request - get items items = self._session.get_items( API_ENDPOINT, params=request_parameters ) # Yield role objects created from the returned JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
[ "List", "all", "roles", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/roles.py#L76-L100
[ "def", "list", "(", "self", ",", "*", "*", "request_parameters", ")", ":", "# API request - get items", "items", "=", "self", ".", "_session", ".", "get_items", "(", "API_ENDPOINT", ",", "params", "=", "request_parameters", ")", "# Yield role objects created from the returned JSON objects", "for", "item", "in", "items", ":", "yield", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "item", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
TeamsAPI.list
List teams to which the authenticated user belongs. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all teams returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the teams returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/teams.py
def list(self, max=None, **request_parameters): """List teams to which the authenticated user belongs. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all teams returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the teams returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(max, int) params = dict_from_items_with_values( request_parameters, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield team objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
def list(self, max=None, **request_parameters): """List teams to which the authenticated user belongs. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all teams returned by the query. The generator will automatically request additional 'pages' of responses from Webex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the teams returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(max, int) params = dict_from_items_with_values( request_parameters, max=max, ) # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield team objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
[ "List", "teams", "to", "which", "the", "authenticated", "user", "belongs", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/teams.py#L76-L116
[ "def", "list", "(", "self", ",", "max", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "max", ",", "int", ")", "params", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "max", "=", "max", ",", ")", "# API request - get items", "items", "=", "self", ".", "_session", ".", "get_items", "(", "API_ENDPOINT", ",", "params", "=", "params", ")", "# Yield team objects created from the returned items JSON objects", "for", "item", "in", "items", ":", "yield", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "item", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
TeamsAPI.create
Create a team. The authenticated user is automatically added as a member of the team. Args: name(basestring): A user-friendly name for the team. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Team: A Team object with the details of the created team. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/teams.py
def create(self, name, **request_parameters): """Create a team. The authenticated user is automatically added as a member of the team. Args: name(basestring): A user-friendly name for the team. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Team: A Team object with the details of the created team. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(name, basestring, may_be_none=False) post_data = dict_from_items_with_values( request_parameters, name=name, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a team object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def create(self, name, **request_parameters): """Create a team. The authenticated user is automatically added as a member of the team. Args: name(basestring): A user-friendly name for the team. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Team: A Team object with the details of the created team. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(name, basestring, may_be_none=False) post_data = dict_from_items_with_values( request_parameters, name=name, ) # API request json_data = self._session.post(API_ENDPOINT, json=post_data) # Return a team object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Create", "a", "team", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/teams.py#L118-L147
[ "def", "create", "(", "self", ",", "name", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "name", ",", "basestring", ",", "may_be_none", "=", "False", ")", "post_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "name", "=", "name", ",", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "post", "(", "API_ENDPOINT", ",", "json", "=", "post_data", ")", "# Return a team object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
TeamsAPI.update
Update details for a team, by ID. Args: teamId(basestring): The team ID. name(basestring): A user-friendly name for the team. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Team: A Team object with the updated Webex Teams team details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/teams.py
def update(self, teamId, name=None, **request_parameters): """Update details for a team, by ID. Args: teamId(basestring): The team ID. name(basestring): A user-friendly name for the team. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Team: A Team object with the updated Webex Teams team details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring, may_be_none=False) check_type(name, basestring) put_data = dict_from_items_with_values( request_parameters, name=name, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + teamId, json=put_data) # Return a team object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def update(self, teamId, name=None, **request_parameters): """Update details for a team, by ID. Args: teamId(basestring): The team ID. name(basestring): A user-friendly name for the team. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: Team: A Team object with the updated Webex Teams team details. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring, may_be_none=False) check_type(name, basestring) put_data = dict_from_items_with_values( request_parameters, name=name, ) # API request json_data = self._session.put(API_ENDPOINT + '/' + teamId, json=put_data) # Return a team object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Update", "details", "for", "a", "team", "by", "ID", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/teams.py#L171-L201
[ "def", "update", "(", "self", ",", "teamId", ",", "name", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "teamId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "name", ",", "basestring", ")", "put_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "name", "=", "name", ",", ")", "# API request", "json_data", "=", "self", ".", "_session", ".", "put", "(", "API_ENDPOINT", "+", "'/'", "+", "teamId", ",", "json", "=", "put_data", ")", "# Return a team object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
TeamsAPI.delete
Delete a team. Args: teamId(basestring): The ID of the team to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/teams.py
def delete(self, teamId): """Delete a team. Args: teamId(basestring): The ID of the team to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + teamId)
def delete(self, teamId): """Delete a team. Args: teamId(basestring): The ID of the team to be deleted. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(teamId, basestring, may_be_none=False) # API request self._session.delete(API_ENDPOINT + '/' + teamId)
[ "Delete", "a", "team", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/teams.py#L203-L217
[ "def", "delete", "(", "self", ",", "teamId", ")", ":", "check_type", "(", "teamId", ",", "basestring", ",", "may_be_none", "=", "False", ")", "# API request", "self", ".", "_session", ".", "delete", "(", "API_ENDPOINT", "+", "'/'", "+", "teamId", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
EventsAPI.list
List events. List events in your organization. Several query parameters are available to filter the response. Note: `from` is a keyword in Python and may not be used as a variable name, so we had to use `_from` instead. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all events returned by the query. The generator will automatically request additional 'pages' of responses from Wevex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: resource(basestring): Limit results to a specific resource type. Possible values: "messages", "memberships". type(basestring): Limit results to a specific event type. Possible values: "created", "updated", "deleted". actorId(basestring): Limit results to events performed by this person, by ID. _from(basestring): Limit results to events which occurred after a date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ). to(basestring): Limit results to events which occurred before a date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ). max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the events returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/events.py
def list(self, resource=None, type=None, actorId=None, _from=None, to=None, max=None, **request_parameters): """List events. List events in your organization. Several query parameters are available to filter the response. Note: `from` is a keyword in Python and may not be used as a variable name, so we had to use `_from` instead. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all events returned by the query. The generator will automatically request additional 'pages' of responses from Wevex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: resource(basestring): Limit results to a specific resource type. Possible values: "messages", "memberships". type(basestring): Limit results to a specific event type. Possible values: "created", "updated", "deleted". actorId(basestring): Limit results to events performed by this person, by ID. _from(basestring): Limit results to events which occurred after a date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ). to(basestring): Limit results to events which occurred before a date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ). max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the events returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(resource, basestring) check_type(type, basestring) check_type(actorId, basestring) check_type(_from, basestring) check_type(to, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, resource=resource, type=type, actorId=actorId, _from=_from, to=to, max=max, ) if _from: params["from"] = params.pop("_from") # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield event objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
def list(self, resource=None, type=None, actorId=None, _from=None, to=None, max=None, **request_parameters): """List events. List events in your organization. Several query parameters are available to filter the response. Note: `from` is a keyword in Python and may not be used as a variable name, so we had to use `_from` instead. This method supports Webex Teams's implementation of RFC5988 Web Linking to provide pagination support. It returns a generator container that incrementally yields all events returned by the query. The generator will automatically request additional 'pages' of responses from Wevex as needed until all responses have been returned. The container makes the generator safe for reuse. A new API call will be made, using the same parameters that were specified when the generator was created, every time a new iterator is requested from the container. Args: resource(basestring): Limit results to a specific resource type. Possible values: "messages", "memberships". type(basestring): Limit results to a specific event type. Possible values: "created", "updated", "deleted". actorId(basestring): Limit results to events performed by this person, by ID. _from(basestring): Limit results to events which occurred after a date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ). to(basestring): Limit results to events which occurred before a date and time, in ISO8601 format (yyyy-MM-dd'T'HH:mm:ss.SSSZ). max(int): Limit the maximum number of items returned from the Webex Teams service per request. **request_parameters: Additional request parameters (provides support for parameters that may be added in the future). Returns: GeneratorContainer: A GeneratorContainer which, when iterated, yields the events returned by the Webex Teams query. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(resource, basestring) check_type(type, basestring) check_type(actorId, basestring) check_type(_from, basestring) check_type(to, basestring) check_type(max, int) params = dict_from_items_with_values( request_parameters, resource=resource, type=type, actorId=actorId, _from=_from, to=to, max=max, ) if _from: params["from"] = params.pop("_from") # API request - get items items = self._session.get_items(API_ENDPOINT, params=params) # Yield event objects created from the returned items JSON objects for item in items: yield self._object_factory(OBJECT_TYPE, item)
[ "List", "events", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/events.py#L76-L146
[ "def", "list", "(", "self", ",", "resource", "=", "None", ",", "type", "=", "None", ",", "actorId", "=", "None", ",", "_from", "=", "None", ",", "to", "=", "None", ",", "max", "=", "None", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "resource", ",", "basestring", ")", "check_type", "(", "type", ",", "basestring", ")", "check_type", "(", "actorId", ",", "basestring", ")", "check_type", "(", "_from", ",", "basestring", ")", "check_type", "(", "to", ",", "basestring", ")", "check_type", "(", "max", ",", "int", ")", "params", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "resource", "=", "resource", ",", "type", "=", "type", ",", "actorId", "=", "actorId", ",", "_from", "=", "_from", ",", "to", "=", "to", ",", "max", "=", "max", ",", ")", "if", "_from", ":", "params", "[", "\"from\"", "]", "=", "params", ".", "pop", "(", "\"_from\"", ")", "# API request - get items", "items", "=", "self", ".", "_session", ".", "get_items", "(", "API_ENDPOINT", ",", "params", "=", "params", ")", "# Yield event objects created from the returned items JSON objects", "for", "item", "in", "items", ":", "yield", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "item", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
ImmutableData._serialize
Serialize data to an frozen tuple.
webexteamssdk/models/immutable.py
def _serialize(cls, data): """Serialize data to an frozen tuple.""" if hasattr(data, "__hash__") and callable(data.__hash__): # If the data is already hashable (should be immutable) return it return data elif isinstance(data, list): # Freeze the elements of the list and return as a tuple return tuple((cls._serialize(item) for item in data)) elif isinstance(data, dict): # Freeze the elements of the dictionary, sort them, and return # them as a list of tuples key_value_tuples = [ (key, cls._serialize(value)) for key, value in data.items() ] key_value_tuples.sort() return tuple(key_value_tuples) else: raise TypeError( "Unable to freeze {} data type.".format(type(data)) )
def _serialize(cls, data): """Serialize data to an frozen tuple.""" if hasattr(data, "__hash__") and callable(data.__hash__): # If the data is already hashable (should be immutable) return it return data elif isinstance(data, list): # Freeze the elements of the list and return as a tuple return tuple((cls._serialize(item) for item in data)) elif isinstance(data, dict): # Freeze the elements of the dictionary, sort them, and return # them as a list of tuples key_value_tuples = [ (key, cls._serialize(value)) for key, value in data.items() ] key_value_tuples.sort() return tuple(key_value_tuples) else: raise TypeError( "Unable to freeze {} data type.".format(type(data)) )
[ "Serialize", "data", "to", "an", "frozen", "tuple", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/models/immutable.py#L121-L141
[ "def", "_serialize", "(", "cls", ",", "data", ")", ":", "if", "hasattr", "(", "data", ",", "\"__hash__\"", ")", "and", "callable", "(", "data", ".", "__hash__", ")", ":", "# If the data is already hashable (should be immutable) return it", "return", "data", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "# Freeze the elements of the list and return as a tuple", "return", "tuple", "(", "(", "cls", ".", "_serialize", "(", "item", ")", "for", "item", "in", "data", ")", ")", "elif", "isinstance", "(", "data", ",", "dict", ")", ":", "# Freeze the elements of the dictionary, sort them, and return", "# them as a list of tuples", "key_value_tuples", "=", "[", "(", "key", ",", "cls", ".", "_serialize", "(", "value", ")", ")", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", "]", "key_value_tuples", ".", "sort", "(", ")", "return", "tuple", "(", "key_value_tuples", ")", "else", ":", "raise", "TypeError", "(", "\"Unable to freeze {} data type.\"", ".", "format", "(", "type", "(", "data", ")", ")", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
AccessTokensAPI.get
Exchange an Authorization Code for an Access Token. Exchange an Authorization Code for an Access Token that can be used to invoke the APIs. Args: client_id(basestring): Provided when you created your integration. client_secret(basestring): Provided when you created your integration. code(basestring): The Authorization Code provided by the user OAuth process. redirect_uri(basestring): The redirect URI used in the user OAuth process. Returns: AccessToken: An AccessToken object with the access token provided by the Webex Teams cloud. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
webexteamssdk/api/access_tokens.py
def get(self, client_id, client_secret, code, redirect_uri): """Exchange an Authorization Code for an Access Token. Exchange an Authorization Code for an Access Token that can be used to invoke the APIs. Args: client_id(basestring): Provided when you created your integration. client_secret(basestring): Provided when you created your integration. code(basestring): The Authorization Code provided by the user OAuth process. redirect_uri(basestring): The redirect URI used in the user OAuth process. Returns: AccessToken: An AccessToken object with the access token provided by the Webex Teams cloud. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(client_id, basestring, may_be_none=False) check_type(client_secret, basestring, may_be_none=False) check_type(code, basestring, may_be_none=False) check_type(redirect_uri, basestring, may_be_none=False) post_data = dict_from_items_with_values( grant_type="authorization_code", client_id=client_id, client_secret=client_secret, code=code, redirect_uri=redirect_uri, ) # API request response = requests.post(self._endpoint_url, data=post_data, **self._request_kwargs) check_response_code(response, EXPECTED_RESPONSE_CODE['POST']) json_data = extract_and_parse_json(response) # Return a access_token object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
def get(self, client_id, client_secret, code, redirect_uri): """Exchange an Authorization Code for an Access Token. Exchange an Authorization Code for an Access Token that can be used to invoke the APIs. Args: client_id(basestring): Provided when you created your integration. client_secret(basestring): Provided when you created your integration. code(basestring): The Authorization Code provided by the user OAuth process. redirect_uri(basestring): The redirect URI used in the user OAuth process. Returns: AccessToken: An AccessToken object with the access token provided by the Webex Teams cloud. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error. """ check_type(client_id, basestring, may_be_none=False) check_type(client_secret, basestring, may_be_none=False) check_type(code, basestring, may_be_none=False) check_type(redirect_uri, basestring, may_be_none=False) post_data = dict_from_items_with_values( grant_type="authorization_code", client_id=client_id, client_secret=client_secret, code=code, redirect_uri=redirect_uri, ) # API request response = requests.post(self._endpoint_url, data=post_data, **self._request_kwargs) check_response_code(response, EXPECTED_RESPONSE_CODE['POST']) json_data = extract_and_parse_json(response) # Return a access_token object created from the response JSON data return self._object_factory(OBJECT_TYPE, json_data)
[ "Exchange", "an", "Authorization", "Code", "for", "an", "Access", "Token", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/api/access_tokens.py#L104-L148
[ "def", "get", "(", "self", ",", "client_id", ",", "client_secret", ",", "code", ",", "redirect_uri", ")", ":", "check_type", "(", "client_id", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "client_secret", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "code", ",", "basestring", ",", "may_be_none", "=", "False", ")", "check_type", "(", "redirect_uri", ",", "basestring", ",", "may_be_none", "=", "False", ")", "post_data", "=", "dict_from_items_with_values", "(", "grant_type", "=", "\"authorization_code\"", ",", "client_id", "=", "client_id", ",", "client_secret", "=", "client_secret", ",", "code", "=", "code", ",", "redirect_uri", "=", "redirect_uri", ",", ")", "# API request", "response", "=", "requests", ".", "post", "(", "self", ".", "_endpoint_url", ",", "data", "=", "post_data", ",", "*", "*", "self", ".", "_request_kwargs", ")", "check_response_code", "(", "response", ",", "EXPECTED_RESPONSE_CODE", "[", "'POST'", "]", ")", "json_data", "=", "extract_and_parse_json", "(", "response", ")", "# Return a access_token object created from the response JSON data", "return", "self", ".", "_object_factory", "(", "OBJECT_TYPE", ",", "json_data", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
PersonBasicPropertiesMixin.lastActivity
The date and time of the person's last activity.
webexteamssdk/models/mixins/person.py
def lastActivity(self): """The date and time of the person's last activity.""" last_activity = self._json_data.get('lastActivity') if last_activity: return WebexTeamsDateTime.strptime(last_activity) else: return None
def lastActivity(self): """The date and time of the person's last activity.""" last_activity = self._json_data.get('lastActivity') if last_activity: return WebexTeamsDateTime.strptime(last_activity) else: return None
[ "The", "date", "and", "time", "of", "the", "person", "s", "last", "activity", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/webexteamssdk/models/mixins/person.py#L111-L117
[ "def", "lastActivity", "(", "self", ")", ":", "last_activity", "=", "self", ".", "_json_data", ".", "get", "(", "'lastActivity'", ")", "if", "last_activity", ":", "return", "WebexTeamsDateTime", ".", "strptime", "(", "last_activity", ")", "else", ":", "return", "None" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
post_events_service
Respond to inbound webhook JSON HTTP POST from Webex Teams.
examples/pyramidWebexTeamsBot/pyramidWebexTeamsBot/views.py
def post_events_service(request): """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json log.info("\n") log.info("WEBHOOK POST RECEIVED:") log.info(json_data) log.info("\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) log.info("NEW MESSAGE IN ROOM '{}'".format(room.title)) log.info("FROM '{}'".format(person.displayName)) log.info("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return {'Message': 'OK'} else: # Message was sent by someone else; parse message and respond. if "/CAT" in message.text: log.info("FOUND '/CAT'") # Get a cat fact catfact = get_catfact() log.info("SENDING CAT FACT'{}'".format(catfact)) # Post the fact to the room where the request was received api.messages.create(room.id, text=catfact) return {'Message': 'OK'}
def post_events_service(request): """Respond to inbound webhook JSON HTTP POST from Webex Teams.""" # Get the POST data sent from Webex Teams json_data = request.json log.info("\n") log.info("WEBHOOK POST RECEIVED:") log.info(json_data) log.info("\n") # Create a Webhook object from the JSON data webhook_obj = Webhook(json_data) # Get the room details room = api.rooms.get(webhook_obj.data.roomId) # Get the message details message = api.messages.get(webhook_obj.data.id) # Get the sender's details person = api.people.get(message.personId) log.info("NEW MESSAGE IN ROOM '{}'".format(room.title)) log.info("FROM '{}'".format(person.displayName)) log.info("MESSAGE '{}'\n".format(message.text)) # This is a VERY IMPORTANT loop prevention control step. # If you respond to all messages... You will respond to the messages # that the bot posts and thereby create a loop condition. me = api.people.me() if message.personId == me.id: # Message was sent by me (bot); do not respond. return {'Message': 'OK'} else: # Message was sent by someone else; parse message and respond. if "/CAT" in message.text: log.info("FOUND '/CAT'") # Get a cat fact catfact = get_catfact() log.info("SENDING CAT FACT'{}'".format(catfact)) # Post the fact to the room where the request was received api.messages.create(room.id, text=catfact) return {'Message': 'OK'}
[ "Respond", "to", "inbound", "webhook", "JSON", "HTTP", "POST", "from", "Webex", "Teams", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/examples/pyramidWebexTeamsBot/pyramidWebexTeamsBot/views.py#L115-L160
[ "def", "post_events_service", "(", "request", ")", ":", "# Get the POST data sent from Webex Teams", "json_data", "=", "request", ".", "json", "log", ".", "info", "(", "\"\\n\"", ")", "log", ".", "info", "(", "\"WEBHOOK POST RECEIVED:\"", ")", "log", ".", "info", "(", "json_data", ")", "log", ".", "info", "(", "\"\\n\"", ")", "# Create a Webhook object from the JSON data", "webhook_obj", "=", "Webhook", "(", "json_data", ")", "# Get the room details", "room", "=", "api", ".", "rooms", ".", "get", "(", "webhook_obj", ".", "data", ".", "roomId", ")", "# Get the message details", "message", "=", "api", ".", "messages", ".", "get", "(", "webhook_obj", ".", "data", ".", "id", ")", "# Get the sender's details", "person", "=", "api", ".", "people", ".", "get", "(", "message", ".", "personId", ")", "log", ".", "info", "(", "\"NEW MESSAGE IN ROOM '{}'\"", ".", "format", "(", "room", ".", "title", ")", ")", "log", ".", "info", "(", "\"FROM '{}'\"", ".", "format", "(", "person", ".", "displayName", ")", ")", "log", ".", "info", "(", "\"MESSAGE '{}'\\n\"", ".", "format", "(", "message", ".", "text", ")", ")", "# This is a VERY IMPORTANT loop prevention control step.", "# If you respond to all messages... You will respond to the messages", "# that the bot posts and thereby create a loop condition.", "me", "=", "api", ".", "people", ".", "me", "(", ")", "if", "message", ".", "personId", "==", "me", ".", "id", ":", "# Message was sent by me (bot); do not respond.", "return", "{", "'Message'", ":", "'OK'", "}", "else", ":", "# Message was sent by someone else; parse message and respond.", "if", "\"/CAT\"", "in", "message", ".", "text", ":", "log", ".", "info", "(", "\"FOUND '/CAT'\"", ")", "# Get a cat fact", "catfact", "=", "get_catfact", "(", ")", "log", ".", "info", "(", "\"SENDING CAT FACT'{}'\"", ".", "format", "(", "catfact", ")", ")", "# Post the fact to the room where the request was received", "api", ".", "messages", ".", "create", "(", "room", ".", "id", ",", "text", "=", "catfact", ")", "return", "{", "'Message'", ":", "'OK'", "}" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
get_ngrok_public_url
Get the ngrok public HTTP URL from the local client API.
examples/ngrokwebhook.py
def get_ngrok_public_url(): """Get the ngrok public HTTP URL from the local client API.""" try: response = requests.get(url=NGROK_CLIENT_API_BASE_URL + "/tunnels", headers={'content-type': 'application/json'}) response.raise_for_status() except requests.exceptions.RequestException: print("Could not connect to the ngrok client API; " "assuming not running.") return None else: for tunnel in response.json()["tunnels"]: if tunnel.get("public_url", "").startswith("http://"): print("Found ngrok public HTTP URL:", tunnel["public_url"]) return tunnel["public_url"]
def get_ngrok_public_url(): """Get the ngrok public HTTP URL from the local client API.""" try: response = requests.get(url=NGROK_CLIENT_API_BASE_URL + "/tunnels", headers={'content-type': 'application/json'}) response.raise_for_status() except requests.exceptions.RequestException: print("Could not connect to the ngrok client API; " "assuming not running.") return None else: for tunnel in response.json()["tunnels"]: if tunnel.get("public_url", "").startswith("http://"): print("Found ngrok public HTTP URL:", tunnel["public_url"]) return tunnel["public_url"]
[ "Get", "the", "ngrok", "public", "HTTP", "URL", "from", "the", "local", "client", "API", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/examples/ngrokwebhook.py#L76-L92
[ "def", "get_ngrok_public_url", "(", ")", ":", "try", ":", "response", "=", "requests", ".", "get", "(", "url", "=", "NGROK_CLIENT_API_BASE_URL", "+", "\"/tunnels\"", ",", "headers", "=", "{", "'content-type'", ":", "'application/json'", "}", ")", "response", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "print", "(", "\"Could not connect to the ngrok client API; \"", "\"assuming not running.\"", ")", "return", "None", "else", ":", "for", "tunnel", "in", "response", ".", "json", "(", ")", "[", "\"tunnels\"", "]", ":", "if", "tunnel", ".", "get", "(", "\"public_url\"", ",", "\"\"", ")", ".", "startswith", "(", "\"http://\"", ")", ":", "print", "(", "\"Found ngrok public HTTP URL:\"", ",", "tunnel", "[", "\"public_url\"", "]", ")", "return", "tunnel", "[", "\"public_url\"", "]" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
delete_webhooks_with_name
Find a webhook by name.
examples/ngrokwebhook.py
def delete_webhooks_with_name(api, name): """Find a webhook by name.""" for webhook in api.webhooks.list(): if webhook.name == name: print("Deleting Webhook:", webhook.name, webhook.targetUrl) api.webhooks.delete(webhook.id)
def delete_webhooks_with_name(api, name): """Find a webhook by name.""" for webhook in api.webhooks.list(): if webhook.name == name: print("Deleting Webhook:", webhook.name, webhook.targetUrl) api.webhooks.delete(webhook.id)
[ "Find", "a", "webhook", "by", "name", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/examples/ngrokwebhook.py#L95-L100
[ "def", "delete_webhooks_with_name", "(", "api", ",", "name", ")", ":", "for", "webhook", "in", "api", ".", "webhooks", ".", "list", "(", ")", ":", "if", "webhook", ".", "name", "==", "name", ":", "print", "(", "\"Deleting Webhook:\"", ",", "webhook", ".", "name", ",", "webhook", ".", "targetUrl", ")", "api", ".", "webhooks", ".", "delete", "(", "webhook", ".", "id", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
create_ngrok_webhook
Create a Webex Teams webhook pointing to the public ngrok URL.
examples/ngrokwebhook.py
def create_ngrok_webhook(api, ngrok_public_url): """Create a Webex Teams webhook pointing to the public ngrok URL.""" print("Creating Webhook...") webhook = api.webhooks.create( name=WEBHOOK_NAME, targetUrl=urljoin(ngrok_public_url, WEBHOOK_URL_SUFFIX), resource=WEBHOOK_RESOURCE, event=WEBHOOK_EVENT, ) print(webhook) print("Webhook successfully created.") return webhook
def create_ngrok_webhook(api, ngrok_public_url): """Create a Webex Teams webhook pointing to the public ngrok URL.""" print("Creating Webhook...") webhook = api.webhooks.create( name=WEBHOOK_NAME, targetUrl=urljoin(ngrok_public_url, WEBHOOK_URL_SUFFIX), resource=WEBHOOK_RESOURCE, event=WEBHOOK_EVENT, ) print(webhook) print("Webhook successfully created.") return webhook
[ "Create", "a", "Webex", "Teams", "webhook", "pointing", "to", "the", "public", "ngrok", "URL", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/examples/ngrokwebhook.py#L103-L114
[ "def", "create_ngrok_webhook", "(", "api", ",", "ngrok_public_url", ")", ":", "print", "(", "\"Creating Webhook...\"", ")", "webhook", "=", "api", ".", "webhooks", ".", "create", "(", "name", "=", "WEBHOOK_NAME", ",", "targetUrl", "=", "urljoin", "(", "ngrok_public_url", ",", "WEBHOOK_URL_SUFFIX", ")", ",", "resource", "=", "WEBHOOK_RESOURCE", ",", "event", "=", "WEBHOOK_EVENT", ",", ")", "print", "(", "webhook", ")", "print", "(", "\"Webhook successfully created.\"", ")", "return", "webhook" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
main
Delete previous webhooks. If local ngrok tunnel, create a webhook.
examples/ngrokwebhook.py
def main(): """Delete previous webhooks. If local ngrok tunnel, create a webhook.""" api = WebexTeamsAPI() delete_webhooks_with_name(api, name=WEBHOOK_NAME) public_url = get_ngrok_public_url() if public_url is not None: create_ngrok_webhook(api, public_url)
def main(): """Delete previous webhooks. If local ngrok tunnel, create a webhook.""" api = WebexTeamsAPI() delete_webhooks_with_name(api, name=WEBHOOK_NAME) public_url = get_ngrok_public_url() if public_url is not None: create_ngrok_webhook(api, public_url)
[ "Delete", "previous", "webhooks", ".", "If", "local", "ngrok", "tunnel", "create", "a", "webhook", "." ]
CiscoDevNet/webexteamssdk
python
https://github.com/CiscoDevNet/webexteamssdk/blob/6fc2cc3557e080ba4b2a380664cb2a0532ae45cd/examples/ngrokwebhook.py#L117-L123
[ "def", "main", "(", ")", ":", "api", "=", "WebexTeamsAPI", "(", ")", "delete_webhooks_with_name", "(", "api", ",", "name", "=", "WEBHOOK_NAME", ")", "public_url", "=", "get_ngrok_public_url", "(", ")", "if", "public_url", "is", "not", "None", ":", "create_ngrok_webhook", "(", "api", ",", "public_url", ")" ]
6fc2cc3557e080ba4b2a380664cb2a0532ae45cd
test
LSM303.read
Since there isn't a real sensor connected, read() creates random data.
fake_rpi/Adafruit.py
def read(self): """ Since there isn't a real sensor connected, read() creates random data. """ data = [0]*6 for i in range(6): data[i] = random.uniform(-2048, 2048) accel = data[:3] mag = data[3:] return (accel, mag)
def read(self): """ Since there isn't a real sensor connected, read() creates random data. """ data = [0]*6 for i in range(6): data[i] = random.uniform(-2048, 2048) accel = data[:3] mag = data[3:] return (accel, mag)
[ "Since", "there", "isn", "t", "a", "real", "sensor", "connected", "read", "()", "creates", "random", "data", "." ]
MomsFriendlyRobotCompany/fake_rpi
python
https://github.com/MomsFriendlyRobotCompany/fake_rpi/blob/eb2f640f19f74db9082bfbf8aed524e3ccba6d4f/fake_rpi/Adafruit.py#L24-L34
[ "def", "read", "(", "self", ")", ":", "data", "=", "[", "0", "]", "*", "6", "for", "i", "in", "range", "(", "6", ")", ":", "data", "[", "i", "]", "=", "random", ".", "uniform", "(", "-", "2048", ",", "2048", ")", "accel", "=", "data", "[", ":", "3", "]", "mag", "=", "data", "[", "3", ":", "]", "return", "(", "accel", ",", "mag", ")" ]
eb2f640f19f74db9082bfbf8aed524e3ccba6d4f
test
console
Output DSMR data to console.
dsmr_parser/__main__.py
def console(): """Output DSMR data to console.""" parser = argparse.ArgumentParser(description=console.__doc__) parser.add_argument('--device', default='/dev/ttyUSB0', help='port to read DSMR data from') parser.add_argument('--host', default=None, help='alternatively connect using TCP host.') parser.add_argument('--port', default=None, help='TCP port to use for connection') parser.add_argument('--version', default='2.2', choices=['2.2', '4'], help='DSMR version (2.2, 4)') parser.add_argument('--verbose', '-v', action='count') args = parser.parse_args() if args.verbose: level = logging.DEBUG else: level = logging.ERROR logging.basicConfig(level=level) loop = asyncio.get_event_loop() def print_callback(telegram): """Callback that prints telegram values.""" for obiref, obj in telegram.items(): if obj: print(obj.value, obj.unit) print() # create tcp or serial connection depending on args if args.host and args.port: create_connection = partial(create_tcp_dsmr_reader, args.host, args.port, args.version, print_callback, loop=loop) else: create_connection = partial(create_dsmr_reader, args.device, args.version, print_callback, loop=loop) try: # connect and keep connected until interrupted by ctrl-c while True: # create serial or tcp connection conn = create_connection() transport, protocol = loop.run_until_complete(conn) # wait until connection it closed loop.run_until_complete(protocol.wait_closed()) # wait 5 seconds before attempting reconnect loop.run_until_complete(asyncio.sleep(5)) except KeyboardInterrupt: # cleanup connection after user initiated shutdown transport.close() loop.run_until_complete(asyncio.sleep(0)) finally: loop.close()
def console(): """Output DSMR data to console.""" parser = argparse.ArgumentParser(description=console.__doc__) parser.add_argument('--device', default='/dev/ttyUSB0', help='port to read DSMR data from') parser.add_argument('--host', default=None, help='alternatively connect using TCP host.') parser.add_argument('--port', default=None, help='TCP port to use for connection') parser.add_argument('--version', default='2.2', choices=['2.2', '4'], help='DSMR version (2.2, 4)') parser.add_argument('--verbose', '-v', action='count') args = parser.parse_args() if args.verbose: level = logging.DEBUG else: level = logging.ERROR logging.basicConfig(level=level) loop = asyncio.get_event_loop() def print_callback(telegram): """Callback that prints telegram values.""" for obiref, obj in telegram.items(): if obj: print(obj.value, obj.unit) print() # create tcp or serial connection depending on args if args.host and args.port: create_connection = partial(create_tcp_dsmr_reader, args.host, args.port, args.version, print_callback, loop=loop) else: create_connection = partial(create_dsmr_reader, args.device, args.version, print_callback, loop=loop) try: # connect and keep connected until interrupted by ctrl-c while True: # create serial or tcp connection conn = create_connection() transport, protocol = loop.run_until_complete(conn) # wait until connection it closed loop.run_until_complete(protocol.wait_closed()) # wait 5 seconds before attempting reconnect loop.run_until_complete(asyncio.sleep(5)) except KeyboardInterrupt: # cleanup connection after user initiated shutdown transport.close() loop.run_until_complete(asyncio.sleep(0)) finally: loop.close()
[ "Output", "DSMR", "data", "to", "console", "." ]
ndokter/dsmr_parser
python
https://github.com/ndokter/dsmr_parser/blob/c04b0a5add58ce70153eede1a87ca171876b61c7/dsmr_parser/__main__.py#L9-L65
[ "def", "console", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "console", ".", "__doc__", ")", "parser", ".", "add_argument", "(", "'--device'", ",", "default", "=", "'/dev/ttyUSB0'", ",", "help", "=", "'port to read DSMR data from'", ")", "parser", ".", "add_argument", "(", "'--host'", ",", "default", "=", "None", ",", "help", "=", "'alternatively connect using TCP host.'", ")", "parser", ".", "add_argument", "(", "'--port'", ",", "default", "=", "None", ",", "help", "=", "'TCP port to use for connection'", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "default", "=", "'2.2'", ",", "choices", "=", "[", "'2.2'", ",", "'4'", "]", ",", "help", "=", "'DSMR version (2.2, 4)'", ")", "parser", ".", "add_argument", "(", "'--verbose'", ",", "'-v'", ",", "action", "=", "'count'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "verbose", ":", "level", "=", "logging", ".", "DEBUG", "else", ":", "level", "=", "logging", ".", "ERROR", "logging", ".", "basicConfig", "(", "level", "=", "level", ")", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "def", "print_callback", "(", "telegram", ")", ":", "\"\"\"Callback that prints telegram values.\"\"\"", "for", "obiref", ",", "obj", "in", "telegram", ".", "items", "(", ")", ":", "if", "obj", ":", "print", "(", "obj", ".", "value", ",", "obj", ".", "unit", ")", "print", "(", ")", "# create tcp or serial connection depending on args", "if", "args", ".", "host", "and", "args", ".", "port", ":", "create_connection", "=", "partial", "(", "create_tcp_dsmr_reader", ",", "args", ".", "host", ",", "args", ".", "port", ",", "args", ".", "version", ",", "print_callback", ",", "loop", "=", "loop", ")", "else", ":", "create_connection", "=", "partial", "(", "create_dsmr_reader", ",", "args", ".", "device", ",", "args", ".", "version", ",", "print_callback", ",", "loop", "=", "loop", ")", "try", ":", "# connect and keep connected until interrupted by ctrl-c", "while", "True", ":", "# create serial or tcp connection", "conn", "=", "create_connection", "(", ")", "transport", ",", "protocol", "=", "loop", ".", "run_until_complete", "(", "conn", ")", "# wait until connection it closed", "loop", ".", "run_until_complete", "(", "protocol", ".", "wait_closed", "(", ")", ")", "# wait 5 seconds before attempting reconnect", "loop", ".", "run_until_complete", "(", "asyncio", ".", "sleep", "(", "5", ")", ")", "except", "KeyboardInterrupt", ":", "# cleanup connection after user initiated shutdown", "transport", ".", "close", "(", ")", "loop", ".", "run_until_complete", "(", "asyncio", ".", "sleep", "(", "0", ")", ")", "finally", ":", "loop", ".", "close", "(", ")" ]
c04b0a5add58ce70153eede1a87ca171876b61c7
test
SerialReader.read
Read complete DSMR telegram's from the serial interface and parse it into CosemObject's and MbusObject's :rtype: generator
dsmr_parser/clients/serial_.py
def read(self): """ Read complete DSMR telegram's from the serial interface and parse it into CosemObject's and MbusObject's :rtype: generator """ with serial.Serial(**self.serial_settings) as serial_handle: while True: data = serial_handle.readline() self.telegram_buffer.append(data.decode('ascii')) for telegram in self.telegram_buffer.get_all(): try: yield self.telegram_parser.parse(telegram) except InvalidChecksumError as e: logger.warning(str(e)) except ParseError as e: logger.error('Failed to parse telegram: %s', e)
def read(self): """ Read complete DSMR telegram's from the serial interface and parse it into CosemObject's and MbusObject's :rtype: generator """ with serial.Serial(**self.serial_settings) as serial_handle: while True: data = serial_handle.readline() self.telegram_buffer.append(data.decode('ascii')) for telegram in self.telegram_buffer.get_all(): try: yield self.telegram_parser.parse(telegram) except InvalidChecksumError as e: logger.warning(str(e)) except ParseError as e: logger.error('Failed to parse telegram: %s', e)
[ "Read", "complete", "DSMR", "telegram", "s", "from", "the", "serial", "interface", "and", "parse", "it", "into", "CosemObject", "s", "and", "MbusObject", "s" ]
ndokter/dsmr_parser
python
https://github.com/ndokter/dsmr_parser/blob/c04b0a5add58ce70153eede1a87ca171876b61c7/dsmr_parser/clients/serial_.py#L24-L42
[ "def", "read", "(", "self", ")", ":", "with", "serial", ".", "Serial", "(", "*", "*", "self", ".", "serial_settings", ")", "as", "serial_handle", ":", "while", "True", ":", "data", "=", "serial_handle", ".", "readline", "(", ")", "self", ".", "telegram_buffer", ".", "append", "(", "data", ".", "decode", "(", "'ascii'", ")", ")", "for", "telegram", "in", "self", ".", "telegram_buffer", ".", "get_all", "(", ")", ":", "try", ":", "yield", "self", ".", "telegram_parser", ".", "parse", "(", "telegram", ")", "except", "InvalidChecksumError", "as", "e", ":", "logger", ".", "warning", "(", "str", "(", "e", ")", ")", "except", "ParseError", "as", "e", ":", "logger", ".", "error", "(", "'Failed to parse telegram: %s'", ",", "e", ")" ]
c04b0a5add58ce70153eede1a87ca171876b61c7
test
AsyncSerialReader.read
Read complete DSMR telegram's from the serial interface and parse it into CosemObject's and MbusObject's. Instead of being a generator, values are pushed to provided queue for asynchronous processing. :rtype: None
dsmr_parser/clients/serial_.py
def read(self, queue): """ Read complete DSMR telegram's from the serial interface and parse it into CosemObject's and MbusObject's. Instead of being a generator, values are pushed to provided queue for asynchronous processing. :rtype: None """ # create Serial StreamReader conn = serial_asyncio.open_serial_connection(**self.serial_settings) reader, _ = yield from conn while True: # Read line if available or give control back to loop until new # data has arrived. data = yield from reader.readline() self.telegram_buffer.append(data.decode('ascii')) for telegram in self.telegram_buffer.get_all(): try: # Push new parsed telegram onto queue. queue.put_nowait( self.telegram_parser.parse(telegram) ) except ParseError as e: logger.warning('Failed to parse telegram: %s', e)
def read(self, queue): """ Read complete DSMR telegram's from the serial interface and parse it into CosemObject's and MbusObject's. Instead of being a generator, values are pushed to provided queue for asynchronous processing. :rtype: None """ # create Serial StreamReader conn = serial_asyncio.open_serial_connection(**self.serial_settings) reader, _ = yield from conn while True: # Read line if available or give control back to loop until new # data has arrived. data = yield from reader.readline() self.telegram_buffer.append(data.decode('ascii')) for telegram in self.telegram_buffer.get_all(): try: # Push new parsed telegram onto queue. queue.put_nowait( self.telegram_parser.parse(telegram) ) except ParseError as e: logger.warning('Failed to parse telegram: %s', e)
[ "Read", "complete", "DSMR", "telegram", "s", "from", "the", "serial", "interface", "and", "parse", "it", "into", "CosemObject", "s", "and", "MbusObject", "s", "." ]
ndokter/dsmr_parser
python
https://github.com/ndokter/dsmr_parser/blob/c04b0a5add58ce70153eede1a87ca171876b61c7/dsmr_parser/clients/serial_.py#L51-L78
[ "def", "read", "(", "self", ",", "queue", ")", ":", "# create Serial StreamReader", "conn", "=", "serial_asyncio", ".", "open_serial_connection", "(", "*", "*", "self", ".", "serial_settings", ")", "reader", ",", "_", "=", "yield", "from", "conn", "while", "True", ":", "# Read line if available or give control back to loop until new", "# data has arrived.", "data", "=", "yield", "from", "reader", ".", "readline", "(", ")", "self", ".", "telegram_buffer", ".", "append", "(", "data", ".", "decode", "(", "'ascii'", ")", ")", "for", "telegram", "in", "self", ".", "telegram_buffer", ".", "get_all", "(", ")", ":", "try", ":", "# Push new parsed telegram onto queue.", "queue", ".", "put_nowait", "(", "self", ".", "telegram_parser", ".", "parse", "(", "telegram", ")", ")", "except", "ParseError", "as", "e", ":", "logger", ".", "warning", "(", "'Failed to parse telegram: %s'", ",", "e", ")" ]
c04b0a5add58ce70153eede1a87ca171876b61c7
test
create_dsmr_protocol
Creates a DSMR asyncio protocol.
dsmr_parser/clients/protocol.py
def create_dsmr_protocol(dsmr_version, telegram_callback, loop=None): """Creates a DSMR asyncio protocol.""" if dsmr_version == '2.2': specification = telegram_specifications.V2_2 serial_settings = SERIAL_SETTINGS_V2_2 elif dsmr_version == '4': specification = telegram_specifications.V4 serial_settings = SERIAL_SETTINGS_V4 elif dsmr_version == '5': specification = telegram_specifications.V5 serial_settings = SERIAL_SETTINGS_V5 else: raise NotImplementedError("No telegram parser found for version: %s", dsmr_version) protocol = partial(DSMRProtocol, loop, TelegramParser(specification), telegram_callback=telegram_callback) return protocol, serial_settings
def create_dsmr_protocol(dsmr_version, telegram_callback, loop=None): """Creates a DSMR asyncio protocol.""" if dsmr_version == '2.2': specification = telegram_specifications.V2_2 serial_settings = SERIAL_SETTINGS_V2_2 elif dsmr_version == '4': specification = telegram_specifications.V4 serial_settings = SERIAL_SETTINGS_V4 elif dsmr_version == '5': specification = telegram_specifications.V5 serial_settings = SERIAL_SETTINGS_V5 else: raise NotImplementedError("No telegram parser found for version: %s", dsmr_version) protocol = partial(DSMRProtocol, loop, TelegramParser(specification), telegram_callback=telegram_callback) return protocol, serial_settings
[ "Creates", "a", "DSMR", "asyncio", "protocol", "." ]
ndokter/dsmr_parser
python
https://github.com/ndokter/dsmr_parser/blob/c04b0a5add58ce70153eede1a87ca171876b61c7/dsmr_parser/clients/protocol.py#L17-L36
[ "def", "create_dsmr_protocol", "(", "dsmr_version", ",", "telegram_callback", ",", "loop", "=", "None", ")", ":", "if", "dsmr_version", "==", "'2.2'", ":", "specification", "=", "telegram_specifications", ".", "V2_2", "serial_settings", "=", "SERIAL_SETTINGS_V2_2", "elif", "dsmr_version", "==", "'4'", ":", "specification", "=", "telegram_specifications", ".", "V4", "serial_settings", "=", "SERIAL_SETTINGS_V4", "elif", "dsmr_version", "==", "'5'", ":", "specification", "=", "telegram_specifications", ".", "V5", "serial_settings", "=", "SERIAL_SETTINGS_V5", "else", ":", "raise", "NotImplementedError", "(", "\"No telegram parser found for version: %s\"", ",", "dsmr_version", ")", "protocol", "=", "partial", "(", "DSMRProtocol", ",", "loop", ",", "TelegramParser", "(", "specification", ")", ",", "telegram_callback", "=", "telegram_callback", ")", "return", "protocol", ",", "serial_settings" ]
c04b0a5add58ce70153eede1a87ca171876b61c7
test
create_dsmr_reader
Creates a DSMR asyncio protocol coroutine using serial port.
dsmr_parser/clients/protocol.py
def create_dsmr_reader(port, dsmr_version, telegram_callback, loop=None): """Creates a DSMR asyncio protocol coroutine using serial port.""" protocol, serial_settings = create_dsmr_protocol( dsmr_version, telegram_callback, loop=None) serial_settings['url'] = port conn = create_serial_connection(loop, protocol, **serial_settings) return conn
def create_dsmr_reader(port, dsmr_version, telegram_callback, loop=None): """Creates a DSMR asyncio protocol coroutine using serial port.""" protocol, serial_settings = create_dsmr_protocol( dsmr_version, telegram_callback, loop=None) serial_settings['url'] = port conn = create_serial_connection(loop, protocol, **serial_settings) return conn
[ "Creates", "a", "DSMR", "asyncio", "protocol", "coroutine", "using", "serial", "port", "." ]
ndokter/dsmr_parser
python
https://github.com/ndokter/dsmr_parser/blob/c04b0a5add58ce70153eede1a87ca171876b61c7/dsmr_parser/clients/protocol.py#L39-L46
[ "def", "create_dsmr_reader", "(", "port", ",", "dsmr_version", ",", "telegram_callback", ",", "loop", "=", "None", ")", ":", "protocol", ",", "serial_settings", "=", "create_dsmr_protocol", "(", "dsmr_version", ",", "telegram_callback", ",", "loop", "=", "None", ")", "serial_settings", "[", "'url'", "]", "=", "port", "conn", "=", "create_serial_connection", "(", "loop", ",", "protocol", ",", "*", "*", "serial_settings", ")", "return", "conn" ]
c04b0a5add58ce70153eede1a87ca171876b61c7
test
create_tcp_dsmr_reader
Creates a DSMR asyncio protocol coroutine using TCP connection.
dsmr_parser/clients/protocol.py
def create_tcp_dsmr_reader(host, port, dsmr_version, telegram_callback, loop=None): """Creates a DSMR asyncio protocol coroutine using TCP connection.""" protocol, _ = create_dsmr_protocol( dsmr_version, telegram_callback, loop=None) conn = loop.create_connection(protocol, host, port) return conn
def create_tcp_dsmr_reader(host, port, dsmr_version, telegram_callback, loop=None): """Creates a DSMR asyncio protocol coroutine using TCP connection.""" protocol, _ = create_dsmr_protocol( dsmr_version, telegram_callback, loop=None) conn = loop.create_connection(protocol, host, port) return conn
[ "Creates", "a", "DSMR", "asyncio", "protocol", "coroutine", "using", "TCP", "connection", "." ]
ndokter/dsmr_parser
python
https://github.com/ndokter/dsmr_parser/blob/c04b0a5add58ce70153eede1a87ca171876b61c7/dsmr_parser/clients/protocol.py#L49-L55
[ "def", "create_tcp_dsmr_reader", "(", "host", ",", "port", ",", "dsmr_version", ",", "telegram_callback", ",", "loop", "=", "None", ")", ":", "protocol", ",", "_", "=", "create_dsmr_protocol", "(", "dsmr_version", ",", "telegram_callback", ",", "loop", "=", "None", ")", "conn", "=", "loop", ".", "create_connection", "(", "protocol", ",", "host", ",", "port", ")", "return", "conn" ]
c04b0a5add58ce70153eede1a87ca171876b61c7
test
DSMRProtocol.data_received
Add incoming data to buffer.
dsmr_parser/clients/protocol.py
def data_received(self, data): """Add incoming data to buffer.""" data = data.decode('ascii') self.log.debug('received data: %s', data) self.telegram_buffer.append(data) for telegram in self.telegram_buffer.get_all(): self.handle_telegram(telegram)
def data_received(self, data): """Add incoming data to buffer.""" data = data.decode('ascii') self.log.debug('received data: %s', data) self.telegram_buffer.append(data) for telegram in self.telegram_buffer.get_all(): self.handle_telegram(telegram)
[ "Add", "incoming", "data", "to", "buffer", "." ]
ndokter/dsmr_parser
python
https://github.com/ndokter/dsmr_parser/blob/c04b0a5add58ce70153eede1a87ca171876b61c7/dsmr_parser/clients/protocol.py#L81-L88
[ "def", "data_received", "(", "self", ",", "data", ")", ":", "data", "=", "data", ".", "decode", "(", "'ascii'", ")", "self", ".", "log", ".", "debug", "(", "'received data: %s'", ",", "data", ")", "self", ".", "telegram_buffer", ".", "append", "(", "data", ")", "for", "telegram", "in", "self", ".", "telegram_buffer", ".", "get_all", "(", ")", ":", "self", ".", "handle_telegram", "(", "telegram", ")" ]
c04b0a5add58ce70153eede1a87ca171876b61c7