id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,500 |
Asana/python-asana
|
Asana_python-asana/asana/api/tags_api.py
|
asana.api.tags_api.TagsApi
|
class TagsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_tag(self, body, opts, **kwargs): # noqa: E501
"""Create a tag # noqa: E501
Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_tag(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_tag_with_http_info(body, opts, **kwargs) # noqa: E501
else:
(data) = self.create_tag_with_http_info(body, opts, **kwargs) # noqa: E501
return data
def create_tag_with_http_info(self, body, opts, **kwargs): # noqa: E501
"""Create a tag # noqa: E501
Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_tag_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_tag" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `create_tag`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/tags', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/tags', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/tags', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_tag_for_workspace(self, body, workspace_gid, opts, **kwargs): # noqa: E501
"""Create a tag in a workspace # noqa: E501
Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_tag_for_workspace(body, workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to create. (required)
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_tag_for_workspace_with_http_info(body, workspace_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.create_tag_for_workspace_with_http_info(body, workspace_gid, opts, **kwargs) # noqa: E501
return data
def create_tag_for_workspace_with_http_info(self, body, workspace_gid, opts, **kwargs): # noqa: E501
"""Create a tag in a workspace # noqa: E501
Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_tag_for_workspace_with_http_info(body, workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to create. (required)
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_tag_for_workspace" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `create_tag_for_workspace`") # noqa: E501
# verify the required parameter 'workspace_gid' is set
if (workspace_gid is None):
raise ValueError("Missing the required parameter `workspace_gid` when calling `create_tag_for_workspace`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['workspace_gid'] = workspace_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/workspaces/{workspace_gid}/tags', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/workspaces/{workspace_gid}/tags', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/workspaces/{workspace_gid}/tags', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_tag(self, tag_gid, **kwargs): # noqa: E501
"""Delete a tag # noqa: E501
A specific, existing tag can be deleted by making a DELETE request on the URL for that tag. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_tag(tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str tag_gid: Globally unique identifier for the tag. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.delete_tag_with_http_info(tag_gid, **kwargs) # noqa: E501
else:
(data) = self.delete_tag_with_http_info(tag_gid, **kwargs) # noqa: E501
return data
def delete_tag_with_http_info(self, tag_gid, **kwargs): # noqa: E501
"""Delete a tag # noqa: E501
A specific, existing tag can be deleted by making a DELETE request on the URL for that tag. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_tag_with_http_info(tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str tag_gid: Globally unique identifier for the tag. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_tag" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'tag_gid' is set
if (tag_gid is None):
raise ValueError("Missing the required parameter `tag_gid` when calling `delete_tag`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['tag_gid'] = tag_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/tags/{tag_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/tags/{tag_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/tags/{tag_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_tag(self, tag_gid, opts, **kwargs): # noqa: E501
"""Get a tag # noqa: E501
Returns the complete tag record for a single tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tag(tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str tag_gid: Globally unique identifier for the tag. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_tag_with_http_info(tag_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_tag_with_http_info(tag_gid, opts, **kwargs) # noqa: E501
return data
def get_tag_with_http_info(self, tag_gid, opts, **kwargs): # noqa: E501
"""Get a tag # noqa: E501
Returns the complete tag record for a single tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tag_with_http_info(tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str tag_gid: Globally unique identifier for the tag. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_tag" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'tag_gid' is set
if (tag_gid is None):
raise ValueError("Missing the required parameter `tag_gid` when calling `get_tag`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['tag_gid'] = tag_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/tags/{tag_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/tags/{tag_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/tags/{tag_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_tags(self, opts, **kwargs): # noqa: E501
"""Get multiple tags # noqa: E501
Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str workspace: The workspace to filter tags on.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_tags_with_http_info(opts, **kwargs) # noqa: E501
else:
(data) = self.get_tags_with_http_info(opts, **kwargs) # noqa: E501
return data
def get_tags_with_http_info(self, opts, **kwargs): # noqa: E501
"""Get multiple tags # noqa: E501
Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str workspace: The workspace to filter tags on.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_tags" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/tags', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/tags',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/tags', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_tags_for_task(self, task_gid, opts, **kwargs): # noqa: E501
"""Get a task's tags # noqa: E501
Get a compact representation of all of the tags the task has. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags_for_task(task_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str task_gid: The task to operate on. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_tags_for_task_with_http_info(task_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_tags_for_task_with_http_info(task_gid, opts, **kwargs) # noqa: E501
return data
def get_tags_for_task_with_http_info(self, task_gid, opts, **kwargs): # noqa: E501
"""Get a task's tags # noqa: E501
Get a compact representation of all of the tags the task has. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags_for_task_with_http_info(task_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str task_gid: The task to operate on. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_tags_for_task" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'task_gid' is set
if (task_gid is None):
raise ValueError("Missing the required parameter `task_gid` when calling `get_tags_for_task`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['task_gid'] = task_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/tasks/{task_gid}/tags', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/tasks/{task_gid}/tags',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/tasks/{task_gid}/tags', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_tags_for_workspace(self, workspace_gid, opts, **kwargs): # noqa: E501
"""Get tags in a workspace # noqa: E501
Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags_for_workspace(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_tags_for_workspace_with_http_info(workspace_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_tags_for_workspace_with_http_info(workspace_gid, opts, **kwargs) # noqa: E501
return data
def get_tags_for_workspace_with_http_info(self, workspace_gid, opts, **kwargs): # noqa: E501
"""Get tags in a workspace # noqa: E501
Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags_for_workspace_with_http_info(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_tags_for_workspace" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'workspace_gid' is set
if (workspace_gid is None):
raise ValueError("Missing the required parameter `workspace_gid` when calling `get_tags_for_workspace`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['workspace_gid'] = workspace_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/workspaces/{workspace_gid}/tags', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/workspaces/{workspace_gid}/tags',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/workspaces/{workspace_gid}/tags', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_tag(self, body, tag_gid, opts, **kwargs): # noqa: E501
"""Update a tag # noqa: E501
Updates the properties of a tag. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the tag. Returns the complete updated tag record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_tag(body, tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to update. (required)
:param str tag_gid: Globally unique identifier for the tag. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.update_tag_with_http_info(body, tag_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.update_tag_with_http_info(body, tag_gid, opts, **kwargs) # noqa: E501
return data
def update_tag_with_http_info(self, body, tag_gid, opts, **kwargs): # noqa: E501
"""Update a tag # noqa: E501
Updates the properties of a tag. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the tag. Returns the complete updated tag record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_tag_with_http_info(body, tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to update. (required)
:param str tag_gid: Globally unique identifier for the tag. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_tag" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `update_tag`") # noqa: E501
# verify the required parameter 'tag_gid' is set
if (tag_gid is None):
raise ValueError("Missing the required parameter `tag_gid` when calling `update_tag`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['tag_gid'] = tag_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/tags/{tag_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/tags/{tag_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/tags/{tag_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class TagsApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def create_tag(self, body, opts, **kwargs):
'''Create a tag # noqa: E501
Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_tag(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_tag_with_http_info(self, body, opts, **kwargs):
'''Create a tag # noqa: E501
Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_tag_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_tag_for_workspace(self, body, workspace_gid, opts, **kwargs):
'''Create a tag in a workspace # noqa: E501
Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_tag_for_workspace(body, workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to create. (required)
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_tag_for_workspace_with_http_info(self, body, workspace_gid, opts, **kwargs):
'''Create a tag in a workspace # noqa: E501
Creates a new tag in a workspace or organization. Every tag is required to be created in a specific workspace or organization, and this cannot be changed once set. Note that you can use the workspace parameter regardless of whether or not it is an organization. Returns the full record of the newly created tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_tag_for_workspace_with_http_info(body, workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to create. (required)
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_tag(self, tag_gid, **kwargs):
'''Delete a tag # noqa: E501
A specific, existing tag can be deleted by making a DELETE request on the URL for that tag. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_tag(tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str tag_gid: Globally unique identifier for the tag. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_tag_with_http_info(self, tag_gid, **kwargs):
'''Delete a tag # noqa: E501
A specific, existing tag can be deleted by making a DELETE request on the URL for that tag. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_tag_with_http_info(tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str tag_gid: Globally unique identifier for the tag. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_tag(self, tag_gid, opts, **kwargs):
'''Get a tag # noqa: E501
Returns the complete tag record for a single tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tag(tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str tag_gid: Globally unique identifier for the tag. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_tag_with_http_info(self, tag_gid, opts, **kwargs):
'''Get a tag # noqa: E501
Returns the complete tag record for a single tag. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tag_with_http_info(tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str tag_gid: Globally unique identifier for the tag. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_tags(self, opts, **kwargs):
'''Get multiple tags # noqa: E501
Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str workspace: The workspace to filter tags on.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_tags_with_http_info(self, opts, **kwargs):
'''Get multiple tags # noqa: E501
Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str workspace: The workspace to filter tags on.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_tags_for_task(self, task_gid, opts, **kwargs):
'''Get a task's tags # noqa: E501
Get a compact representation of all of the tags the task has. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags_for_task(task_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str task_gid: The task to operate on. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_tags_for_task_with_http_info(self, task_gid, opts, **kwargs):
'''Get a task's tags # noqa: E501
Get a compact representation of all of the tags the task has. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags_for_task_with_http_info(task_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str task_gid: The task to operate on. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_tags_for_workspace(self, workspace_gid, opts, **kwargs):
'''Get tags in a workspace # noqa: E501
Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags_for_workspace(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_tags_for_workspace_with_http_info(self, workspace_gid, opts, **kwargs):
'''Get tags in a workspace # noqa: E501
Returns the compact tag records for some filtered set of tags. Use one or more of the parameters provided to filter the tags returned. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_tags_for_workspace_with_http_info(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_tag(self, body, tag_gid, opts, **kwargs):
'''Update a tag # noqa: E501
Updates the properties of a tag. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the tag. Returns the complete updated tag record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_tag(body, tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to update. (required)
:param str tag_gid: Globally unique identifier for the tag. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_tag_with_http_info(self, body, tag_gid, opts, **kwargs):
'''Update a tag # noqa: E501
Updates the properties of a tag. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the tag. Returns the complete updated tag record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_tag_with_http_info(body, tag_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The tag to update. (required)
:param str tag_gid: Globally unique identifier for the tag. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: TagResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
| 18 | 17 | 67 | 7 | 44 | 20 | 5 | 0.47 | 1 | 4 | 2 | 0 | 17 | 1 | 17 | 17 | 1,158 | 141 | 755 | 120 | 737 | 352 | 329 | 120 | 311 | 9 | 1 | 2 | 77 |
7,501 |
Asana/python-asana
|
Asana_python-asana/asana/api/project_briefs_api.py
|
asana.api.project_briefs_api.ProjectBriefsApi
|
class ProjectBriefsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_project_brief(self, body, project_gid, opts, **kwargs): # noqa: E501
"""Create a project brief # noqa: E501
Creates a new project brief. Returns the full record of the newly created project brief. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_project_brief(body, project_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The project brief to create. (required)
:param str project_gid: Globally unique identifier for the project. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_project_brief_with_http_info(body, project_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.create_project_brief_with_http_info(body, project_gid, opts, **kwargs) # noqa: E501
return data
def create_project_brief_with_http_info(self, body, project_gid, opts, **kwargs): # noqa: E501
"""Create a project brief # noqa: E501
Creates a new project brief. Returns the full record of the newly created project brief. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_project_brief_with_http_info(body, project_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The project brief to create. (required)
:param str project_gid: Globally unique identifier for the project. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_project_brief" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `create_project_brief`") # noqa: E501
# verify the required parameter 'project_gid' is set
if (project_gid is None):
raise ValueError("Missing the required parameter `project_gid` when calling `create_project_brief`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['project_gid'] = project_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/projects/{project_gid}/project_briefs', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/projects/{project_gid}/project_briefs', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/projects/{project_gid}/project_briefs', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_project_brief(self, project_brief_gid, **kwargs): # noqa: E501
"""Delete a project brief # noqa: E501
Deletes a specific, existing project brief. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_project_brief(project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.delete_project_brief_with_http_info(project_brief_gid, **kwargs) # noqa: E501
else:
(data) = self.delete_project_brief_with_http_info(project_brief_gid, **kwargs) # noqa: E501
return data
def delete_project_brief_with_http_info(self, project_brief_gid, **kwargs): # noqa: E501
"""Delete a project brief # noqa: E501
Deletes a specific, existing project brief. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_project_brief_with_http_info(project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_project_brief" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'project_brief_gid' is set
if (project_brief_gid is None):
raise ValueError("Missing the required parameter `project_brief_gid` when calling `delete_project_brief`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['project_brief_gid'] = project_brief_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/project_briefs/{project_brief_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/project_briefs/{project_brief_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/project_briefs/{project_brief_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_project_brief(self, project_brief_gid, opts, **kwargs): # noqa: E501
"""Get a project brief # noqa: E501
Get the full record for a project brief. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_project_brief(project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_project_brief_with_http_info(project_brief_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_project_brief_with_http_info(project_brief_gid, opts, **kwargs) # noqa: E501
return data
def get_project_brief_with_http_info(self, project_brief_gid, opts, **kwargs): # noqa: E501
"""Get a project brief # noqa: E501
Get the full record for a project brief. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_project_brief_with_http_info(project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_project_brief" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'project_brief_gid' is set
if (project_brief_gid is None):
raise ValueError("Missing the required parameter `project_brief_gid` when calling `get_project_brief`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['project_brief_gid'] = project_brief_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/project_briefs/{project_brief_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/project_briefs/{project_brief_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/project_briefs/{project_brief_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_project_brief(self, body, project_brief_gid, opts, **kwargs): # noqa: E501
"""Update a project brief # noqa: E501
An existing project brief can be updated by making a PUT request on the URL for that project brief. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated project brief record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_project_brief(body, project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the project brief. (required)
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.update_project_brief_with_http_info(body, project_brief_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.update_project_brief_with_http_info(body, project_brief_gid, opts, **kwargs) # noqa: E501
return data
def update_project_brief_with_http_info(self, body, project_brief_gid, opts, **kwargs): # noqa: E501
"""Update a project brief # noqa: E501
An existing project brief can be updated by making a PUT request on the URL for that project brief. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated project brief record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_project_brief_with_http_info(body, project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the project brief. (required)
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_project_brief" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `update_project_brief`") # noqa: E501
# verify the required parameter 'project_brief_gid' is set
if (project_brief_gid is None):
raise ValueError("Missing the required parameter `project_brief_gid` when calling `update_project_brief`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['project_brief_gid'] = project_brief_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/project_briefs/{project_brief_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/project_briefs/{project_brief_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/project_briefs/{project_brief_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class ProjectBriefsApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def create_project_brief(self, body, project_gid, opts, **kwargs):
'''Create a project brief # noqa: E501
Creates a new project brief. Returns the full record of the newly created project brief. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_project_brief(body, project_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The project brief to create. (required)
:param str project_gid: Globally unique identifier for the project. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_project_brief_with_http_info(self, body, project_gid, opts, **kwargs):
'''Create a project brief # noqa: E501
Creates a new project brief. Returns the full record of the newly created project brief. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_project_brief_with_http_info(body, project_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The project brief to create. (required)
:param str project_gid: Globally unique identifier for the project. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_project_brief(self, project_brief_gid, **kwargs):
'''Delete a project brief # noqa: E501
Deletes a specific, existing project brief. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_project_brief(project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_project_brief_with_http_info(self, project_brief_gid, **kwargs):
'''Delete a project brief # noqa: E501
Deletes a specific, existing project brief. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_project_brief_with_http_info(project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_project_brief(self, project_brief_gid, opts, **kwargs):
'''Get a project brief # noqa: E501
Get the full record for a project brief. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_project_brief(project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_project_brief_with_http_info(self, project_brief_gid, opts, **kwargs):
'''Get a project brief # noqa: E501
Get the full record for a project brief. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_project_brief_with_http_info(project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_project_brief(self, body, project_brief_gid, opts, **kwargs):
'''Update a project brief # noqa: E501
An existing project brief can be updated by making a PUT request on the URL for that project brief. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated project brief record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_project_brief(body, project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the project brief. (required)
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_project_brief_with_http_info(self, body, project_brief_gid, opts, **kwargs):
'''Update a project brief # noqa: E501
An existing project brief can be updated by making a PUT request on the URL for that project brief. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated project brief record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_project_brief_with_http_info(body, project_brief_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the project brief. (required)
:param str project_brief_gid: Globally unique identifier for the project brief. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectBriefResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
| 10 | 9 | 63 | 7 | 42 | 20 | 5 | 0.47 | 1 | 3 | 1 | 0 | 9 | 1 | 9 | 9 | 582 | 72 | 380 | 63 | 370 | 180 | 174 | 63 | 164 | 9 | 1 | 2 | 44 |
7,502 |
Asana/python-asana
|
Asana_python-asana/asana/api/jobs_api.py
|
asana.api.jobs_api.JobsApi
|
class JobsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_job(self, job_gid, opts, **kwargs): # noqa: E501
"""Get a job by id # noqa: E501
Returns the full record for a job. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_job(job_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str job_gid: Globally unique identifier for the job. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: JobResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_job_with_http_info(job_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_job_with_http_info(job_gid, opts, **kwargs) # noqa: E501
return data
def get_job_with_http_info(self, job_gid, opts, **kwargs): # noqa: E501
"""Get a job by id # noqa: E501
Returns the full record for a job. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_job_with_http_info(job_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str job_gid: Globally unique identifier for the job. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: JobResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_job" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'job_gid' is set
if (job_gid is None):
raise ValueError("Missing the required parameter `job_gid` when calling `get_job`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['job_gid'] = job_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/jobs/{job_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/jobs/{job_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/jobs/{job_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class JobsApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def get_job(self, job_gid, opts, **kwargs):
'''Get a job by id # noqa: E501
Returns the full record for a job. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_job(job_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str job_gid: Globally unique identifier for the job. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: JobResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_job_with_http_info(self, job_gid, opts, **kwargs):
'''Get a job by id # noqa: E501
Returns the full record for a job. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_job_with_http_info(job_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str job_gid: Globally unique identifier for the job. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: JobResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
| 4 | 3 | 47 | 5 | 32 | 14 | 4 | 0.46 | 1 | 3 | 1 | 0 | 3 | 1 | 3 | 3 | 150 | 19 | 97 | 18 | 93 | 45 | 46 | 18 | 42 | 8 | 1 | 2 | 12 |
7,503 |
Asana/python-asana
|
Asana_python-asana/asana/api/goal_relationships_api.py
|
asana.api.goal_relationships_api.GoalRelationshipsApi
|
class GoalRelationshipsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def add_supporting_relationship(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Add a supporting goal relationship # noqa: E501
Creates a goal relationship by adding a supporting resource to a given goal. Returns the newly created goal relationship record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_supporting_relationship(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The supporting resource to be added to the goal (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.add_supporting_relationship_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.add_supporting_relationship_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
return data
def add_supporting_relationship_with_http_info(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Add a supporting goal relationship # noqa: E501
Creates a goal relationship by adding a supporting resource to a given goal. Returns the newly created goal relationship record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_supporting_relationship_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The supporting resource to be added to the goal (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_supporting_relationship" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `add_supporting_relationship`") # noqa: E501
# verify the required parameter 'goal_gid' is set
if (goal_gid is None):
raise ValueError("Missing the required parameter `goal_gid` when calling `add_supporting_relationship`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_gid'] = goal_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals/{goal_gid}/addSupportingRelationship', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goals/{goal_gid}/addSupportingRelationship', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goals/{goal_gid}/addSupportingRelationship', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_goal_relationship(self, goal_relationship_gid, opts, **kwargs): # noqa: E501
"""Get a goal relationship # noqa: E501
Returns the complete updated goal relationship record for a single goal relationship. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal_relationship(goal_relationship_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_relationship_gid: Globally unique identifier for the goal relationship. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_goal_relationship_with_http_info(goal_relationship_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_goal_relationship_with_http_info(goal_relationship_gid, opts, **kwargs) # noqa: E501
return data
def get_goal_relationship_with_http_info(self, goal_relationship_gid, opts, **kwargs): # noqa: E501
"""Get a goal relationship # noqa: E501
Returns the complete updated goal relationship record for a single goal relationship. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal_relationship_with_http_info(goal_relationship_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_relationship_gid: Globally unique identifier for the goal relationship. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_goal_relationship" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'goal_relationship_gid' is set
if (goal_relationship_gid is None):
raise ValueError("Missing the required parameter `goal_relationship_gid` when calling `get_goal_relationship`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_relationship_gid'] = goal_relationship_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goal_relationships/{goal_relationship_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goal_relationships/{goal_relationship_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goal_relationships/{goal_relationship_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_goal_relationships(self, supported_goal, opts, **kwargs): # noqa: E501
"""Get goal relationships # noqa: E501
Returns compact goal relationship records. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal_relationships(supported_goal, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str supported_goal: Globally unique identifier for the supported goal in the goal relationship. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str resource_subtype: If provided, filter to goal relationships with a given resource_subtype.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_goal_relationships_with_http_info(supported_goal, opts, **kwargs) # noqa: E501
else:
(data) = self.get_goal_relationships_with_http_info(supported_goal, opts, **kwargs) # noqa: E501
return data
def get_goal_relationships_with_http_info(self, supported_goal, opts, **kwargs): # noqa: E501
"""Get goal relationships # noqa: E501
Returns compact goal relationship records. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal_relationships_with_http_info(supported_goal, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str supported_goal: Globally unique identifier for the supported goal in the goal relationship. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str resource_subtype: If provided, filter to goal relationships with a given resource_subtype.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_goal_relationships" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'supported_goal' is set
if (supported_goal is None):
raise ValueError("Missing the required parameter `supported_goal` when calling `get_goal_relationships`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
query_params['supported_goal'] = supported_goal
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goal_relationships', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/goal_relationships',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/goal_relationships', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def remove_supporting_relationship(self, body, goal_gid, **kwargs): # noqa: E501
"""Removes a supporting goal relationship # noqa: E501
Removes a goal relationship for a given parent goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_supporting_relationship(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The supporting resource to be removed from the goal (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.remove_supporting_relationship_with_http_info(body, goal_gid, **kwargs) # noqa: E501
else:
(data) = self.remove_supporting_relationship_with_http_info(body, goal_gid, **kwargs) # noqa: E501
return data
def remove_supporting_relationship_with_http_info(self, body, goal_gid, **kwargs): # noqa: E501
"""Removes a supporting goal relationship # noqa: E501
Removes a goal relationship for a given parent goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_supporting_relationship_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The supporting resource to be removed from the goal (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_supporting_relationship" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `remove_supporting_relationship`") # noqa: E501
# verify the required parameter 'goal_gid' is set
if (goal_gid is None):
raise ValueError("Missing the required parameter `goal_gid` when calling `remove_supporting_relationship`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_gid'] = goal_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals/{goal_gid}/removeSupportingRelationship', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goals/{goal_gid}/removeSupportingRelationship', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goals/{goal_gid}/removeSupportingRelationship', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_goal_relationship(self, body, goal_relationship_gid, opts, **kwargs): # noqa: E501
"""Update a goal relationship # noqa: E501
An existing goal relationship can be updated by making a PUT request on the URL for that goal relationship. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal relationship record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal_relationship(body, goal_relationship_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal relationship. (required)
:param str goal_relationship_gid: Globally unique identifier for the goal relationship. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.update_goal_relationship_with_http_info(body, goal_relationship_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.update_goal_relationship_with_http_info(body, goal_relationship_gid, opts, **kwargs) # noqa: E501
return data
def update_goal_relationship_with_http_info(self, body, goal_relationship_gid, opts, **kwargs): # noqa: E501
"""Update a goal relationship # noqa: E501
An existing goal relationship can be updated by making a PUT request on the URL for that goal relationship. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal relationship record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal_relationship_with_http_info(body, goal_relationship_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal relationship. (required)
:param str goal_relationship_gid: Globally unique identifier for the goal relationship. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_goal_relationship" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `update_goal_relationship`") # noqa: E501
# verify the required parameter 'goal_relationship_gid' is set
if (goal_relationship_gid is None):
raise ValueError("Missing the required parameter `goal_relationship_gid` when calling `update_goal_relationship`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_relationship_gid'] = goal_relationship_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goal_relationships/{goal_relationship_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goal_relationships/{goal_relationship_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goal_relationships/{goal_relationship_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class GoalRelationshipsApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def add_supporting_relationship(self, body, goal_gid, opts, **kwargs):
'''Add a supporting goal relationship # noqa: E501
Creates a goal relationship by adding a supporting resource to a given goal. Returns the newly created goal relationship record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_supporting_relationship(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The supporting resource to be added to the goal (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def add_supporting_relationship_with_http_info(self, body, goal_gid, opts, **kwargs):
'''Add a supporting goal relationship # noqa: E501
Creates a goal relationship by adding a supporting resource to a given goal. Returns the newly created goal relationship record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_supporting_relationship_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The supporting resource to be added to the goal (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_goal_relationship(self, goal_relationship_gid, opts, **kwargs):
'''Get a goal relationship # noqa: E501
Returns the complete updated goal relationship record for a single goal relationship. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal_relationship(goal_relationship_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_relationship_gid: Globally unique identifier for the goal relationship. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_goal_relationship_with_http_info(self, goal_relationship_gid, opts, **kwargs):
'''Get a goal relationship # noqa: E501
Returns the complete updated goal relationship record for a single goal relationship. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal_relationship_with_http_info(goal_relationship_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_relationship_gid: Globally unique identifier for the goal relationship. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_goal_relationships(self, supported_goal, opts, **kwargs):
'''Get goal relationships # noqa: E501
Returns compact goal relationship records. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal_relationships(supported_goal, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str supported_goal: Globally unique identifier for the supported goal in the goal relationship. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str resource_subtype: If provided, filter to goal relationships with a given resource_subtype.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_goal_relationships_with_http_info(self, supported_goal, opts, **kwargs):
'''Get goal relationships # noqa: E501
Returns compact goal relationship records. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal_relationships_with_http_info(supported_goal, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str supported_goal: Globally unique identifier for the supported goal in the goal relationship. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str resource_subtype: If provided, filter to goal relationships with a given resource_subtype.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def remove_supporting_relationship(self, body, goal_gid, **kwargs):
'''Removes a supporting goal relationship # noqa: E501
Removes a goal relationship for a given parent goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_supporting_relationship(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The supporting resource to be removed from the goal (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def remove_supporting_relationship_with_http_info(self, body, goal_gid, **kwargs):
'''Removes a supporting goal relationship # noqa: E501
Removes a goal relationship for a given parent goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_supporting_relationship_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The supporting resource to be removed from the goal (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_goal_relationship(self, body, goal_relationship_gid, opts, **kwargs):
'''Update a goal relationship # noqa: E501
An existing goal relationship can be updated by making a PUT request on the URL for that goal relationship. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal relationship record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal_relationship(body, goal_relationship_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal relationship. (required)
:param str goal_relationship_gid: Globally unique identifier for the goal relationship. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_goal_relationship_with_http_info(self, body, goal_relationship_gid, opts, **kwargs):
'''Update a goal relationship # noqa: E501
An existing goal relationship can be updated by making a PUT request on the URL for that goal relationship. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal relationship record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal_relationship_with_http_info(body, goal_relationship_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal relationship. (required)
:param str goal_relationship_gid: Globally unique identifier for the goal relationship. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalRelationshipResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
| 12 | 11 | 66 | 7 | 43 | 21 | 5 | 0.48 | 1 | 4 | 2 | 0 | 11 | 1 | 11 | 11 | 739 | 90 | 479 | 77 | 467 | 232 | 216 | 77 | 204 | 9 | 1 | 2 | 53 |
7,504 |
Asana/python-asana
|
Asana_python-asana/test/test_batch_api_api.py
|
test.test_batch_api_api.TestBatchAPIApi
|
class TestBatchAPIApi(unittest.TestCase):
"""BatchAPIApi unit test stubs"""
def setUp(self):
self.api = BatchAPIApi() # noqa: E501
def tearDown(self):
pass
def test_create_batch_request(self):
"""Test case for create_batch_request
Submit parallel requests # noqa: E501
"""
pass
|
class TestBatchAPIApi(unittest.TestCase):
'''BatchAPIApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_batch_request(self):
'''Test case for create_batch_request
Submit parallel requests # noqa: E501
'''
pass
| 4 | 2 | 3 | 0 | 2 | 1 | 1 | 0.71 | 1 | 1 | 1 | 0 | 3 | 1 | 3 | 75 | 15 | 4 | 7 | 5 | 3 | 5 | 7 | 5 | 3 | 1 | 2 | 0 | 3 |
7,505 |
Asana/python-asana
|
Asana_python-asana/test/test_custom_field_settings_api.py
|
test.test_custom_field_settings_api.TestCustomFieldSettingsApi
|
class TestCustomFieldSettingsApi(unittest.TestCase):
"""CustomFieldSettingsApi unit test stubs"""
def setUp(self):
self.api = CustomFieldSettingsApi() # noqa: E501
def tearDown(self):
pass
def test_get_custom_field_settings_for_portfolio(self):
"""Test case for get_custom_field_settings_for_portfolio
Get a portfolio's custom fields # noqa: E501
"""
pass
def test_get_custom_field_settings_for_project(self):
"""Test case for get_custom_field_settings_for_project
Get a project's custom fields # noqa: E501
"""
pass
|
class TestCustomFieldSettingsApi(unittest.TestCase):
'''CustomFieldSettingsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_get_custom_field_settings_for_portfolio(self):
'''Test case for get_custom_field_settings_for_portfolio
Get a portfolio's custom fields # noqa: E501
'''
pass
def test_get_custom_field_settings_for_project(self):
'''Test case for get_custom_field_settings_for_project
Get a project's custom fields # noqa: E501
'''
pass
| 5 | 3 | 4 | 1 | 2 | 2 | 1 | 0.89 | 1 | 1 | 1 | 0 | 4 | 1 | 4 | 76 | 22 | 6 | 9 | 6 | 4 | 8 | 9 | 6 | 4 | 1 | 2 | 0 | 4 |
7,506 |
Asana/python-asana
|
Asana_python-asana/test/test_custom_fields_api.py
|
test.test_custom_fields_api.TestCustomFieldsApi
|
class TestCustomFieldsApi(unittest.TestCase):
"""CustomFieldsApi unit test stubs"""
def setUp(self):
self.api = CustomFieldsApi() # noqa: E501
def tearDown(self):
pass
def test_create_custom_field(self):
"""Test case for create_custom_field
Create a custom field # noqa: E501
"""
pass
def test_create_enum_option_for_custom_field(self):
"""Test case for create_enum_option_for_custom_field
Create an enum option # noqa: E501
"""
pass
def test_delete_custom_field(self):
"""Test case for delete_custom_field
Delete a custom field # noqa: E501
"""
pass
def test_get_custom_field(self):
"""Test case for get_custom_field
Get a custom field # noqa: E501
"""
pass
def test_get_custom_fields_for_workspace(self):
"""Test case for get_custom_fields_for_workspace
Get a workspace's custom fields # noqa: E501
"""
pass
def test_insert_enum_option_for_custom_field(self):
"""Test case for insert_enum_option_for_custom_field
Reorder a custom field's enum # noqa: E501
"""
pass
def test_update_custom_field(self):
"""Test case for update_custom_field
Update a custom field # noqa: E501
"""
pass
def test_update_enum_option(self):
"""Test case for update_enum_option
Update an enum option # noqa: E501
"""
pass
|
class TestCustomFieldsApi(unittest.TestCase):
'''CustomFieldsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_custom_field(self):
'''Test case for create_custom_field
Create a custom field # noqa: E501
'''
pass
def test_create_enum_option_for_custom_field(self):
'''Test case for create_enum_option_for_custom_field
Create an enum option # noqa: E501
'''
pass
def test_delete_custom_field(self):
'''Test case for delete_custom_field
Delete a custom field # noqa: E501
'''
pass
def test_get_custom_field(self):
'''Test case for get_custom_field
Get a custom field # noqa: E501
'''
pass
def test_get_custom_fields_for_workspace(self):
'''Test case for get_custom_fields_for_workspace
Get a workspace's custom fields # noqa: E501
'''
pass
def test_insert_enum_option_for_custom_field(self):
'''Test case for insert_enum_option_for_custom_field
Reorder a custom field's enum # noqa: E501
'''
pass
def test_update_custom_field(self):
'''Test case for update_custom_field
Update a custom field # noqa: E501
'''
pass
def test_update_enum_option(self):
'''Test case for update_enum_option
Update an enum option # noqa: E501
'''
pass
| 11 | 9 | 5 | 1 | 2 | 3 | 1 | 1.24 | 1 | 1 | 1 | 0 | 10 | 1 | 10 | 82 | 64 | 18 | 21 | 12 | 10 | 26 | 21 | 12 | 10 | 1 | 2 | 0 | 10 |
7,507 |
Asana/python-asana
|
Asana_python-asana/test/test_events_api.py
|
test.test_events_api.TestEventsApi
|
class TestEventsApi(unittest.TestCase):
"""EventsApi unit test stubs"""
def setUp(self):
self.api = EventsApi() # noqa: E501
def tearDown(self):
pass
def test_get_events(self):
"""Test case for get_events
Get events on a resource # noqa: E501
"""
pass
|
class TestEventsApi(unittest.TestCase):
'''EventsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_get_events(self):
'''Test case for get_events
Get events on a resource # noqa: E501
'''
pass
| 4 | 2 | 3 | 0 | 2 | 1 | 1 | 0.71 | 1 | 1 | 1 | 0 | 3 | 1 | 3 | 75 | 15 | 4 | 7 | 5 | 3 | 5 | 7 | 5 | 3 | 1 | 2 | 0 | 3 |
7,508 |
Asana/python-asana
|
Asana_python-asana/test/test_goal_relationships_api.py
|
test.test_goal_relationships_api.TestGoalRelationshipsApi
|
class TestGoalRelationshipsApi(unittest.TestCase):
"""GoalRelationshipsApi unit test stubs"""
def setUp(self):
self.api = GoalRelationshipsApi() # noqa: E501
def tearDown(self):
pass
def test_add_supporting_relationship(self):
"""Test case for add_supporting_relationship
Add a supporting goal relationship # noqa: E501
"""
pass
def test_get_goal_relationship(self):
"""Test case for get_goal_relationship
Get a goal relationship # noqa: E501
"""
pass
def test_get_goal_relationships(self):
"""Test case for get_goal_relationships
Get goal relationships # noqa: E501
"""
pass
def test_remove_supporting_relationship(self):
"""Test case for remove_supporting_relationship
Removes a supporting goal relationship # noqa: E501
"""
pass
def test_update_goal_relationship(self):
"""Test case for update_goal_relationship
Update a goal relationship # noqa: E501
"""
pass
|
class TestGoalRelationshipsApi(unittest.TestCase):
'''GoalRelationshipsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_add_supporting_relationship(self):
'''Test case for add_supporting_relationship
Add a supporting goal relationship # noqa: E501
'''
pass
def test_get_goal_relationship(self):
'''Test case for get_goal_relationship
Get a goal relationship # noqa: E501
'''
pass
def test_get_goal_relationships(self):
'''Test case for get_goal_relationships
Get goal relationships # noqa: E501
'''
pass
def test_remove_supporting_relationship(self):
'''Test case for remove_supporting_relationship
Removes a supporting goal relationship # noqa: E501
'''
pass
def test_update_goal_relationship(self):
'''Test case for update_goal_relationship
Update a goal relationship # noqa: E501
'''
pass
| 8 | 6 | 5 | 1 | 2 | 2 | 1 | 1.13 | 1 | 1 | 1 | 0 | 7 | 1 | 7 | 79 | 43 | 12 | 15 | 9 | 7 | 17 | 15 | 9 | 7 | 1 | 2 | 0 | 7 |
7,509 |
Asana/python-asana
|
Asana_python-asana/test/test_goals_api.py
|
test.test_goals_api.TestGoalsApi
|
class TestGoalsApi(unittest.TestCase):
"""GoalsApi unit test stubs"""
def setUp(self):
self.api = GoalsApi() # noqa: E501
def tearDown(self):
pass
def test_add_followers(self):
"""Test case for add_followers
Add a collaborator to a goal # noqa: E501
"""
pass
def test_create_goal(self):
"""Test case for create_goal
Create a goal # noqa: E501
"""
pass
def test_create_goal_metric(self):
"""Test case for create_goal_metric
Create a goal metric # noqa: E501
"""
pass
def test_delete_goal(self):
"""Test case for delete_goal
Delete a goal # noqa: E501
"""
pass
def test_get_goal(self):
"""Test case for get_goal
Get a goal # noqa: E501
"""
pass
def test_get_goals(self):
"""Test case for get_goals
Get goals # noqa: E501
"""
pass
def test_get_parent_goals_for_goal(self):
"""Test case for get_parent_goals_for_goal
Get parent goals from a goal # noqa: E501
"""
pass
def test_remove_followers(self):
"""Test case for remove_followers
Remove a collaborator from a goal # noqa: E501
"""
pass
def test_update_goal(self):
"""Test case for update_goal
Update a goal # noqa: E501
"""
pass
def test_update_goal_metric(self):
"""Test case for update_goal_metric
Update a goal metric # noqa: E501
"""
pass
|
class TestGoalsApi(unittest.TestCase):
'''GoalsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_add_followers(self):
'''Test case for add_followers
Add a collaborator to a goal # noqa: E501
'''
pass
def test_create_goal(self):
'''Test case for create_goal
Create a goal # noqa: E501
'''
pass
def test_create_goal_metric(self):
'''Test case for create_goal_metric
Create a goal metric # noqa: E501
'''
pass
def test_delete_goal(self):
'''Test case for delete_goal
Delete a goal # noqa: E501
'''
pass
def test_get_goal(self):
'''Test case for get_goal
Get a goal # noqa: E501
'''
pass
def test_get_goals(self):
'''Test case for get_goals
Get goals # noqa: E501
'''
pass
def test_get_parent_goals_for_goal(self):
'''Test case for get_parent_goals_for_goal
Get parent goals from a goal # noqa: E501
'''
pass
def test_remove_followers(self):
'''Test case for remove_followers
Remove a collaborator from a goal # noqa: E501
'''
pass
def test_update_goal(self):
'''Test case for update_goal
Update a goal # noqa: E501
'''
pass
def test_update_goal_metric(self):
'''Test case for update_goal_metric
Update a goal metric # noqa: E501
'''
pass
| 13 | 11 | 5 | 1 | 2 | 3 | 1 | 1.28 | 1 | 1 | 1 | 0 | 12 | 1 | 12 | 84 | 78 | 22 | 25 | 14 | 12 | 32 | 25 | 14 | 12 | 1 | 2 | 0 | 12 |
7,510 |
Asana/python-asana
|
Asana_python-asana/test/test_jobs_api.py
|
test.test_jobs_api.TestJobsApi
|
class TestJobsApi(unittest.TestCase):
"""JobsApi unit test stubs"""
def setUp(self):
self.api = JobsApi() # noqa: E501
def tearDown(self):
pass
def test_get_job(self):
"""Test case for get_job
Get a job by id # noqa: E501
"""
pass
|
class TestJobsApi(unittest.TestCase):
'''JobsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_get_job(self):
'''Test case for get_job
Get a job by id # noqa: E501
'''
pass
| 4 | 2 | 3 | 0 | 2 | 1 | 1 | 0.71 | 1 | 1 | 1 | 0 | 3 | 1 | 3 | 75 | 15 | 4 | 7 | 5 | 3 | 5 | 7 | 5 | 3 | 1 | 2 | 0 | 3 |
7,511 |
Asana/python-asana
|
Asana_python-asana/test/test_memberships_api.py
|
test.test_memberships_api.TestMembershipsApi
|
class TestMembershipsApi(unittest.TestCase):
"""MembershipsApi unit test stubs"""
def setUp(self):
self.api = MembershipsApi() # noqa: E501
def tearDown(self):
pass
def test_create_membership(self):
"""Test case for create_membership
Create a membership # noqa: E501
"""
pass
def test_delete_membership(self):
"""Test case for delete_membership
Delete a membership # noqa: E501
"""
pass
def test_get_membership(self):
"""Test case for get_membership
Get a membership # noqa: E501
"""
pass
def test_get_memberships(self):
"""Test case for get_memberships
Get multiple memberships # noqa: E501
"""
pass
|
class TestMembershipsApi(unittest.TestCase):
'''MembershipsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_membership(self):
'''Test case for create_membership
Create a membership # noqa: E501
'''
pass
def test_delete_membership(self):
'''Test case for delete_membership
Delete a membership # noqa: E501
'''
pass
def test_get_membership(self):
'''Test case for get_membership
Get a membership # noqa: E501
'''
pass
def test_get_memberships(self):
'''Test case for get_memberships
Get multiple memberships # noqa: E501
'''
pass
| 7 | 5 | 5 | 1 | 2 | 2 | 1 | 1.08 | 1 | 1 | 1 | 0 | 6 | 1 | 6 | 78 | 36 | 10 | 13 | 8 | 6 | 14 | 13 | 8 | 6 | 1 | 2 | 0 | 6 |
7,512 |
Asana/python-asana
|
Asana_python-asana/test/test_organization_exports_api.py
|
test.test_organization_exports_api.TestOrganizationExportsApi
|
class TestOrganizationExportsApi(unittest.TestCase):
"""OrganizationExportsApi unit test stubs"""
def setUp(self):
self.api = OrganizationExportsApi() # noqa: E501
def tearDown(self):
pass
def test_create_organization_export(self):
"""Test case for create_organization_export
Create an organization export request # noqa: E501
"""
pass
def test_get_organization_export(self):
"""Test case for get_organization_export
Get details on an org export request # noqa: E501
"""
pass
|
class TestOrganizationExportsApi(unittest.TestCase):
'''OrganizationExportsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_organization_export(self):
'''Test case for create_organization_export
Create an organization export request # noqa: E501
'''
pass
def test_get_organization_export(self):
'''Test case for get_organization_export
Get details on an org export request # noqa: E501
'''
pass
| 5 | 3 | 4 | 1 | 2 | 2 | 1 | 0.89 | 1 | 1 | 1 | 0 | 4 | 1 | 4 | 76 | 22 | 6 | 9 | 6 | 4 | 8 | 9 | 6 | 4 | 1 | 2 | 0 | 4 |
7,513 |
Asana/python-asana
|
Asana_python-asana/test/test_portfolio_memberships_api.py
|
test.test_portfolio_memberships_api.TestPortfolioMembershipsApi
|
class TestPortfolioMembershipsApi(unittest.TestCase):
"""PortfolioMembershipsApi unit test stubs"""
def setUp(self):
self.api = PortfolioMembershipsApi() # noqa: E501
def tearDown(self):
pass
def test_get_portfolio_membership(self):
"""Test case for get_portfolio_membership
Get a portfolio membership # noqa: E501
"""
pass
def test_get_portfolio_memberships(self):
"""Test case for get_portfolio_memberships
Get multiple portfolio memberships # noqa: E501
"""
pass
def test_get_portfolio_memberships_for_portfolio(self):
"""Test case for get_portfolio_memberships_for_portfolio
Get memberships from a portfolio # noqa: E501
"""
pass
|
class TestPortfolioMembershipsApi(unittest.TestCase):
'''PortfolioMembershipsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_get_portfolio_membership(self):
'''Test case for get_portfolio_membership
Get a portfolio membership # noqa: E501
'''
pass
def test_get_portfolio_memberships(self):
'''Test case for get_portfolio_memberships
Get multiple portfolio memberships # noqa: E501
'''
pass
def test_get_portfolio_memberships_for_portfolio(self):
'''Test case for get_portfolio_memberships_for_portfolio
Get memberships from a portfolio # noqa: E501
'''
pass
| 6 | 4 | 4 | 1 | 2 | 2 | 1 | 1 | 1 | 1 | 1 | 0 | 5 | 1 | 5 | 77 | 29 | 8 | 11 | 7 | 5 | 11 | 11 | 7 | 5 | 1 | 2 | 0 | 5 |
7,514 |
Asana/python-asana
|
Asana_python-asana/test/test_webhooks_api.py
|
test.test_webhooks_api.TestWebhooksApi
|
class TestWebhooksApi(unittest.TestCase):
"""WebhooksApi unit test stubs"""
def setUp(self):
self.api = WebhooksApi() # noqa: E501
def tearDown(self):
pass
def test_create_webhook(self):
"""Test case for create_webhook
Establish a webhook # noqa: E501
"""
pass
def test_delete_webhook(self):
"""Test case for delete_webhook
Delete a webhook # noqa: E501
"""
pass
def test_get_webhook(self):
"""Test case for get_webhook
Get a webhook # noqa: E501
"""
pass
def test_get_webhooks(self):
"""Test case for get_webhooks
Get multiple webhooks # noqa: E501
"""
pass
def test_update_webhook(self):
"""Test case for update_webhook
Update a webhook # noqa: E501
"""
pass
|
class TestWebhooksApi(unittest.TestCase):
'''WebhooksApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_webhook(self):
'''Test case for create_webhook
Establish a webhook # noqa: E501
'''
pass
def test_delete_webhook(self):
'''Test case for delete_webhook
Delete a webhook # noqa: E501
'''
pass
def test_get_webhook(self):
'''Test case for get_webhook
Get a webhook # noqa: E501
'''
pass
def test_get_webhooks(self):
'''Test case for get_webhooks
Get multiple webhooks # noqa: E501
'''
pass
def test_update_webhook(self):
'''Test case for update_webhook
Update a webhook # noqa: E501
'''
pass
| 8 | 6 | 5 | 1 | 2 | 2 | 1 | 1.13 | 1 | 1 | 1 | 0 | 7 | 1 | 7 | 79 | 43 | 12 | 15 | 9 | 7 | 17 | 15 | 9 | 7 | 1 | 2 | 0 | 7 |
7,515 |
Asana/python-asana
|
Asana_python-asana/test/test_workspace_memberships_api.py
|
test.test_workspace_memberships_api.TestWorkspaceMembershipsApi
|
class TestWorkspaceMembershipsApi(unittest.TestCase):
"""WorkspaceMembershipsApi unit test stubs"""
def setUp(self):
self.api = WorkspaceMembershipsApi() # noqa: E501
def tearDown(self):
pass
def test_get_workspace_membership(self):
"""Test case for get_workspace_membership
Get a workspace membership # noqa: E501
"""
pass
def test_get_workspace_memberships_for_user(self):
"""Test case for get_workspace_memberships_for_user
Get workspace memberships for a user # noqa: E501
"""
pass
def test_get_workspace_memberships_for_workspace(self):
"""Test case for get_workspace_memberships_for_workspace
Get the workspace memberships for a workspace # noqa: E501
"""
pass
|
class TestWorkspaceMembershipsApi(unittest.TestCase):
'''WorkspaceMembershipsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_get_workspace_membership(self):
'''Test case for get_workspace_membership
Get a workspace membership # noqa: E501
'''
pass
def test_get_workspace_memberships_for_user(self):
'''Test case for get_workspace_memberships_for_user
Get workspace memberships for a user # noqa: E501
'''
pass
def test_get_workspace_memberships_for_workspace(self):
'''Test case for get_workspace_memberships_for_workspace
Get the workspace memberships for a workspace # noqa: E501
'''
pass
| 6 | 4 | 4 | 1 | 2 | 2 | 1 | 1 | 1 | 1 | 1 | 0 | 5 | 1 | 5 | 77 | 29 | 8 | 11 | 7 | 5 | 11 | 11 | 7 | 5 | 1 | 2 | 0 | 5 |
7,516 |
Asana/python-asana
|
Asana_python-asana/test/test_workspaces_api.py
|
test.test_workspaces_api.TestWorkspacesApi
|
class TestWorkspacesApi(unittest.TestCase):
"""WorkspacesApi unit test stubs"""
def setUp(self):
self.api = WorkspacesApi() # noqa: E501
def tearDown(self):
pass
def test_add_user_for_workspace(self):
"""Test case for add_user_for_workspace
Add a user to a workspace or organization # noqa: E501
"""
pass
def test_get_workspace(self):
"""Test case for get_workspace
Get a workspace # noqa: E501
"""
pass
def test_get_workspaces(self):
"""Test case for get_workspaces
Get multiple workspaces # noqa: E501
"""
pass
def test_remove_user_for_workspace(self):
"""Test case for remove_user_for_workspace
Remove a user from a workspace or organization # noqa: E501
"""
pass
def test_update_workspace(self):
"""Test case for update_workspace
Update a workspace # noqa: E501
"""
pass
|
class TestWorkspacesApi(unittest.TestCase):
'''WorkspacesApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_add_user_for_workspace(self):
'''Test case for add_user_for_workspace
Add a user to a workspace or organization # noqa: E501
'''
pass
def test_get_workspace(self):
'''Test case for get_workspace
Get a workspace # noqa: E501
'''
pass
def test_get_workspaces(self):
'''Test case for get_workspaces
Get multiple workspaces # noqa: E501
'''
pass
def test_remove_user_for_workspace(self):
'''Test case for remove_user_for_workspace
Remove a user from a workspace or organization # noqa: E501
'''
pass
def test_update_workspace(self):
'''Test case for update_workspace
Update a workspace # noqa: E501
'''
pass
| 8 | 6 | 5 | 1 | 2 | 2 | 1 | 1.13 | 1 | 1 | 1 | 0 | 7 | 1 | 7 | 79 | 43 | 12 | 15 | 9 | 7 | 17 | 15 | 9 | 7 | 1 | 2 | 0 | 7 |
7,517 |
Asana/python-asana
|
Asana_python-asana/test/test_user_task_lists_api.py
|
test.test_user_task_lists_api.TestUserTaskListsApi
|
class TestUserTaskListsApi(unittest.TestCase):
"""UserTaskListsApi unit test stubs"""
def setUp(self):
self.api = UserTaskListsApi() # noqa: E501
def tearDown(self):
pass
def test_get_user_task_list(self):
"""Test case for get_user_task_list
Get a user task list # noqa: E501
"""
pass
def test_get_user_task_list_for_user(self):
"""Test case for get_user_task_list_for_user
Get a user's task list # noqa: E501
"""
pass
|
class TestUserTaskListsApi(unittest.TestCase):
'''UserTaskListsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_get_user_task_list(self):
'''Test case for get_user_task_list
Get a user task list # noqa: E501
'''
pass
def test_get_user_task_list_for_user(self):
'''Test case for get_user_task_list_for_user
Get a user's task list # noqa: E501
'''
pass
| 5 | 3 | 4 | 1 | 2 | 2 | 1 | 0.89 | 1 | 1 | 1 | 0 | 4 | 1 | 4 | 76 | 22 | 6 | 9 | 6 | 4 | 8 | 9 | 6 | 4 | 1 | 2 | 0 | 4 |
7,518 |
Asana/python-asana
|
Asana_python-asana/test/test_users_api.py
|
test.test_users_api.TestUsersApi
|
class TestUsersApi(unittest.TestCase):
"""UsersApi unit test stubs"""
def setUp(self):
self.api = UsersApi() # noqa: E501
def tearDown(self):
pass
def test_get_favorites_for_user(self):
"""Test case for get_favorites_for_user
Get a user's favorites # noqa: E501
"""
pass
def test_get_user(self):
"""Test case for get_user
Get a user # noqa: E501
"""
pass
def test_get_users(self):
"""Test case for get_users
Get multiple users # noqa: E501
"""
pass
def test_get_users_for_team(self):
"""Test case for get_users_for_team
Get users in a team # noqa: E501
"""
pass
def test_get_users_for_workspace(self):
"""Test case for get_users_for_workspace
Get users in a workspace or organization # noqa: E501
"""
pass
|
class TestUsersApi(unittest.TestCase):
'''UsersApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_get_favorites_for_user(self):
'''Test case for get_favorites_for_user
Get a user's favorites # noqa: E501
'''
pass
def test_get_user(self):
'''Test case for get_user
Get a user # noqa: E501
'''
pass
def test_get_users(self):
'''Test case for get_users
Get multiple users # noqa: E501
'''
pass
def test_get_users_for_team(self):
'''Test case for get_users_for_team
Get users in a team # noqa: E501
'''
pass
def test_get_users_for_workspace(self):
'''Test case for get_users_for_workspace
Get users in a workspace or organization # noqa: E501
'''
pass
| 8 | 6 | 5 | 1 | 2 | 2 | 1 | 1.13 | 1 | 1 | 1 | 0 | 7 | 1 | 7 | 79 | 43 | 12 | 15 | 9 | 7 | 17 | 15 | 9 | 7 | 1 | 2 | 0 | 7 |
7,519 |
Asana/python-asana
|
Asana_python-asana/test/test_audit_log_api_api.py
|
test.test_audit_log_api_api.TestAuditLogAPIApi
|
class TestAuditLogAPIApi(unittest.TestCase):
"""AuditLogAPIApi unit test stubs"""
def setUp(self):
self.api = AuditLogAPIApi() # noqa: E501
def tearDown(self):
pass
def test_get_audit_log_events(self):
"""Test case for get_audit_log_events
Get audit log events # noqa: E501
"""
pass
|
class TestAuditLogAPIApi(unittest.TestCase):
'''AuditLogAPIApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_get_audit_log_events(self):
'''Test case for get_audit_log_events
Get audit log events # noqa: E501
'''
pass
| 4 | 2 | 3 | 0 | 2 | 1 | 1 | 0.71 | 1 | 1 | 1 | 0 | 3 | 1 | 3 | 75 | 15 | 4 | 7 | 5 | 3 | 5 | 7 | 5 | 3 | 1 | 2 | 0 | 3 |
7,520 |
Asana/python-asana
|
Asana_python-asana/test/test_attachments_api.py
|
test.test_attachments_api.TestAttachmentsApi
|
class TestAttachmentsApi(unittest.TestCase):
"""AttachmentsApi unit test stubs"""
def setUp(self):
self.api = AttachmentsApi() # noqa: E501
def tearDown(self):
pass
def test_create_attachment_for_object(self):
"""Test case for create_attachment_for_object
Upload an attachment # noqa: E501
"""
pass
def test_delete_attachment(self):
"""Test case for delete_attachment
Delete an attachment # noqa: E501
"""
pass
def test_get_attachment(self):
"""Test case for get_attachment
Get an attachment # noqa: E501
"""
pass
def test_get_attachments_for_object(self):
"""Test case for get_attachments_for_object
Get attachments from an object # noqa: E501
"""
pass
|
class TestAttachmentsApi(unittest.TestCase):
'''AttachmentsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_attachment_for_object(self):
'''Test case for create_attachment_for_object
Upload an attachment # noqa: E501
'''
pass
def test_delete_attachment(self):
'''Test case for delete_attachment
Delete an attachment # noqa: E501
'''
pass
def test_get_attachment(self):
'''Test case for get_attachment
Get an attachment # noqa: E501
'''
pass
def test_get_attachments_for_object(self):
'''Test case for get_attachments_for_object
Get attachments from an object # noqa: E501
'''
pass
| 7 | 5 | 5 | 1 | 2 | 2 | 1 | 1.08 | 1 | 1 | 1 | 0 | 6 | 1 | 6 | 78 | 36 | 10 | 13 | 8 | 6 | 14 | 13 | 8 | 6 | 1 | 2 | 0 | 6 |
7,521 |
Asana/python-asana
|
Asana_python-asana/test/test_allocations_api.py
|
test.test_allocations_api.TestAllocationsApi
|
class TestAllocationsApi(unittest.TestCase):
"""AllocationsApi unit test stubs"""
def setUp(self):
self.api = AllocationsApi() # noqa: E501
def tearDown(self):
pass
def test_create_allocation(self):
"""Test case for create_allocation
Create an allocation # noqa: E501
"""
pass
def test_delete_allocation(self):
"""Test case for delete_allocation
Delete an allocation # noqa: E501
"""
pass
def test_get_allocation(self):
"""Test case for get_allocation
Get an allocation # noqa: E501
"""
pass
def test_get_allocations(self):
"""Test case for get_allocations
Get multiple allocations # noqa: E501
"""
pass
def test_update_allocation(self):
"""Test case for update_allocation
Update an allocation # noqa: E501
"""
pass
|
class TestAllocationsApi(unittest.TestCase):
'''AllocationsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_allocation(self):
'''Test case for create_allocation
Create an allocation # noqa: E501
'''
pass
def test_delete_allocation(self):
'''Test case for delete_allocation
Delete an allocation # noqa: E501
'''
pass
def test_get_allocation(self):
'''Test case for get_allocation
Get an allocation # noqa: E501
'''
pass
def test_get_allocations(self):
'''Test case for get_allocations
Get multiple allocations # noqa: E501
'''
pass
def test_update_allocation(self):
'''Test case for update_allocation
Update an allocation # noqa: E501
'''
pass
| 8 | 6 | 5 | 1 | 2 | 2 | 1 | 1.13 | 1 | 1 | 1 | 0 | 7 | 1 | 7 | 79 | 43 | 12 | 15 | 9 | 7 | 17 | 15 | 9 | 7 | 1 | 2 | 0 | 7 |
7,522 |
Asana/python-asana
|
Asana_python-asana/test/test_typeahead_api.py
|
test.test_typeahead_api.TestTypeaheadApi
|
class TestTypeaheadApi(unittest.TestCase):
"""TypeaheadApi unit test stubs"""
def setUp(self):
self.api = TypeaheadApi() # noqa: E501
def tearDown(self):
pass
def test_typeahead_for_workspace(self):
"""Test case for typeahead_for_workspace
Get objects via typeahead # noqa: E501
"""
pass
|
class TestTypeaheadApi(unittest.TestCase):
'''TypeaheadApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_typeahead_for_workspace(self):
'''Test case for typeahead_for_workspace
Get objects via typeahead # noqa: E501
'''
pass
| 4 | 2 | 3 | 0 | 2 | 1 | 1 | 0.71 | 1 | 1 | 1 | 0 | 3 | 1 | 3 | 75 | 15 | 4 | 7 | 5 | 3 | 5 | 7 | 5 | 3 | 1 | 2 | 0 | 3 |
7,523 |
Asana/python-asana
|
Asana_python-asana/asana/api/events_api.py
|
asana.api.events_api.EventsApi
|
class EventsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_events(self, resource, opts, **kwargs): # noqa: E501
"""Get events on a resource # noqa: E501
Returns the full record for all events that have occurred since the sync token was created. A `GET` request to the endpoint `/[path_to_resource]/events` can be made in lieu of including the resource ID in the data for the request. Asana limits a single sync token to 100 events. If more than 100 events exist for a given resource, `has_more: true` will be returned in the response, indicating that there are more events to pull. *Note: The resource returned will be the resource that triggered the event. This may be different from the one that the events were requested for. For example, a subscription to a project will contain events for tasks contained within the project.* # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_events(resource, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str resource: A resource ID to subscribe to. The resource can be a task, project, or goal. (required)
:param str sync: A sync token received from the last request, or none on first sync. Events will be returned from the point in time that the sync token was generated. *Note: On your first request, omit the sync token. The response will be the same as for an expired sync token, and will include a new valid sync token.If the sync token is too old (which may happen from time to time) the API will return a `412 Precondition Failed` error, and include a fresh sync token in the response.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EventResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_events_with_http_info(resource, opts, **kwargs) # noqa: E501
else:
(data) = self.get_events_with_http_info(resource, opts, **kwargs) # noqa: E501
return data
def get_events_with_http_info(self, resource, opts, **kwargs): # noqa: E501
"""Get events on a resource # noqa: E501
Returns the full record for all events that have occurred since the sync token was created. A `GET` request to the endpoint `/[path_to_resource]/events` can be made in lieu of including the resource ID in the data for the request. Asana limits a single sync token to 100 events. If more than 100 events exist for a given resource, `has_more: true` will be returned in the response, indicating that there are more events to pull. *Note: The resource returned will be the resource that triggered the event. This may be different from the one that the events were requested for. For example, a subscription to a project will contain events for tasks contained within the project.* # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_events_with_http_info(resource, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str resource: A resource ID to subscribe to. The resource can be a task, project, or goal. (required)
:param str sync: A sync token received from the last request, or none on first sync. Events will be returned from the point in time that the sync token was generated. *Note: On your first request, omit the sync token. The response will be the same as for an expired sync token, and will include a new valid sync token.If the sync token is too old (which may happen from time to time) the API will return a `412 Precondition Failed` error, and include a fresh sync token in the response.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EventResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_events" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'resource' is set
if (resource is None):
raise ValueError("Missing the required parameter `resource` when calling `get_events`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
query_params['resource'] = resource
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/events', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return EventIterator(
self.api_client,
{
"resource_path": '/events',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/events', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class EventsApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def get_events(self, resource, opts, **kwargs):
'''Get events on a resource # noqa: E501
Returns the full record for all events that have occurred since the sync token was created. A `GET` request to the endpoint `/[path_to_resource]/events` can be made in lieu of including the resource ID in the data for the request. Asana limits a single sync token to 100 events. If more than 100 events exist for a given resource, `has_more: true` will be returned in the response, indicating that there are more events to pull. *Note: The resource returned will be the resource that triggered the event. This may be different from the one that the events were requested for. For example, a subscription to a project will contain events for tasks contained within the project.* # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_events(resource, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str resource: A resource ID to subscribe to. The resource can be a task, project, or goal. (required)
:param str sync: A sync token received from the last request, or none on first sync. Events will be returned from the point in time that the sync token was generated. *Note: On your first request, omit the sync token. The response will be the same as for an expired sync token, and will include a new valid sync token.If the sync token is too old (which may happen from time to time) the API will return a `412 Precondition Failed` error, and include a fresh sync token in the response.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EventResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_events_with_http_info(self, resource, opts, **kwargs):
'''Get events on a resource # noqa: E501
Returns the full record for all events that have occurred since the sync token was created. A `GET` request to the endpoint `/[path_to_resource]/events` can be made in lieu of including the resource ID in the data for the request. Asana limits a single sync token to 100 events. If more than 100 events exist for a given resource, `has_more: true` will be returned in the response, indicating that there are more events to pull. *Note: The resource returned will be the resource that triggered the event. This may be different from the one that the events were requested for. For example, a subscription to a project will contain events for tasks contained within the project.* # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_events_with_http_info(resource, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str resource: A resource ID to subscribe to. The resource can be a task, project, or goal. (required)
:param str sync: A sync token received from the last request, or none on first sync. Events will be returned from the point in time that the sync token was generated. *Note: On your first request, omit the sync token. The response will be the same as for an expired sync token, and will include a new valid sync token.If the sync token is too old (which may happen from time to time) the API will return a `412 Precondition Failed` error, and include a fresh sync token in the response.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EventResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
| 4 | 3 | 49 | 5 | 33 | 14 | 3 | 0.45 | 1 | 4 | 2 | 0 | 3 | 1 | 3 | 3 | 155 | 19 | 100 | 17 | 96 | 45 | 44 | 17 | 40 | 6 | 1 | 2 | 10 |
7,524 |
Asana/python-asana
|
Asana_python-asana/asana/api/custom_fields_api.py
|
asana.api.custom_fields_api.CustomFieldsApi
|
class CustomFieldsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_custom_field(self, body, opts, **kwargs): # noqa: E501
"""Create a custom field # noqa: E501
Creates a new custom field in a workspace. Every custom field is required to be created in a specific workspace, and this workspace cannot be changed once set. A custom field’s name must be unique within a workspace and not conflict with names of existing task properties such as `Due Date` or `Assignee`. A custom field’s type must be one of `text`, `enum`, `multi_enum`, `number`, `date`, or `people`. Returns the full record of the newly created custom field. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_custom_field(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The custom field object to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_custom_field_with_http_info(body, opts, **kwargs) # noqa: E501
else:
(data) = self.create_custom_field_with_http_info(body, opts, **kwargs) # noqa: E501
return data
def create_custom_field_with_http_info(self, body, opts, **kwargs): # noqa: E501
"""Create a custom field # noqa: E501
Creates a new custom field in a workspace. Every custom field is required to be created in a specific workspace, and this workspace cannot be changed once set. A custom field’s name must be unique within a workspace and not conflict with names of existing task properties such as `Due Date` or `Assignee`. A custom field’s type must be one of `text`, `enum`, `multi_enum`, `number`, `date`, or `people`. Returns the full record of the newly created custom field. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_custom_field_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The custom field object to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_custom_field" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `create_custom_field`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/custom_fields', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/custom_fields', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/custom_fields', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_enum_option_for_custom_field(self, custom_field_gid, opts, **kwargs): # noqa: E501
"""Create an enum option # noqa: E501
Creates an enum option and adds it to this custom field’s list of enum options. A custom field can have at most 500 enum options (including disabled options). By default new enum options are inserted at the end of a custom field’s list. Locked custom fields can only have enum options added by the user who locked the field. Returns the full record of the newly created enum option. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_enum_option_for_custom_field(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The enum option object to create.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_enum_option_for_custom_field_with_http_info(custom_field_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.create_enum_option_for_custom_field_with_http_info(custom_field_gid, opts, **kwargs) # noqa: E501
return data
def create_enum_option_for_custom_field_with_http_info(self, custom_field_gid, opts, **kwargs): # noqa: E501
"""Create an enum option # noqa: E501
Creates an enum option and adds it to this custom field’s list of enum options. A custom field can have at most 500 enum options (including disabled options). By default new enum options are inserted at the end of a custom field’s list. Locked custom fields can only have enum options added by the user who locked the field. Returns the full record of the newly created enum option. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_enum_option_for_custom_field_with_http_info(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The enum option object to create.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_enum_option_for_custom_field" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'custom_field_gid' is set
if (custom_field_gid is None):
raise ValueError("Missing the required parameter `custom_field_gid` when calling `create_enum_option_for_custom_field`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['custom_field_gid'] = custom_field_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = opts['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/custom_fields/{custom_field_gid}/enum_options', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/custom_fields/{custom_field_gid}/enum_options', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/custom_fields/{custom_field_gid}/enum_options', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_custom_field(self, custom_field_gid, **kwargs): # noqa: E501
"""Delete a custom field # noqa: E501
A specific, existing custom field can be deleted by making a DELETE request on the URL for that custom field. Locked custom fields can only be deleted by the user who locked the field. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_custom_field(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.delete_custom_field_with_http_info(custom_field_gid, **kwargs) # noqa: E501
else:
(data) = self.delete_custom_field_with_http_info(custom_field_gid, **kwargs) # noqa: E501
return data
def delete_custom_field_with_http_info(self, custom_field_gid, **kwargs): # noqa: E501
"""Delete a custom field # noqa: E501
A specific, existing custom field can be deleted by making a DELETE request on the URL for that custom field. Locked custom fields can only be deleted by the user who locked the field. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_custom_field_with_http_info(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_custom_field" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'custom_field_gid' is set
if (custom_field_gid is None):
raise ValueError("Missing the required parameter `custom_field_gid` when calling `delete_custom_field`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['custom_field_gid'] = custom_field_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/custom_fields/{custom_field_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/custom_fields/{custom_field_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/custom_fields/{custom_field_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_custom_field(self, custom_field_gid, opts, **kwargs): # noqa: E501
"""Get a custom field # noqa: E501
Get the complete definition of a custom field’s metadata. Since custom fields can be defined for one of a number of types, and these types have different data and behaviors, there are fields that are relevant to a particular type. For instance, as noted above, enum_options is only relevant for the enum type and defines the set of choices that the enum could represent. The examples below show some of these type-specific custom field definitions. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_custom_field_with_http_info(custom_field_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_custom_field_with_http_info(custom_field_gid, opts, **kwargs) # noqa: E501
return data
def get_custom_field_with_http_info(self, custom_field_gid, opts, **kwargs): # noqa: E501
"""Get a custom field # noqa: E501
Get the complete definition of a custom field’s metadata. Since custom fields can be defined for one of a number of types, and these types have different data and behaviors, there are fields that are relevant to a particular type. For instance, as noted above, enum_options is only relevant for the enum type and defines the set of choices that the enum could represent. The examples below show some of these type-specific custom field definitions. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field_with_http_info(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_custom_field" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'custom_field_gid' is set
if (custom_field_gid is None):
raise ValueError("Missing the required parameter `custom_field_gid` when calling `get_custom_field`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['custom_field_gid'] = custom_field_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/custom_fields/{custom_field_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/custom_fields/{custom_field_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/custom_fields/{custom_field_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_custom_fields_for_workspace(self, workspace_gid, opts, **kwargs): # noqa: E501
"""Get a workspace's custom fields # noqa: E501
Returns a list of the compact representation of all of the custom fields in a workspace. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_fields_for_workspace(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_custom_fields_for_workspace_with_http_info(workspace_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_custom_fields_for_workspace_with_http_info(workspace_gid, opts, **kwargs) # noqa: E501
return data
def get_custom_fields_for_workspace_with_http_info(self, workspace_gid, opts, **kwargs): # noqa: E501
"""Get a workspace's custom fields # noqa: E501
Returns a list of the compact representation of all of the custom fields in a workspace. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_fields_for_workspace_with_http_info(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_custom_fields_for_workspace" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'workspace_gid' is set
if (workspace_gid is None):
raise ValueError("Missing the required parameter `workspace_gid` when calling `get_custom_fields_for_workspace`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['workspace_gid'] = workspace_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/workspaces/{workspace_gid}/custom_fields', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/workspaces/{workspace_gid}/custom_fields',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/workspaces/{workspace_gid}/custom_fields', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def insert_enum_option_for_custom_field(self, custom_field_gid, opts, **kwargs): # noqa: E501
"""Reorder a custom field's enum # noqa: E501
Moves a particular enum option to be either before or after another specified enum option in the custom field. Locked custom fields can only be reordered by the user who locked the field. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.insert_enum_option_for_custom_field(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The enum option object to create.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.insert_enum_option_for_custom_field_with_http_info(custom_field_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.insert_enum_option_for_custom_field_with_http_info(custom_field_gid, opts, **kwargs) # noqa: E501
return data
def insert_enum_option_for_custom_field_with_http_info(self, custom_field_gid, opts, **kwargs): # noqa: E501
"""Reorder a custom field's enum # noqa: E501
Moves a particular enum option to be either before or after another specified enum option in the custom field. Locked custom fields can only be reordered by the user who locked the field. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.insert_enum_option_for_custom_field_with_http_info(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The enum option object to create.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method insert_enum_option_for_custom_field" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'custom_field_gid' is set
if (custom_field_gid is None):
raise ValueError("Missing the required parameter `custom_field_gid` when calling `insert_enum_option_for_custom_field`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['custom_field_gid'] = custom_field_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = opts['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/custom_fields/{custom_field_gid}/enum_options/insert', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/custom_fields/{custom_field_gid}/enum_options/insert', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/custom_fields/{custom_field_gid}/enum_options/insert', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_custom_field(self, custom_field_gid, opts, **kwargs): # noqa: E501
"""Update a custom field # noqa: E501
A specific, existing custom field can be updated by making a PUT request on the URL for that custom field. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the custom field. A custom field’s `type` cannot be updated. An enum custom field’s `enum_options` cannot be updated with this endpoint. Instead see “Work With Enum Options” for information on how to update `enum_options`. Locked custom fields can only be updated by the user who locked the field. Returns the complete updated custom field record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_custom_field(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The custom field object with all updated properties.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.update_custom_field_with_http_info(custom_field_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.update_custom_field_with_http_info(custom_field_gid, opts, **kwargs) # noqa: E501
return data
def update_custom_field_with_http_info(self, custom_field_gid, opts, **kwargs): # noqa: E501
"""Update a custom field # noqa: E501
A specific, existing custom field can be updated by making a PUT request on the URL for that custom field. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the custom field. A custom field’s `type` cannot be updated. An enum custom field’s `enum_options` cannot be updated with this endpoint. Instead see “Work With Enum Options” for information on how to update `enum_options`. Locked custom fields can only be updated by the user who locked the field. Returns the complete updated custom field record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_custom_field_with_http_info(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The custom field object with all updated properties.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_custom_field" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'custom_field_gid' is set
if (custom_field_gid is None):
raise ValueError("Missing the required parameter `custom_field_gid` when calling `update_custom_field`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['custom_field_gid'] = custom_field_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = opts['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/custom_fields/{custom_field_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/custom_fields/{custom_field_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/custom_fields/{custom_field_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_enum_option(self, enum_option_gid, opts, **kwargs): # noqa: E501
"""Update an enum option # noqa: E501
Updates an existing enum option. Enum custom fields require at least one enabled enum option. Locked custom fields can only be updated by the user who locked the field. Returns the full record of the updated enum option. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_enum_option(enum_option_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str enum_option_gid: Globally unique identifier for the enum option. (required)
:param dict body: The enum option object to update
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.update_enum_option_with_http_info(enum_option_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.update_enum_option_with_http_info(enum_option_gid, opts, **kwargs) # noqa: E501
return data
def update_enum_option_with_http_info(self, enum_option_gid, opts, **kwargs): # noqa: E501
"""Update an enum option # noqa: E501
Updates an existing enum option. Enum custom fields require at least one enabled enum option. Locked custom fields can only be updated by the user who locked the field. Returns the full record of the updated enum option. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_enum_option_with_http_info(enum_option_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str enum_option_gid: Globally unique identifier for the enum option. (required)
:param dict body: The enum option object to update
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_enum_option" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'enum_option_gid' is set
if (enum_option_gid is None):
raise ValueError("Missing the required parameter `enum_option_gid` when calling `update_enum_option`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['enum_option_gid'] = enum_option_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = opts['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/enum_options/{enum_option_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/enum_options/{enum_option_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/enum_options/{enum_option_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class CustomFieldsApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def create_custom_field(self, body, opts, **kwargs):
'''Create a custom field # noqa: E501
Creates a new custom field in a workspace. Every custom field is required to be created in a specific workspace, and this workspace cannot be changed once set. A custom field’s name must be unique within a workspace and not conflict with names of existing task properties such as `Due Date` or `Assignee`. A custom field’s type must be one of `text`, `enum`, `multi_enum`, `number`, `date`, or `people`. Returns the full record of the newly created custom field. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_custom_field(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The custom field object to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_custom_field_with_http_info(self, body, opts, **kwargs):
'''Create a custom field # noqa: E501
Creates a new custom field in a workspace. Every custom field is required to be created in a specific workspace, and this workspace cannot be changed once set. A custom field’s name must be unique within a workspace and not conflict with names of existing task properties such as `Due Date` or `Assignee`. A custom field’s type must be one of `text`, `enum`, `multi_enum`, `number`, `date`, or `people`. Returns the full record of the newly created custom field. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_custom_field_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The custom field object to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_enum_option_for_custom_field(self, custom_field_gid, opts, **kwargs):
'''Create an enum option # noqa: E501
Creates an enum option and adds it to this custom field’s list of enum options. A custom field can have at most 500 enum options (including disabled options). By default new enum options are inserted at the end of a custom field’s list. Locked custom fields can only have enum options added by the user who locked the field. Returns the full record of the newly created enum option. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_enum_option_for_custom_field(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The enum option object to create.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_enum_option_for_custom_field_with_http_info(self, custom_field_gid, opts, **kwargs):
'''Create an enum option # noqa: E501
Creates an enum option and adds it to this custom field’s list of enum options. A custom field can have at most 500 enum options (including disabled options). By default new enum options are inserted at the end of a custom field’s list. Locked custom fields can only have enum options added by the user who locked the field. Returns the full record of the newly created enum option. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_enum_option_for_custom_field_with_http_info(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The enum option object to create.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_custom_field(self, custom_field_gid, **kwargs):
'''Delete a custom field # noqa: E501
A specific, existing custom field can be deleted by making a DELETE request on the URL for that custom field. Locked custom fields can only be deleted by the user who locked the field. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_custom_field(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_custom_field_with_http_info(self, custom_field_gid, **kwargs):
'''Delete a custom field # noqa: E501
A specific, existing custom field can be deleted by making a DELETE request on the URL for that custom field. Locked custom fields can only be deleted by the user who locked the field. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_custom_field_with_http_info(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_custom_field(self, custom_field_gid, opts, **kwargs):
'''Get a custom field # noqa: E501
Get the complete definition of a custom field’s metadata. Since custom fields can be defined for one of a number of types, and these types have different data and behaviors, there are fields that are relevant to a particular type. For instance, as noted above, enum_options is only relevant for the enum type and defines the set of choices that the enum could represent. The examples below show some of these type-specific custom field definitions. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_custom_field_with_http_info(self, custom_field_gid, opts, **kwargs):
'''Get a custom field # noqa: E501
Get the complete definition of a custom field’s metadata. Since custom fields can be defined for one of a number of types, and these types have different data and behaviors, there are fields that are relevant to a particular type. For instance, as noted above, enum_options is only relevant for the enum type and defines the set of choices that the enum could represent. The examples below show some of these type-specific custom field definitions. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field_with_http_info(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_custom_fields_for_workspace(self, workspace_gid, opts, **kwargs):
'''Get a workspace's custom fields # noqa: E501
Returns a list of the compact representation of all of the custom fields in a workspace. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_fields_for_workspace(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_custom_fields_for_workspace_with_http_info(self, workspace_gid, opts, **kwargs):
'''Get a workspace's custom fields # noqa: E501
Returns a list of the compact representation of all of the custom fields in a workspace. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_fields_for_workspace_with_http_info(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def insert_enum_option_for_custom_field(self, custom_field_gid, opts, **kwargs):
'''Reorder a custom field's enum # noqa: E501
Moves a particular enum option to be either before or after another specified enum option in the custom field. Locked custom fields can only be reordered by the user who locked the field. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.insert_enum_option_for_custom_field(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The enum option object to create.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
'''
pass
def insert_enum_option_for_custom_field_with_http_info(self, custom_field_gid, opts, **kwargs):
'''Reorder a custom field's enum # noqa: E501
Moves a particular enum option to be either before or after another specified enum option in the custom field. Locked custom fields can only be reordered by the user who locked the field. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.insert_enum_option_for_custom_field_with_http_info(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The enum option object to create.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_custom_field(self, custom_field_gid, opts, **kwargs):
'''Update a custom field # noqa: E501
A specific, existing custom field can be updated by making a PUT request on the URL for that custom field. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the custom field. A custom field’s `type` cannot be updated. An enum custom field’s `enum_options` cannot be updated with this endpoint. Instead see “Work With Enum Options” for information on how to update `enum_options`. Locked custom fields can only be updated by the user who locked the field. Returns the complete updated custom field record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_custom_field(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The custom field object with all updated properties.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_custom_field_with_http_info(self, custom_field_gid, opts, **kwargs):
'''Update a custom field # noqa: E501
A specific, existing custom field can be updated by making a PUT request on the URL for that custom field. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged When using this method, it is best to specify only those fields you wish to change, or else you may overwrite changes made by another user since you last retrieved the custom field. A custom field’s `type` cannot be updated. An enum custom field’s `enum_options` cannot be updated with this endpoint. Instead see “Work With Enum Options” for information on how to update `enum_options`. Locked custom fields can only be updated by the user who locked the field. Returns the complete updated custom field record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_custom_field_with_http_info(custom_field_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str custom_field_gid: Globally unique identifier for the custom field. (required)
:param dict body: The custom field object with all updated properties.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_enum_option(self, enum_option_gid, opts, **kwargs):
'''Update an enum option # noqa: E501
Updates an existing enum option. Enum custom fields require at least one enabled enum option. Locked custom fields can only be updated by the user who locked the field. Returns the full record of the updated enum option. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_enum_option(enum_option_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str enum_option_gid: Globally unique identifier for the enum option. (required)
:param dict body: The enum option object to update
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_enum_option_with_http_info(self, enum_option_gid, opts, **kwargs):
'''Update an enum option # noqa: E501
Updates an existing enum option. Enum custom fields require at least one enabled enum option. Locked custom fields can only be updated by the user who locked the field. Returns the full record of the updated enum option. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_enum_option_with_http_info(enum_option_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str enum_option_gid: Globally unique identifier for the enum option. (required)
:param dict body: The enum option object to update
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: EnumOptionData
If the method is called asynchronously,
returns the request thread.
'''
pass
| 18 | 17 | 67 | 7 | 44 | 21 | 5 | 0.47 | 1 | 4 | 2 | 0 | 17 | 1 | 17 | 17 | 1,154 | 143 | 752 | 122 | 734 | 355 | 334 | 122 | 316 | 8 | 1 | 2 | 80 |
7,525 |
Asana/python-asana
|
Asana_python-asana/asana/api/custom_field_settings_api.py
|
asana.api.custom_field_settings_api.CustomFieldSettingsApi
|
class CustomFieldSettingsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_custom_field_settings_for_portfolio(self, portfolio_gid, opts, **kwargs): # noqa: E501
"""Get a portfolio's custom fields # noqa: E501
Returns a list of all of the custom fields settings on a portfolio, in compact form. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field_settings_for_portfolio(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldSettingResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_custom_field_settings_for_portfolio_with_http_info(portfolio_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_custom_field_settings_for_portfolio_with_http_info(portfolio_gid, opts, **kwargs) # noqa: E501
return data
def get_custom_field_settings_for_portfolio_with_http_info(self, portfolio_gid, opts, **kwargs): # noqa: E501
"""Get a portfolio's custom fields # noqa: E501
Returns a list of all of the custom fields settings on a portfolio, in compact form. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field_settings_for_portfolio_with_http_info(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldSettingResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_custom_field_settings_for_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `get_custom_field_settings_for_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/custom_field_settings', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/portfolios/{portfolio_gid}/custom_field_settings',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/custom_field_settings', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_custom_field_settings_for_project(self, project_gid, opts, **kwargs): # noqa: E501
"""Get a project's custom fields # noqa: E501
Returns a list of all of the custom fields settings on a project, in compact form. Note that, as in all queries to collections which return compact representation, `opt_fields` can be used to include more data than is returned in the compact representation. See the [documentation for input/output options](https://developers.asana.com/docs/inputoutput-options) for more information. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field_settings_for_project(project_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_gid: Globally unique identifier for the project. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldSettingResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_custom_field_settings_for_project_with_http_info(project_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_custom_field_settings_for_project_with_http_info(project_gid, opts, **kwargs) # noqa: E501
return data
def get_custom_field_settings_for_project_with_http_info(self, project_gid, opts, **kwargs): # noqa: E501
"""Get a project's custom fields # noqa: E501
Returns a list of all of the custom fields settings on a project, in compact form. Note that, as in all queries to collections which return compact representation, `opt_fields` can be used to include more data than is returned in the compact representation. See the [documentation for input/output options](https://developers.asana.com/docs/inputoutput-options) for more information. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field_settings_for_project_with_http_info(project_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_gid: Globally unique identifier for the project. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldSettingResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_custom_field_settings_for_project" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'project_gid' is set
if (project_gid is None):
raise ValueError("Missing the required parameter `project_gid` when calling `get_custom_field_settings_for_project`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['project_gid'] = project_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/projects/{project_gid}/custom_field_settings', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/projects/{project_gid}/custom_field_settings',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/projects/{project_gid}/custom_field_settings', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class CustomFieldSettingsApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def get_custom_field_settings_for_portfolio(self, portfolio_gid, opts, **kwargs):
'''Get a portfolio's custom fields # noqa: E501
Returns a list of all of the custom fields settings on a portfolio, in compact form. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field_settings_for_portfolio(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldSettingResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_custom_field_settings_for_portfolio_with_http_info(self, portfolio_gid, opts, **kwargs):
'''Get a portfolio's custom fields # noqa: E501
Returns a list of all of the custom fields settings on a portfolio, in compact form. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field_settings_for_portfolio_with_http_info(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldSettingResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_custom_field_settings_for_project(self, project_gid, opts, **kwargs):
'''Get a project's custom fields # noqa: E501
Returns a list of all of the custom fields settings on a project, in compact form. Note that, as in all queries to collections which return compact representation, `opt_fields` can be used to include more data than is returned in the compact representation. See the [documentation for input/output options](https://developers.asana.com/docs/inputoutput-options) for more information. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field_settings_for_project(project_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_gid: Globally unique identifier for the project. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldSettingResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_custom_field_settings_for_project_with_http_info(self, project_gid, opts, **kwargs):
'''Get a project's custom fields # noqa: E501
Returns a list of all of the custom fields settings on a project, in compact form. Note that, as in all queries to collections which return compact representation, `opt_fields` can be used to include more data than is returned in the compact representation. See the [documentation for input/output options](https://developers.asana.com/docs/inputoutput-options) for more information. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_custom_field_settings_for_project_with_http_info(project_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str project_gid: Globally unique identifier for the project. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: CustomFieldSettingResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
| 6 | 5 | 58 | 6 | 39 | 18 | 4 | 0.47 | 1 | 4 | 2 | 0 | 5 | 1 | 5 | 5 | 303 | 36 | 195 | 31 | 189 | 92 | 83 | 31 | 77 | 6 | 1 | 2 | 18 |
7,526 |
Asana/python-asana
|
Asana_python-asana/asana/api/batch_api_api.py
|
asana.api.batch_api_api.BatchAPIApi
|
class BatchAPIApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_batch_request(self, body, opts, **kwargs): # noqa: E501
"""Submit parallel requests # noqa: E501
Make multiple requests in parallel to Asana's API. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_batch_request(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The requests to batch together via the Batch API. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: BatchResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_batch_request_with_http_info(body, opts, **kwargs) # noqa: E501
else:
(data) = self.create_batch_request_with_http_info(body, opts, **kwargs) # noqa: E501
return data
def create_batch_request_with_http_info(self, body, opts, **kwargs): # noqa: E501
"""Submit parallel requests # noqa: E501
Make multiple requests in parallel to Asana's API. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_batch_request_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The requests to batch together via the Batch API. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: BatchResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_batch_request" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `create_batch_request`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/batch', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/batch',
"method": 'POST',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/batch', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class BatchAPIApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def create_batch_request(self, body, opts, **kwargs):
'''Submit parallel requests # noqa: E501
Make multiple requests in parallel to Asana's API. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_batch_request(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The requests to batch together via the Batch API. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: BatchResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_batch_request_with_http_info(self, body, opts, **kwargs):
'''Submit parallel requests # noqa: E501
Make multiple requests in parallel to Asana's API. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_batch_request_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The requests to batch together via the Batch API. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: BatchResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
| 4 | 3 | 49 | 5 | 33 | 14 | 3 | 0.46 | 1 | 4 | 2 | 0 | 3 | 1 | 3 | 3 | 156 | 20 | 101 | 17 | 97 | 46 | 44 | 17 | 40 | 6 | 1 | 2 | 10 |
7,527 |
Asana/python-asana
|
Asana_python-asana/asana/api/audit_log_api_api.py
|
asana.api.audit_log_api_api.AuditLogAPIApi
|
class AuditLogAPIApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_audit_log_events(self, workspace_gid, opts, **kwargs): # noqa: E501
"""Get audit log events # noqa: E501
Retrieve the audit log events that have been captured in your domain. This endpoint will return a list of [AuditLogEvent](/reference/audit-log-api) objects, sorted by creation time in ascending order. Note that the Audit Log API captures events from October 8th, 2021 and later. Queries for events before this date will not return results. There are a number of query parameters (below) that can be used to filter the set of [AuditLogEvent](/reference/audit-log-api) objects that are returned in the response. Any combination of query parameters is valid. When no filters are provided, all of the events that have been captured in your domain will match. The list of events will always be [paginated](/docs/pagination). The default limit is 1000 events. The next set of events can be retrieved using the `offset` from the previous response. If there are no events that match the provided filters in your domain, the endpoint will return `null` for the `next_page` field. Querying again with the same filters may return new events if they were captured after the last request. Once a response includes a `next_page` with an `offset`, subsequent requests can be made with the latest `offset` to poll for new events that match the provided filters. *Note: If the filters you provided match events in your domain and `next_page` is present in the response, we will continue to send `next_page` on subsequent requests even when there are no more events that match the filters. This was put in place so that you can implement an audit log stream that will return future events that match these filters. If you are not interested in future events that match the filters you have defined, you can rely on checking empty `data` response for the end of current events that match your filters.* When no `offset` is provided, the response will begin with the oldest events that match the provided filters. It is important to note that [AuditLogEvent](/reference/audit-log-api) objects will be permanently deleted from our systems after 90 days. If you wish to keep a permanent record of these events, we recommend using a SIEM tool to ingest and store these logs. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_audit_log_events(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param datetime start_at: Filter to events created after this time (inclusive).
:param datetime end_at: Filter to events created before this time (exclusive).
:param str event_type: Filter to events of this type. Refer to the [supported audit log events](/docs/audit-log-events#supported-audit-log-events) for a full list of values.
:param str actor_type: Filter to events with an actor of this type. This only needs to be included if querying for actor types without an ID. If `actor_gid` is included, this should be excluded.
:param str actor_gid: Filter to events triggered by the actor with this ID.
:param str resource_gid: Filter to events with this resource ID.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:return: AuditLogEventArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_audit_log_events_with_http_info(workspace_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_audit_log_events_with_http_info(workspace_gid, opts, **kwargs) # noqa: E501
return data
def get_audit_log_events_with_http_info(self, workspace_gid, opts, **kwargs): # noqa: E501
"""Get audit log events # noqa: E501
Retrieve the audit log events that have been captured in your domain. This endpoint will return a list of [AuditLogEvent](/reference/audit-log-api) objects, sorted by creation time in ascending order. Note that the Audit Log API captures events from October 8th, 2021 and later. Queries for events before this date will not return results. There are a number of query parameters (below) that can be used to filter the set of [AuditLogEvent](/reference/audit-log-api) objects that are returned in the response. Any combination of query parameters is valid. When no filters are provided, all of the events that have been captured in your domain will match. The list of events will always be [paginated](/docs/pagination). The default limit is 1000 events. The next set of events can be retrieved using the `offset` from the previous response. If there are no events that match the provided filters in your domain, the endpoint will return `null` for the `next_page` field. Querying again with the same filters may return new events if they were captured after the last request. Once a response includes a `next_page` with an `offset`, subsequent requests can be made with the latest `offset` to poll for new events that match the provided filters. *Note: If the filters you provided match events in your domain and `next_page` is present in the response, we will continue to send `next_page` on subsequent requests even when there are no more events that match the filters. This was put in place so that you can implement an audit log stream that will return future events that match these filters. If you are not interested in future events that match the filters you have defined, you can rely on checking empty `data` response for the end of current events that match your filters.* When no `offset` is provided, the response will begin with the oldest events that match the provided filters. It is important to note that [AuditLogEvent](/reference/audit-log-api) objects will be permanently deleted from our systems after 90 days. If you wish to keep a permanent record of these events, we recommend using a SIEM tool to ingest and store these logs. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_audit_log_events_with_http_info(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param datetime start_at: Filter to events created after this time (inclusive).
:param datetime end_at: Filter to events created before this time (exclusive).
:param str event_type: Filter to events of this type. Refer to the [supported audit log events](/docs/audit-log-events#supported-audit-log-events) for a full list of values.
:param str actor_type: Filter to events with an actor of this type. This only needs to be included if querying for actor types without an ID. If `actor_gid` is included, this should be excluded.
:param str actor_gid: Filter to events triggered by the actor with this ID.
:param str resource_gid: Filter to events with this resource ID.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:return: AuditLogEventArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_audit_log_events" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'workspace_gid' is set
if (workspace_gid is None):
raise ValueError("Missing the required parameter `workspace_gid` when calling `get_audit_log_events`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['workspace_gid'] = workspace_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/workspaces/{workspace_gid}/audit_log_events', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/workspaces/{workspace_gid}/audit_log_events',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/workspaces/{workspace_gid}/audit_log_events', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class AuditLogAPIApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def get_audit_log_events(self, workspace_gid, opts, **kwargs):
'''Get audit log events # noqa: E501
Retrieve the audit log events that have been captured in your domain. This endpoint will return a list of [AuditLogEvent](/reference/audit-log-api) objects, sorted by creation time in ascending order. Note that the Audit Log API captures events from October 8th, 2021 and later. Queries for events before this date will not return results. There are a number of query parameters (below) that can be used to filter the set of [AuditLogEvent](/reference/audit-log-api) objects that are returned in the response. Any combination of query parameters is valid. When no filters are provided, all of the events that have been captured in your domain will match. The list of events will always be [paginated](/docs/pagination). The default limit is 1000 events. The next set of events can be retrieved using the `offset` from the previous response. If there are no events that match the provided filters in your domain, the endpoint will return `null` for the `next_page` field. Querying again with the same filters may return new events if they were captured after the last request. Once a response includes a `next_page` with an `offset`, subsequent requests can be made with the latest `offset` to poll for new events that match the provided filters. *Note: If the filters you provided match events in your domain and `next_page` is present in the response, we will continue to send `next_page` on subsequent requests even when there are no more events that match the filters. This was put in place so that you can implement an audit log stream that will return future events that match these filters. If you are not interested in future events that match the filters you have defined, you can rely on checking empty `data` response for the end of current events that match your filters.* When no `offset` is provided, the response will begin with the oldest events that match the provided filters. It is important to note that [AuditLogEvent](/reference/audit-log-api) objects will be permanently deleted from our systems after 90 days. If you wish to keep a permanent record of these events, we recommend using a SIEM tool to ingest and store these logs. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_audit_log_events(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param datetime start_at: Filter to events created after this time (inclusive).
:param datetime end_at: Filter to events created before this time (exclusive).
:param str event_type: Filter to events of this type. Refer to the [supported audit log events](/docs/audit-log-events#supported-audit-log-events) for a full list of values.
:param str actor_type: Filter to events with an actor of this type. This only needs to be included if querying for actor types without an ID. If `actor_gid` is included, this should be excluded.
:param str actor_gid: Filter to events triggered by the actor with this ID.
:param str resource_gid: Filter to events with this resource ID.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:return: AuditLogEventArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_audit_log_events_with_http_info(self, workspace_gid, opts, **kwargs):
'''Get audit log events # noqa: E501
Retrieve the audit log events that have been captured in your domain. This endpoint will return a list of [AuditLogEvent](/reference/audit-log-api) objects, sorted by creation time in ascending order. Note that the Audit Log API captures events from October 8th, 2021 and later. Queries for events before this date will not return results. There are a number of query parameters (below) that can be used to filter the set of [AuditLogEvent](/reference/audit-log-api) objects that are returned in the response. Any combination of query parameters is valid. When no filters are provided, all of the events that have been captured in your domain will match. The list of events will always be [paginated](/docs/pagination). The default limit is 1000 events. The next set of events can be retrieved using the `offset` from the previous response. If there are no events that match the provided filters in your domain, the endpoint will return `null` for the `next_page` field. Querying again with the same filters may return new events if they were captured after the last request. Once a response includes a `next_page` with an `offset`, subsequent requests can be made with the latest `offset` to poll for new events that match the provided filters. *Note: If the filters you provided match events in your domain and `next_page` is present in the response, we will continue to send `next_page` on subsequent requests even when there are no more events that match the filters. This was put in place so that you can implement an audit log stream that will return future events that match these filters. If you are not interested in future events that match the filters you have defined, you can rely on checking empty `data` response for the end of current events that match your filters.* When no `offset` is provided, the response will begin with the oldest events that match the provided filters. It is important to note that [AuditLogEvent](/reference/audit-log-api) objects will be permanently deleted from our systems after 90 days. If you wish to keep a permanent record of these events, we recommend using a SIEM tool to ingest and store these logs. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_audit_log_events_with_http_info(workspace_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace_gid: Globally unique identifier for the workspace or organization. (required)
:param datetime start_at: Filter to events created after this time (inclusive).
:param datetime end_at: Filter to events created before this time (exclusive).
:param str event_type: Filter to events of this type. Refer to the [supported audit log events](/docs/audit-log-events#supported-audit-log-events) for a full list of values.
:param str actor_type: Filter to events with an actor of this type. This only needs to be included if querying for actor types without an ID. If `actor_gid` is included, this should be excluded.
:param str actor_gid: Filter to events triggered by the actor with this ID.
:param str resource_gid: Filter to events with this resource ID.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:return: AuditLogEventArray
If the method is called asynchronously,
returns the request thread.
'''
pass
| 4 | 3 | 53 | 5 | 33 | 18 | 3 | 0.58 | 1 | 4 | 2 | 0 | 3 | 1 | 3 | 3 | 167 | 19 | 100 | 17 | 96 | 58 | 44 | 17 | 40 | 6 | 1 | 2 | 10 |
7,528 |
Asana/python-asana
|
Asana_python-asana/asana/api/attachments_api.py
|
asana.api.attachments_api.AttachmentsApi
|
class AttachmentsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_attachment_for_object(self, opts, **kwargs): # noqa: E501
"""Upload an attachment # noqa: E501
Upload an attachment. This method uploads an attachment on an object and returns the compact record for the created attachment object. This is possible by either: - Providing the URL of the external resource being attached, or - Downloading the file content first and then uploading it as any other attachment. Note that it is not possible to attach files from third party services such as Dropbox, Box, Vimeo & Google Drive via the API The 100MB size limit on attachments in Asana is enforced on this endpoint. This endpoint expects a multipart/form-data encoded request containing the full contents of the file to be uploaded. Requests made should follow the HTTP/1.1 specification that line terminators are of the form `CRLF` or `\\r\\n` outlined [here](http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01#Basic-Rules) in order for the server to reliably and properly handle the request. For file names that contain non-ASCII characters, the file name should be URL-encoded. For example, a file named `résumé.pdf` should be encoded as `r%C3%A9sum%C3%A9.pdf` and the `filename` parameter in the `Content-Disposition` header should be set to the encoded file name. Below is an example of a cURL request with the `Content-Disposition` header: ``` export ASANA_PAT=\"<YOUR_ASANA_PERSONAL_ACCESS_TOKEN>\" export PARENT_ID=\"<PARENT_GID>\" export ENCODED_NAME=\"r%C3%A9sum%C3%A9.pdf\" curl --location 'https://app.asana.com/api/1.0/attachments' \\ --header 'Content-Type: multipart/form-data' \\ --header 'Accept: application/json' \\ --header \"Authorization: Bearer $ASANA_PAT\" \\ --form \"parent=$PARENT_ID\" \\ --form \"file=@/Users/exampleUser/Downloads/résumé.pdf;headers=\\\"Content-Disposition: form-data; name=\"file\"; filename=\"$ENCODED_NAME.pdf\"; filename*=UTF-8''$ENCODED_NAME.pdf\\\"\" ``` # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_attachment_for_object(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str resource_subtype:
:param str file:
:param str parent:
:param str url:
:param str name:
:param bool connect_to_app:
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_attachment_for_object_with_http_info(opts, **kwargs) # noqa: E501
else:
(data) = self.create_attachment_for_object_with_http_info(opts, **kwargs) # noqa: E501
return data
def create_attachment_for_object_with_http_info(self, opts, **kwargs): # noqa: E501
"""Upload an attachment # noqa: E501
Upload an attachment. This method uploads an attachment on an object and returns the compact record for the created attachment object. This is possible by either: - Providing the URL of the external resource being attached, or - Downloading the file content first and then uploading it as any other attachment. Note that it is not possible to attach files from third party services such as Dropbox, Box, Vimeo & Google Drive via the API The 100MB size limit on attachments in Asana is enforced on this endpoint. This endpoint expects a multipart/form-data encoded request containing the full contents of the file to be uploaded. Requests made should follow the HTTP/1.1 specification that line terminators are of the form `CRLF` or `\\r\\n` outlined [here](http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01#Basic-Rules) in order for the server to reliably and properly handle the request. For file names that contain non-ASCII characters, the file name should be URL-encoded. For example, a file named `résumé.pdf` should be encoded as `r%C3%A9sum%C3%A9.pdf` and the `filename` parameter in the `Content-Disposition` header should be set to the encoded file name. Below is an example of a cURL request with the `Content-Disposition` header: ``` export ASANA_PAT=\"<YOUR_ASANA_PERSONAL_ACCESS_TOKEN>\" export PARENT_ID=\"<PARENT_GID>\" export ENCODED_NAME=\"r%C3%A9sum%C3%A9.pdf\" curl --location 'https://app.asana.com/api/1.0/attachments' \\ --header 'Content-Type: multipart/form-data' \\ --header 'Accept: application/json' \\ --header \"Authorization: Bearer $ASANA_PAT\" \\ --form \"parent=$PARENT_ID\" \\ --form \"file=@/Users/exampleUser/Downloads/résumé.pdf;headers=\\\"Content-Disposition: form-data; name=\"file\"; filename=\"$ENCODED_NAME.pdf\"; filename*=UTF-8''$ENCODED_NAME.pdf\\\"\" ``` # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_attachment_for_object_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str resource_subtype:
:param str file:
:param str parent:
:param str url:
:param str name:
:param bool connect_to_app:
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_attachment_for_object" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
if 'resource_subtype' in opts:
form_params.append(('resource_subtype', opts['resource_subtype'])) # noqa: E501
# Because form params and query params are both provided in the opts method parameter we need to remove the form params from the query params
query_params.pop('resource_subtype')
if 'file' in opts:
local_var_files['file'] = opts['file'] # noqa: E501
# Because form params and query params are both provided in the opts method parameter we need to remove the form params from the query params
query_params.pop('file')
if 'parent' in opts:
form_params.append(('parent', opts['parent'])) # noqa: E501
# Because form params and query params are both provided in the opts method parameter we need to remove the form params from the query params
query_params.pop('parent')
if 'url' in opts:
form_params.append(('url', opts['url'])) # noqa: E501
# Because form params and query params are both provided in the opts method parameter we need to remove the form params from the query params
query_params.pop('url')
if 'name' in opts:
form_params.append(('name', opts['name'])) # noqa: E501
# Because form params and query params are both provided in the opts method parameter we need to remove the form params from the query params
query_params.pop('name')
if 'connect_to_app' in opts:
form_params.append(('connect_to_app', opts['connect_to_app'])) # noqa: E501
# Because form params and query params are both provided in the opts method parameter we need to remove the form params from the query params
query_params.pop('connect_to_app')
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['multipart/form-data']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/attachments', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/attachments', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/attachments', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_attachment(self, attachment_gid, **kwargs): # noqa: E501
"""Delete an attachment # noqa: E501
Deletes a specific, existing attachment. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_attachment(attachment_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str attachment_gid: Globally unique identifier for the attachment. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.delete_attachment_with_http_info(attachment_gid, **kwargs) # noqa: E501
else:
(data) = self.delete_attachment_with_http_info(attachment_gid, **kwargs) # noqa: E501
return data
def delete_attachment_with_http_info(self, attachment_gid, **kwargs): # noqa: E501
"""Delete an attachment # noqa: E501
Deletes a specific, existing attachment. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_attachment_with_http_info(attachment_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str attachment_gid: Globally unique identifier for the attachment. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_attachment" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'attachment_gid' is set
if (attachment_gid is None):
raise ValueError("Missing the required parameter `attachment_gid` when calling `delete_attachment`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['attachment_gid'] = attachment_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/attachments/{attachment_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/attachments/{attachment_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/attachments/{attachment_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_attachment(self, attachment_gid, opts, **kwargs): # noqa: E501
"""Get an attachment # noqa: E501
Get the full record for a single attachment. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_attachment(attachment_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str attachment_gid: Globally unique identifier for the attachment. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_attachment_with_http_info(attachment_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_attachment_with_http_info(attachment_gid, opts, **kwargs) # noqa: E501
return data
def get_attachment_with_http_info(self, attachment_gid, opts, **kwargs): # noqa: E501
"""Get an attachment # noqa: E501
Get the full record for a single attachment. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_attachment_with_http_info(attachment_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str attachment_gid: Globally unique identifier for the attachment. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_attachment" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'attachment_gid' is set
if (attachment_gid is None):
raise ValueError("Missing the required parameter `attachment_gid` when calling `get_attachment`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['attachment_gid'] = attachment_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/attachments/{attachment_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/attachments/{attachment_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/attachments/{attachment_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_attachments_for_object(self, parent, opts, **kwargs): # noqa: E501
"""Get attachments from an object # noqa: E501
Returns the compact records for all attachments on the object. There are three possible `parent` values for this request: `project`, `project_brief`, and `task`. For a project, an attachment refers to a file uploaded to the \"Key resources\" section in the project Overview. For a project brief, an attachment refers to inline files in the project brief itself. For a task, an attachment refers to a file directly associated to that task. Note that within the Asana app, inline images in the task description do not appear in the index of image thumbnails nor as stories in the task. However, requests made to `GET /attachments` for a task will return all of the images in the task, including inline images. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_attachments_for_object(parent, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str parent: Globally unique identifier for object to fetch statuses from. Must be a GID for a `project`, `project_brief`, or `task`. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_attachments_for_object_with_http_info(parent, opts, **kwargs) # noqa: E501
else:
(data) = self.get_attachments_for_object_with_http_info(parent, opts, **kwargs) # noqa: E501
return data
def get_attachments_for_object_with_http_info(self, parent, opts, **kwargs): # noqa: E501
"""Get attachments from an object # noqa: E501
Returns the compact records for all attachments on the object. There are three possible `parent` values for this request: `project`, `project_brief`, and `task`. For a project, an attachment refers to a file uploaded to the \"Key resources\" section in the project Overview. For a project brief, an attachment refers to inline files in the project brief itself. For a task, an attachment refers to a file directly associated to that task. Note that within the Asana app, inline images in the task description do not appear in the index of image thumbnails nor as stories in the task. However, requests made to `GET /attachments` for a task will return all of the images in the task, including inline images. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_attachments_for_object_with_http_info(parent, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str parent: Globally unique identifier for object to fetch statuses from. Must be a GID for a `project`, `project_brief`, or `task`. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_attachments_for_object" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'parent' is set
if (parent is None):
raise ValueError("Missing the required parameter `parent` when calling `get_attachments_for_object`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
query_params['parent'] = parent
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/attachments', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/attachments',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/attachments', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class AttachmentsApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def create_attachment_for_object(self, opts, **kwargs):
'''Upload an attachment # noqa: E501
Upload an attachment. This method uploads an attachment on an object and returns the compact record for the created attachment object. This is possible by either: - Providing the URL of the external resource being attached, or - Downloading the file content first and then uploading it as any other attachment. Note that it is not possible to attach files from third party services such as Dropbox, Box, Vimeo & Google Drive via the API The 100MB size limit on attachments in Asana is enforced on this endpoint. This endpoint expects a multipart/form-data encoded request containing the full contents of the file to be uploaded. Requests made should follow the HTTP/1.1 specification that line terminators are of the form `CRLF` or `\r\n` outlined [here](http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01#Basic-Rules) in order for the server to reliably and properly handle the request. For file names that contain non-ASCII characters, the file name should be URL-encoded. For example, a file named `résumé.pdf` should be encoded as `r%C3%A9sum%C3%A9.pdf` and the `filename` parameter in the `Content-Disposition` header should be set to the encoded file name. Below is an example of a cURL request with the `Content-Disposition` header: ``` export ASANA_PAT="<YOUR_ASANA_PERSONAL_ACCESS_TOKEN>" export PARENT_ID="<PARENT_GID>" export ENCODED_NAME="r%C3%A9sum%C3%A9.pdf" curl --location 'https://app.asana.com/api/1.0/attachments' \ --header 'Content-Type: multipart/form-data' \ --header 'Accept: application/json' \ --header "Authorization: Bearer $ASANA_PAT" \ --form "parent=$PARENT_ID" \ --form "file=@/Users/exampleUser/Downloads/résumé.pdf;headers=\"Content-Disposition: form-data; name="file"; filename="$ENCODED_NAME.pdf"; filename*=UTF-8''$ENCODED_NAME.pdf\"" ``` # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_attachment_for_object(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str resource_subtype:
:param str file:
:param str parent:
:param str url:
:param str name:
:param bool connect_to_app:
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_attachment_for_object_with_http_info(self, opts, **kwargs):
'''Upload an attachment # noqa: E501
Upload an attachment. This method uploads an attachment on an object and returns the compact record for the created attachment object. This is possible by either: - Providing the URL of the external resource being attached, or - Downloading the file content first and then uploading it as any other attachment. Note that it is not possible to attach files from third party services such as Dropbox, Box, Vimeo & Google Drive via the API The 100MB size limit on attachments in Asana is enforced on this endpoint. This endpoint expects a multipart/form-data encoded request containing the full contents of the file to be uploaded. Requests made should follow the HTTP/1.1 specification that line terminators are of the form `CRLF` or `\r\n` outlined [here](http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01#Basic-Rules) in order for the server to reliably and properly handle the request. For file names that contain non-ASCII characters, the file name should be URL-encoded. For example, a file named `résumé.pdf` should be encoded as `r%C3%A9sum%C3%A9.pdf` and the `filename` parameter in the `Content-Disposition` header should be set to the encoded file name. Below is an example of a cURL request with the `Content-Disposition` header: ``` export ASANA_PAT="<YOUR_ASANA_PERSONAL_ACCESS_TOKEN>" export PARENT_ID="<PARENT_GID>" export ENCODED_NAME="r%C3%A9sum%C3%A9.pdf" curl --location 'https://app.asana.com/api/1.0/attachments' \ --header 'Content-Type: multipart/form-data' \ --header 'Accept: application/json' \ --header "Authorization: Bearer $ASANA_PAT" \ --form "parent=$PARENT_ID" \ --form "file=@/Users/exampleUser/Downloads/résumé.pdf;headers=\"Content-Disposition: form-data; name="file"; filename="$ENCODED_NAME.pdf"; filename*=UTF-8''$ENCODED_NAME.pdf\"" ``` # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_attachment_for_object_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str resource_subtype:
:param str file:
:param str parent:
:param str url:
:param str name:
:param bool connect_to_app:
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_attachment(self, attachment_gid, **kwargs):
'''Delete an attachment # noqa: E501
Deletes a specific, existing attachment. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_attachment(attachment_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str attachment_gid: Globally unique identifier for the attachment. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_attachment_with_http_info(self, attachment_gid, **kwargs):
'''Delete an attachment # noqa: E501
Deletes a specific, existing attachment. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_attachment_with_http_info(attachment_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str attachment_gid: Globally unique identifier for the attachment. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_attachment(self, attachment_gid, opts, **kwargs):
'''Get an attachment # noqa: E501
Get the full record for a single attachment. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_attachment(attachment_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str attachment_gid: Globally unique identifier for the attachment. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_attachment_with_http_info(self, attachment_gid, opts, **kwargs):
'''Get an attachment # noqa: E501
Get the full record for a single attachment. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_attachment_with_http_info(attachment_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str attachment_gid: Globally unique identifier for the attachment. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_attachments_for_object(self, parent, opts, **kwargs):
'''Get attachments from an object # noqa: E501
Returns the compact records for all attachments on the object. There are three possible `parent` values for this request: `project`, `project_brief`, and `task`. For a project, an attachment refers to a file uploaded to the "Key resources" section in the project Overview. For a project brief, an attachment refers to inline files in the project brief itself. For a task, an attachment refers to a file directly associated to that task. Note that within the Asana app, inline images in the task description do not appear in the index of image thumbnails nor as stories in the task. However, requests made to `GET /attachments` for a task will return all of the images in the task, including inline images. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_attachments_for_object(parent, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str parent: Globally unique identifier for object to fetch statuses from. Must be a GID for a `project`, `project_brief`, or `task`. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_attachments_for_object_with_http_info(self, parent, opts, **kwargs):
'''Get attachments from an object # noqa: E501
Returns the compact records for all attachments on the object. There are three possible `parent` values for this request: `project`, `project_brief`, and `task`. For a project, an attachment refers to a file uploaded to the "Key resources" section in the project Overview. For a project brief, an attachment refers to inline files in the project brief itself. For a task, an attachment refers to a file directly associated to that task. Note that within the Asana app, inline images in the task description do not appear in the index of image thumbnails nor as stories in the task. However, requests made to `GET /attachments` for a task will return all of the images in the task, including inline images. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_attachments_for_object_with_http_info(parent, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str parent: Globally unique identifier for object to fetch statuses from. Must be a GID for a `project`, `project_brief`, or `task`. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AttachmentResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
| 10 | 9 | 66 | 7 | 43 | 21 | 5 | 0.48 | 1 | 4 | 2 | 0 | 9 | 1 | 9 | 9 | 611 | 77 | 392 | 62 | 382 | 190 | 182 | 62 | 172 | 13 | 1 | 2 | 45 |
7,529 |
Asana/python-asana
|
Asana_python-asana/asana/api/allocations_api.py
|
asana.api.allocations_api.AllocationsApi
|
class AllocationsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_allocation(self, body, opts, **kwargs): # noqa: E501
"""Create an allocation # noqa: E501
Creates a new allocation. Returns the full record of the newly created allocation. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_allocation(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The allocation to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_allocation_with_http_info(body, opts, **kwargs) # noqa: E501
else:
(data) = self.create_allocation_with_http_info(body, opts, **kwargs) # noqa: E501
return data
def create_allocation_with_http_info(self, body, opts, **kwargs): # noqa: E501
"""Create an allocation # noqa: E501
Creates a new allocation. Returns the full record of the newly created allocation. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_allocation_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The allocation to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_allocation" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `create_allocation`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/allocations', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/allocations', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/allocations', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_allocation(self, allocation_gid, **kwargs): # noqa: E501
"""Delete an allocation # noqa: E501
A specific, existing allocation can be deleted by making a DELETE request on the URL for that allocation. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_allocation(allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.delete_allocation_with_http_info(allocation_gid, **kwargs) # noqa: E501
else:
(data) = self.delete_allocation_with_http_info(allocation_gid, **kwargs) # noqa: E501
return data
def delete_allocation_with_http_info(self, allocation_gid, **kwargs): # noqa: E501
"""Delete an allocation # noqa: E501
A specific, existing allocation can be deleted by making a DELETE request on the URL for that allocation. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_allocation_with_http_info(allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_allocation" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'allocation_gid' is set
if (allocation_gid is None):
raise ValueError("Missing the required parameter `allocation_gid` when calling `delete_allocation`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['allocation_gid'] = allocation_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/allocations/{allocation_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/allocations/{allocation_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/allocations/{allocation_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_allocation(self, allocation_gid, opts, **kwargs): # noqa: E501
"""Get an allocation # noqa: E501
Returns the complete allocation record for a single allocation. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_allocation(allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_allocation_with_http_info(allocation_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_allocation_with_http_info(allocation_gid, opts, **kwargs) # noqa: E501
return data
def get_allocation_with_http_info(self, allocation_gid, opts, **kwargs): # noqa: E501
"""Get an allocation # noqa: E501
Returns the complete allocation record for a single allocation. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_allocation_with_http_info(allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_allocation" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'allocation_gid' is set
if (allocation_gid is None):
raise ValueError("Missing the required parameter `allocation_gid` when calling `get_allocation`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['allocation_gid'] = allocation_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/allocations/{allocation_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/allocations/{allocation_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/allocations/{allocation_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_allocations(self, opts, **kwargs): # noqa: E501
"""Get multiple allocations # noqa: E501
Returns a list of allocations filtered to a specific project, user or placeholder. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_allocations(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str parent: Globally unique identifier for the project to filter allocations by.
:param str assignee: Globally unique identifier for the user or placeholder the allocation is assigned to.
:param str workspace: Globally unique identifier for the workspace.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_allocations_with_http_info(opts, **kwargs) # noqa: E501
else:
(data) = self.get_allocations_with_http_info(opts, **kwargs) # noqa: E501
return data
def get_allocations_with_http_info(self, opts, **kwargs): # noqa: E501
"""Get multiple allocations # noqa: E501
Returns a list of allocations filtered to a specific project, user or placeholder. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_allocations_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str parent: Globally unique identifier for the project to filter allocations by.
:param str assignee: Globally unique identifier for the user or placeholder the allocation is assigned to.
:param str workspace: Globally unique identifier for the workspace.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_allocations" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/allocations', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/allocations',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/allocations', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_allocation(self, body, allocation_gid, opts, **kwargs): # noqa: E501
"""Update an allocation # noqa: E501
An existing allocation can be updated by making a PUT request on the URL for that allocation. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated allocation record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_allocation(body, allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the allocation. (required)
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.update_allocation_with_http_info(body, allocation_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.update_allocation_with_http_info(body, allocation_gid, opts, **kwargs) # noqa: E501
return data
def update_allocation_with_http_info(self, body, allocation_gid, opts, **kwargs): # noqa: E501
"""Update an allocation # noqa: E501
An existing allocation can be updated by making a PUT request on the URL for that allocation. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated allocation record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_allocation_with_http_info(body, allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the allocation. (required)
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_allocation" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `update_allocation`") # noqa: E501
# verify the required parameter 'allocation_gid' is set
if (allocation_gid is None):
raise ValueError("Missing the required parameter `allocation_gid` when calling `update_allocation`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['allocation_gid'] = allocation_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/allocations/{allocation_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/allocations/{allocation_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/allocations/{allocation_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class AllocationsApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def create_allocation(self, body, opts, **kwargs):
'''Create an allocation # noqa: E501
Creates a new allocation. Returns the full record of the newly created allocation. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_allocation(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The allocation to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_allocation_with_http_info(self, body, opts, **kwargs):
'''Create an allocation # noqa: E501
Creates a new allocation. Returns the full record of the newly created allocation. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_allocation_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The allocation to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_allocation(self, allocation_gid, **kwargs):
'''Delete an allocation # noqa: E501
A specific, existing allocation can be deleted by making a DELETE request on the URL for that allocation. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_allocation(allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_allocation_with_http_info(self, allocation_gid, **kwargs):
'''Delete an allocation # noqa: E501
A specific, existing allocation can be deleted by making a DELETE request on the URL for that allocation. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_allocation_with_http_info(allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_allocation(self, allocation_gid, opts, **kwargs):
'''Get an allocation # noqa: E501
Returns the complete allocation record for a single allocation. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_allocation(allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_allocation_with_http_info(self, allocation_gid, opts, **kwargs):
'''Get an allocation # noqa: E501
Returns the complete allocation record for a single allocation. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_allocation_with_http_info(allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_allocations(self, opts, **kwargs):
'''Get multiple allocations # noqa: E501
Returns a list of allocations filtered to a specific project, user or placeholder. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_allocations(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str parent: Globally unique identifier for the project to filter allocations by.
:param str assignee: Globally unique identifier for the user or placeholder the allocation is assigned to.
:param str workspace: Globally unique identifier for the workspace.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_allocations_with_http_info(self, opts, **kwargs):
'''Get multiple allocations # noqa: E501
Returns a list of allocations filtered to a specific project, user or placeholder. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_allocations_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str parent: Globally unique identifier for the project to filter allocations by.
:param str assignee: Globally unique identifier for the user or placeholder the allocation is assigned to.
:param str workspace: Globally unique identifier for the workspace.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_allocation(self, body, allocation_gid, opts, **kwargs):
'''Update an allocation # noqa: E501
An existing allocation can be updated by making a PUT request on the URL for that allocation. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated allocation record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_allocation(body, allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the allocation. (required)
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_allocation_with_http_info(self, body, allocation_gid, opts, **kwargs):
'''Update an allocation # noqa: E501
An existing allocation can be updated by making a PUT request on the URL for that allocation. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated allocation record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_allocation_with_http_info(body, allocation_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the allocation. (required)
:param str allocation_gid: Globally unique identifier for the allocation. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: AllocationResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
| 12 | 11 | 64 | 7 | 43 | 20 | 5 | 0.47 | 1 | 4 | 2 | 0 | 11 | 1 | 11 | 11 | 722 | 89 | 469 | 77 | 457 | 220 | 207 | 77 | 195 | 9 | 1 | 2 | 50 |
7,530 |
Asana/python-asana
|
Asana_python-asana/asana/api/goals_api.py
|
asana.api.goals_api.GoalsApi
|
class GoalsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def add_followers(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Add a collaborator to a goal # noqa: E501
Adds followers to a goal. Returns the goal the followers were added to. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_followers(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The followers to be added as collaborators (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.add_followers_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.add_followers_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
return data
def add_followers_with_http_info(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Add a collaborator to a goal # noqa: E501
Adds followers to a goal. Returns the goal the followers were added to. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_followers_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The followers to be added as collaborators (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_followers" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `add_followers`") # noqa: E501
# verify the required parameter 'goal_gid' is set
if (goal_gid is None):
raise ValueError("Missing the required parameter `goal_gid` when calling `add_followers`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_gid'] = goal_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals/{goal_gid}/addFollowers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goals/{goal_gid}/addFollowers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goals/{goal_gid}/addFollowers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_goal(self, body, opts, **kwargs): # noqa: E501
"""Create a goal # noqa: E501
Creates a new goal in a workspace or team. Returns the full record of the newly created goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_goal(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The goal to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_goal_with_http_info(body, opts, **kwargs) # noqa: E501
else:
(data) = self.create_goal_with_http_info(body, opts, **kwargs) # noqa: E501
return data
def create_goal_with_http_info(self, body, opts, **kwargs): # noqa: E501
"""Create a goal # noqa: E501
Creates a new goal in a workspace or team. Returns the full record of the newly created goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_goal_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The goal to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_goal" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `create_goal`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goals', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goals', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_goal_metric(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Create a goal metric # noqa: E501
Creates and adds a goal metric to a specified goal. Note that this replaces an existing goal metric if one already exists. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_goal_metric(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The goal metric to create. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_goal_metric_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.create_goal_metric_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
return data
def create_goal_metric_with_http_info(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Create a goal metric # noqa: E501
Creates and adds a goal metric to a specified goal. Note that this replaces an existing goal metric if one already exists. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_goal_metric_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The goal metric to create. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_goal_metric" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `create_goal_metric`") # noqa: E501
# verify the required parameter 'goal_gid' is set
if (goal_gid is None):
raise ValueError("Missing the required parameter `goal_gid` when calling `create_goal_metric`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_gid'] = goal_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals/{goal_gid}/setMetric', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goals/{goal_gid}/setMetric', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goals/{goal_gid}/setMetric', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_goal(self, goal_gid, **kwargs): # noqa: E501
"""Delete a goal # noqa: E501
A specific, existing goal can be deleted by making a DELETE request on the URL for that goal. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_goal(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.delete_goal_with_http_info(goal_gid, **kwargs) # noqa: E501
else:
(data) = self.delete_goal_with_http_info(goal_gid, **kwargs) # noqa: E501
return data
def delete_goal_with_http_info(self, goal_gid, **kwargs): # noqa: E501
"""Delete a goal # noqa: E501
A specific, existing goal can be deleted by making a DELETE request on the URL for that goal. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_goal_with_http_info(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_goal" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'goal_gid' is set
if (goal_gid is None):
raise ValueError("Missing the required parameter `goal_gid` when calling `delete_goal`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_gid'] = goal_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals/{goal_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goals/{goal_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goals/{goal_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_goal(self, goal_gid, opts, **kwargs): # noqa: E501
"""Get a goal # noqa: E501
Returns the complete goal record for a single goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_goal_with_http_info(goal_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_goal_with_http_info(goal_gid, opts, **kwargs) # noqa: E501
return data
def get_goal_with_http_info(self, goal_gid, opts, **kwargs): # noqa: E501
"""Get a goal # noqa: E501
Returns the complete goal record for a single goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal_with_http_info(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_goal" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'goal_gid' is set
if (goal_gid is None):
raise ValueError("Missing the required parameter `goal_gid` when calling `get_goal`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_gid'] = goal_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals/{goal_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goals/{goal_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goals/{goal_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_goals(self, opts, **kwargs): # noqa: E501
"""Get goals # noqa: E501
Returns compact goal records. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goals(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio: Globally unique identifier for supporting portfolio.
:param str project: Globally unique identifier for supporting project.
:param str task: Globally unique identifier for supporting task.
:param bool is_workspace_level: Filter to goals with is_workspace_level set to query value. Must be used with the workspace parameter.
:param str team: Globally unique identifier for the team.
:param str workspace: Globally unique identifier for the workspace.
:param list[str] time_periods: Globally unique identifiers for the time periods.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_goals_with_http_info(opts, **kwargs) # noqa: E501
else:
(data) = self.get_goals_with_http_info(opts, **kwargs) # noqa: E501
return data
def get_goals_with_http_info(self, opts, **kwargs): # noqa: E501
"""Get goals # noqa: E501
Returns compact goal records. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goals_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio: Globally unique identifier for supporting portfolio.
:param str project: Globally unique identifier for supporting project.
:param str task: Globally unique identifier for supporting task.
:param bool is_workspace_level: Filter to goals with is_workspace_level set to query value. Must be used with the workspace parameter.
:param str team: Globally unique identifier for the team.
:param str workspace: Globally unique identifier for the workspace.
:param list[str] time_periods: Globally unique identifiers for the time periods.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_goals" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/goals',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/goals', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_parent_goals_for_goal(self, goal_gid, opts, **kwargs): # noqa: E501
"""Get parent goals from a goal # noqa: E501
Returns a compact representation of all of the parent goals of a goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_parent_goals_for_goal(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_parent_goals_for_goal_with_http_info(goal_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_parent_goals_for_goal_with_http_info(goal_gid, opts, **kwargs) # noqa: E501
return data
def get_parent_goals_for_goal_with_http_info(self, goal_gid, opts, **kwargs): # noqa: E501
"""Get parent goals from a goal # noqa: E501
Returns a compact representation of all of the parent goals of a goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_parent_goals_for_goal_with_http_info(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_parent_goals_for_goal" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'goal_gid' is set
if (goal_gid is None):
raise ValueError("Missing the required parameter `goal_gid` when calling `get_parent_goals_for_goal`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_gid'] = goal_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals/{goal_gid}/parentGoals', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/goals/{goal_gid}/parentGoals',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/goals/{goal_gid}/parentGoals', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def remove_followers(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Remove a collaborator from a goal # noqa: E501
Removes followers from a goal. Returns the goal the followers were removed from. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_followers(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The followers to be removed as collaborators (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.remove_followers_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.remove_followers_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
return data
def remove_followers_with_http_info(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Remove a collaborator from a goal # noqa: E501
Removes followers from a goal. Returns the goal the followers were removed from. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_followers_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The followers to be removed as collaborators (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_followers" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `remove_followers`") # noqa: E501
# verify the required parameter 'goal_gid' is set
if (goal_gid is None):
raise ValueError("Missing the required parameter `goal_gid` when calling `remove_followers`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_gid'] = goal_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals/{goal_gid}/removeFollowers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goals/{goal_gid}/removeFollowers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goals/{goal_gid}/removeFollowers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_goal(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Update a goal # noqa: E501
An existing goal can be updated by making a PUT request on the URL for that goal. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.update_goal_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.update_goal_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
return data
def update_goal_with_http_info(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Update a goal # noqa: E501
An existing goal can be updated by making a PUT request on the URL for that goal. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_goal" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `update_goal`") # noqa: E501
# verify the required parameter 'goal_gid' is set
if (goal_gid is None):
raise ValueError("Missing the required parameter `goal_gid` when calling `update_goal`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_gid'] = goal_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals/{goal_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goals/{goal_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goals/{goal_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_goal_metric(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Update a goal metric # noqa: E501
Updates a goal's existing metric's `current_number_value` if one exists, otherwise responds with a 400 status code. Returns the complete updated goal metric record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal_metric(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal metric. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.update_goal_metric_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.update_goal_metric_with_http_info(body, goal_gid, opts, **kwargs) # noqa: E501
return data
def update_goal_metric_with_http_info(self, body, goal_gid, opts, **kwargs): # noqa: E501
"""Update a goal metric # noqa: E501
Updates a goal's existing metric's `current_number_value` if one exists, otherwise responds with a 400 status code. Returns the complete updated goal metric record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal_metric_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal metric. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_goal_metric" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `update_goal_metric`") # noqa: E501
# verify the required parameter 'goal_gid' is set
if (goal_gid is None):
raise ValueError("Missing the required parameter `goal_gid` when calling `update_goal_metric`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['goal_gid'] = goal_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/goals/{goal_gid}/setMetricCurrentValue', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/goals/{goal_gid}/setMetricCurrentValue', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/goals/{goal_gid}/setMetricCurrentValue', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class GoalsApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def add_followers(self, body, goal_gid, opts, **kwargs):
'''Add a collaborator to a goal # noqa: E501
Adds followers to a goal. Returns the goal the followers were added to. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_followers(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The followers to be added as collaborators (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def add_followers_with_http_info(self, body, goal_gid, opts, **kwargs):
'''Add a collaborator to a goal # noqa: E501
Adds followers to a goal. Returns the goal the followers were added to. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_followers_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The followers to be added as collaborators (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_goal(self, body, opts, **kwargs):
'''Create a goal # noqa: E501
Creates a new goal in a workspace or team. Returns the full record of the newly created goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_goal(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The goal to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_goal_with_http_info(self, body, opts, **kwargs):
'''Create a goal # noqa: E501
Creates a new goal in a workspace or team. Returns the full record of the newly created goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_goal_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The goal to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_goal_metric(self, body, goal_gid, opts, **kwargs):
'''Create a goal metric # noqa: E501
Creates and adds a goal metric to a specified goal. Note that this replaces an existing goal metric if one already exists. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_goal_metric(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The goal metric to create. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_goal_metric_with_http_info(self, body, goal_gid, opts, **kwargs):
'''Create a goal metric # noqa: E501
Creates and adds a goal metric to a specified goal. Note that this replaces an existing goal metric if one already exists. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_goal_metric_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The goal metric to create. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_goal(self, goal_gid, **kwargs):
'''Delete a goal # noqa: E501
A specific, existing goal can be deleted by making a DELETE request on the URL for that goal. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_goal(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_goal_with_http_info(self, goal_gid, **kwargs):
'''Delete a goal # noqa: E501
A specific, existing goal can be deleted by making a DELETE request on the URL for that goal. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_goal_with_http_info(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_goal(self, goal_gid, opts, **kwargs):
'''Get a goal # noqa: E501
Returns the complete goal record for a single goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_goal_with_http_info(self, goal_gid, opts, **kwargs):
'''Get a goal # noqa: E501
Returns the complete goal record for a single goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goal_with_http_info(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_goals(self, opts, **kwargs):
'''Get goals # noqa: E501
Returns compact goal records. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goals(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio: Globally unique identifier for supporting portfolio.
:param str project: Globally unique identifier for supporting project.
:param str task: Globally unique identifier for supporting task.
:param bool is_workspace_level: Filter to goals with is_workspace_level set to query value. Must be used with the workspace parameter.
:param str team: Globally unique identifier for the team.
:param str workspace: Globally unique identifier for the workspace.
:param list[str] time_periods: Globally unique identifiers for the time periods.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_goals_with_http_info(self, opts, **kwargs):
'''Get goals # noqa: E501
Returns compact goal records. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_goals_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio: Globally unique identifier for supporting portfolio.
:param str project: Globally unique identifier for supporting project.
:param str task: Globally unique identifier for supporting task.
:param bool is_workspace_level: Filter to goals with is_workspace_level set to query value. Must be used with the workspace parameter.
:param str team: Globally unique identifier for the team.
:param str workspace: Globally unique identifier for the workspace.
:param list[str] time_periods: Globally unique identifiers for the time periods.
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_parent_goals_for_goal(self, goal_gid, opts, **kwargs):
'''Get parent goals from a goal # noqa: E501
Returns a compact representation of all of the parent goals of a goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_parent_goals_for_goal(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_parent_goals_for_goal_with_http_info(self, goal_gid, opts, **kwargs):
'''Get parent goals from a goal # noqa: E501
Returns a compact representation of all of the parent goals of a goal. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_parent_goals_for_goal_with_http_info(goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def remove_followers(self, body, goal_gid, opts, **kwargs):
'''Remove a collaborator from a goal # noqa: E501
Removes followers from a goal. Returns the goal the followers were removed from. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_followers(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The followers to be removed as collaborators (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def remove_followers_with_http_info(self, body, goal_gid, opts, **kwargs):
'''Remove a collaborator from a goal # noqa: E501
Removes followers from a goal. Returns the goal the followers were removed from. Each goal can be associated with zero or more followers in the system. Requests to add/remove followers, if successful, will return the complete updated goal record, described above. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_followers_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The followers to be removed as collaborators (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_goal(self, body, goal_gid, opts, **kwargs):
'''Update a goal # noqa: E501
An existing goal can be updated by making a PUT request on the URL for that goal. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_goal_with_http_info(self, body, goal_gid, opts, **kwargs):
'''Update a goal # noqa: E501
An existing goal can be updated by making a PUT request on the URL for that goal. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated goal record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_goal_metric(self, body, goal_gid, opts, **kwargs):
'''Update a goal metric # noqa: E501
Updates a goal's existing metric's `current_number_value` if one exists, otherwise responds with a 400 status code. Returns the complete updated goal metric record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal_metric(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal metric. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_goal_metric_with_http_info(self, body, goal_gid, opts, **kwargs):
'''Update a goal metric # noqa: E501
Updates a goal's existing metric's `current_number_value` if one exists, otherwise responds with a 400 status code. Returns the complete updated goal metric record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_goal_metric_with_http_info(body, goal_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the goal metric. (required)
:param str goal_gid: Globally unique identifier for the goal. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: GoalResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
| 22 | 21 | 68 | 7 | 45 | 22 | 5 | 0.49 | 1 | 4 | 2 | 0 | 21 | 1 | 21 | 21 | 1,464 | 178 | 948 | 151 | 926 | 460 | 422 | 151 | 400 | 9 | 1 | 2 | 102 |
7,531 |
Asana/python-asana
|
Asana_python-asana/test/test_sections_api.py
|
test.test_sections_api.TestSectionsApi
|
class TestSectionsApi(unittest.TestCase):
"""SectionsApi unit test stubs"""
def setUp(self):
self.api = SectionsApi() # noqa: E501
def tearDown(self):
pass
def test_add_task_for_section(self):
"""Test case for add_task_for_section
Add task to section # noqa: E501
"""
pass
def test_create_section_for_project(self):
"""Test case for create_section_for_project
Create a section in a project # noqa: E501
"""
pass
def test_delete_section(self):
"""Test case for delete_section
Delete a section # noqa: E501
"""
pass
def test_get_section(self):
"""Test case for get_section
Get a section # noqa: E501
"""
pass
def test_get_sections_for_project(self):
"""Test case for get_sections_for_project
Get sections in a project # noqa: E501
"""
pass
def test_insert_section_for_project(self):
"""Test case for insert_section_for_project
Move or Insert sections # noqa: E501
"""
pass
def test_update_section(self):
"""Test case for update_section
Update a section # noqa: E501
"""
pass
|
class TestSectionsApi(unittest.TestCase):
'''SectionsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_add_task_for_section(self):
'''Test case for add_task_for_section
Add task to section # noqa: E501
'''
pass
def test_create_section_for_project(self):
'''Test case for create_section_for_project
Create a section in a project # noqa: E501
'''
pass
def test_delete_section(self):
'''Test case for delete_section
Delete a section # noqa: E501
'''
pass
def test_get_section(self):
'''Test case for get_section
Get a section # noqa: E501
'''
pass
def test_get_sections_for_project(self):
'''Test case for get_sections_for_project
Get sections in a project # noqa: E501
'''
pass
def test_insert_section_for_project(self):
'''Test case for insert_section_for_project
Move or Insert sections # noqa: E501
'''
pass
def test_update_section(self):
'''Test case for update_section
Update a section # noqa: E501
'''
pass
| 10 | 8 | 5 | 1 | 2 | 2 | 1 | 1.21 | 1 | 1 | 1 | 0 | 9 | 1 | 9 | 81 | 57 | 16 | 19 | 11 | 9 | 23 | 19 | 11 | 9 | 1 | 2 | 0 | 9 |
7,532 |
Asana/python-asana
|
Asana_python-asana/test/test_stories_api.py
|
test.test_stories_api.TestStoriesApi
|
class TestStoriesApi(unittest.TestCase):
"""StoriesApi unit test stubs"""
def setUp(self):
self.api = StoriesApi() # noqa: E501
def tearDown(self):
pass
def test_create_story_for_task(self):
"""Test case for create_story_for_task
Create a story on a task # noqa: E501
"""
pass
def test_delete_story(self):
"""Test case for delete_story
Delete a story # noqa: E501
"""
pass
def test_get_stories_for_task(self):
"""Test case for get_stories_for_task
Get stories from a task # noqa: E501
"""
pass
def test_get_story(self):
"""Test case for get_story
Get a story # noqa: E501
"""
pass
def test_update_story(self):
"""Test case for update_story
Update a story # noqa: E501
"""
pass
|
class TestStoriesApi(unittest.TestCase):
'''StoriesApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_story_for_task(self):
'''Test case for create_story_for_task
Create a story on a task # noqa: E501
'''
pass
def test_delete_story(self):
'''Test case for delete_story
Delete a story # noqa: E501
'''
pass
def test_get_stories_for_task(self):
'''Test case for get_stories_for_task
Get stories from a task # noqa: E501
'''
pass
def test_get_story(self):
'''Test case for get_story
Get a story # noqa: E501
'''
pass
def test_update_story(self):
'''Test case for update_story
Update a story # noqa: E501
'''
pass
| 8 | 6 | 5 | 1 | 2 | 2 | 1 | 1.13 | 1 | 1 | 1 | 0 | 7 | 1 | 7 | 79 | 43 | 12 | 15 | 9 | 7 | 17 | 15 | 9 | 7 | 1 | 2 | 0 | 7 |
7,533 |
Asana/python-asana
|
Asana_python-asana/test/test_tags_api.py
|
test.test_tags_api.TestTagsApi
|
class TestTagsApi(unittest.TestCase):
"""TagsApi unit test stubs"""
def setUp(self):
self.api = TagsApi() # noqa: E501
def tearDown(self):
pass
def test_create_tag(self):
"""Test case for create_tag
Create a tag # noqa: E501
"""
pass
def test_create_tag_for_workspace(self):
"""Test case for create_tag_for_workspace
Create a tag in a workspace # noqa: E501
"""
pass
def test_delete_tag(self):
"""Test case for delete_tag
Delete a tag # noqa: E501
"""
pass
def test_get_tag(self):
"""Test case for get_tag
Get a tag # noqa: E501
"""
pass
def test_get_tags(self):
"""Test case for get_tags
Get multiple tags # noqa: E501
"""
pass
def test_get_tags_for_task(self):
"""Test case for get_tags_for_task
Get a task's tags # noqa: E501
"""
pass
def test_get_tags_for_workspace(self):
"""Test case for get_tags_for_workspace
Get tags in a workspace # noqa: E501
"""
pass
def test_update_tag(self):
"""Test case for update_tag
Update a tag # noqa: E501
"""
pass
|
class TestTagsApi(unittest.TestCase):
'''TagsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_tag(self):
'''Test case for create_tag
Create a tag # noqa: E501
'''
pass
def test_create_tag_for_workspace(self):
'''Test case for create_tag_for_workspace
Create a tag in a workspace # noqa: E501
'''
pass
def test_delete_tag(self):
'''Test case for delete_tag
Delete a tag # noqa: E501
'''
pass
def test_get_tag(self):
'''Test case for get_tag
Get a tag # noqa: E501
'''
pass
def test_get_tags(self):
'''Test case for get_tags
Get multiple tags # noqa: E501
'''
pass
def test_get_tags_for_task(self):
'''Test case for get_tags_for_task
Get a task's tags # noqa: E501
'''
pass
def test_get_tags_for_workspace(self):
'''Test case for get_tags_for_workspace
Get tags in a workspace # noqa: E501
'''
pass
def test_update_tag(self):
'''Test case for update_tag
Update a tag # noqa: E501
'''
pass
| 11 | 9 | 5 | 1 | 2 | 3 | 1 | 1.24 | 1 | 1 | 1 | 0 | 10 | 1 | 10 | 82 | 64 | 18 | 21 | 12 | 10 | 26 | 21 | 12 | 10 | 1 | 2 | 0 | 10 |
7,534 |
Asana/python-asana
|
Asana_python-asana/test/test_tasks_api.py
|
test.test_tasks_api.TestTasksApi
|
class TestTasksApi(unittest.TestCase):
"""TasksApi unit test stubs"""
def setUp(self):
self.api = TasksApi() # noqa: E501
def tearDown(self):
pass
def test_add_dependencies_for_task(self):
"""Test case for add_dependencies_for_task
Set dependencies for a task # noqa: E501
"""
pass
def test_add_dependents_for_task(self):
"""Test case for add_dependents_for_task
Set dependents for a task # noqa: E501
"""
pass
def test_add_followers_for_task(self):
"""Test case for add_followers_for_task
Add followers to a task # noqa: E501
"""
pass
def test_add_project_for_task(self):
"""Test case for add_project_for_task
Add a project to a task # noqa: E501
"""
pass
def test_add_tag_for_task(self):
"""Test case for add_tag_for_task
Add a tag to a task # noqa: E501
"""
pass
def test_create_subtask_for_task(self):
"""Test case for create_subtask_for_task
Create a subtask # noqa: E501
"""
pass
def test_create_task(self):
"""Test case for create_task
Create a task # noqa: E501
"""
pass
def test_delete_task(self):
"""Test case for delete_task
Delete a task # noqa: E501
"""
pass
def test_duplicate_task(self):
"""Test case for duplicate_task
Duplicate a task # noqa: E501
"""
pass
def test_get_dependencies_for_task(self):
"""Test case for get_dependencies_for_task
Get dependencies from a task # noqa: E501
"""
pass
def test_get_dependents_for_task(self):
"""Test case for get_dependents_for_task
Get dependents from a task # noqa: E501
"""
pass
def test_get_subtasks_for_task(self):
"""Test case for get_subtasks_for_task
Get subtasks from a task # noqa: E501
"""
pass
def test_get_task(self):
"""Test case for get_task
Get a task # noqa: E501
"""
pass
def test_get_tasks(self):
"""Test case for get_tasks
Get multiple tasks # noqa: E501
"""
pass
def test_get_tasks_for_project(self):
"""Test case for get_tasks_for_project
Get tasks from a project # noqa: E501
"""
pass
def test_get_tasks_for_section(self):
"""Test case for get_tasks_for_section
Get tasks from a section # noqa: E501
"""
pass
def test_get_tasks_for_tag(self):
"""Test case for get_tasks_for_tag
Get tasks from a tag # noqa: E501
"""
pass
def test_get_tasks_for_user_task_list(self):
"""Test case for get_tasks_for_user_task_list
Get tasks from a user task list # noqa: E501
"""
pass
def test_remove_dependencies_for_task(self):
"""Test case for remove_dependencies_for_task
Unlink dependencies from a task # noqa: E501
"""
pass
def test_remove_dependents_for_task(self):
"""Test case for remove_dependents_for_task
Unlink dependents from a task # noqa: E501
"""
pass
def test_remove_follower_for_task(self):
"""Test case for remove_follower_for_task
Remove followers from a task # noqa: E501
"""
pass
def test_remove_project_for_task(self):
"""Test case for remove_project_for_task
Remove a project from a task # noqa: E501
"""
pass
def test_remove_tag_for_task(self):
"""Test case for remove_tag_for_task
Remove a tag from a task # noqa: E501
"""
pass
def test_search_tasks_for_workspace(self):
"""Test case for search_tasks_for_workspace
Search tasks in a workspace # noqa: E501
"""
pass
def test_set_parent_for_task(self):
"""Test case for set_parent_for_task
Set the parent of a task # noqa: E501
"""
pass
def test_update_task(self):
"""Test case for update_task
Update a task # noqa: E501
"""
pass
|
class TestTasksApi(unittest.TestCase):
'''TasksApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_add_dependencies_for_task(self):
'''Test case for add_dependencies_for_task
Set dependencies for a task # noqa: E501
'''
pass
def test_add_dependents_for_task(self):
'''Test case for add_dependents_for_task
Set dependents for a task # noqa: E501
'''
pass
def test_add_followers_for_task(self):
'''Test case for add_followers_for_task
Add followers to a task # noqa: E501
'''
pass
def test_add_project_for_task(self):
'''Test case for add_project_for_task
Add a project to a task # noqa: E501
'''
pass
def test_add_tag_for_task(self):
'''Test case for add_tag_for_task
Add a tag to a task # noqa: E501
'''
pass
def test_create_subtask_for_task(self):
'''Test case for create_subtask_for_task
Create a subtask # noqa: E501
'''
pass
def test_create_task(self):
'''Test case for create_task
Create a task # noqa: E501
'''
pass
def test_delete_task(self):
'''Test case for delete_task
Delete a task # noqa: E501
'''
pass
def test_duplicate_task(self):
'''Test case for duplicate_task
Duplicate a task # noqa: E501
'''
pass
def test_get_dependencies_for_task(self):
'''Test case for get_dependencies_for_task
Get dependencies from a task # noqa: E501
'''
pass
def test_get_dependents_for_task(self):
'''Test case for get_dependents_for_task
Get dependents from a task # noqa: E501
'''
pass
def test_get_subtasks_for_task(self):
'''Test case for get_subtasks_for_task
Get subtasks from a task # noqa: E501
'''
pass
def test_get_task(self):
'''Test case for get_task
Get a task # noqa: E501
'''
pass
def test_get_tasks(self):
'''Test case for get_tasks
Get multiple tasks # noqa: E501
'''
pass
def test_get_tasks_for_project(self):
'''Test case for get_tasks_for_project
Get tasks from a project # noqa: E501
'''
pass
def test_get_tasks_for_section(self):
'''Test case for get_tasks_for_section
Get tasks from a section # noqa: E501
'''
pass
def test_get_tasks_for_tag(self):
'''Test case for get_tasks_for_tag
Get tasks from a tag # noqa: E501
'''
pass
def test_get_tasks_for_user_task_list(self):
'''Test case for get_tasks_for_user_task_list
Get tasks from a user task list # noqa: E501
'''
pass
def test_remove_dependencies_for_task(self):
'''Test case for remove_dependencies_for_task
Unlink dependencies from a task # noqa: E501
'''
pass
def test_remove_dependents_for_task(self):
'''Test case for remove_dependents_for_task
Unlink dependents from a task # noqa: E501
'''
pass
def test_remove_follower_for_task(self):
'''Test case for remove_follower_for_task
Remove followers from a task # noqa: E501
'''
pass
def test_remove_project_for_task(self):
'''Test case for remove_project_for_task
Remove a project from a task # noqa: E501
'''
pass
def test_remove_tag_for_task(self):
'''Test case for remove_tag_for_task
Remove a tag from a task # noqa: E501
'''
pass
def test_search_tasks_for_workspace(self):
'''Test case for search_tasks_for_workspace
Search tasks in a workspace # noqa: E501
'''
pass
def test_set_parent_for_task(self):
'''Test case for set_parent_for_task
Set the parent of a task # noqa: E501
'''
pass
def test_update_task(self):
'''Test case for update_task
Update a task # noqa: E501
'''
pass
| 29 | 27 | 6 | 1 | 2 | 3 | 1 | 1.4 | 1 | 1 | 1 | 0 | 28 | 1 | 28 | 100 | 190 | 54 | 57 | 30 | 28 | 80 | 57 | 30 | 28 | 1 | 2 | 0 | 28 |
7,535 |
Asana/python-asana
|
Asana_python-asana/test/test_team_memberships_api.py
|
test.test_team_memberships_api.TestTeamMembershipsApi
|
class TestTeamMembershipsApi(unittest.TestCase):
"""TeamMembershipsApi unit test stubs"""
def setUp(self):
self.api = TeamMembershipsApi() # noqa: E501
def tearDown(self):
pass
def test_get_team_membership(self):
"""Test case for get_team_membership
Get a team membership # noqa: E501
"""
pass
def test_get_team_memberships(self):
"""Test case for get_team_memberships
Get team memberships # noqa: E501
"""
pass
def test_get_team_memberships_for_team(self):
"""Test case for get_team_memberships_for_team
Get memberships from a team # noqa: E501
"""
pass
def test_get_team_memberships_for_user(self):
"""Test case for get_team_memberships_for_user
Get memberships from a user # noqa: E501
"""
pass
|
class TestTeamMembershipsApi(unittest.TestCase):
'''TeamMembershipsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_get_team_membership(self):
'''Test case for get_team_membership
Get a team membership # noqa: E501
'''
pass
def test_get_team_memberships(self):
'''Test case for get_team_memberships
Get team memberships # noqa: E501
'''
pass
def test_get_team_memberships_for_team(self):
'''Test case for get_team_memberships_for_team
Get memberships from a team # noqa: E501
'''
pass
def test_get_team_memberships_for_user(self):
'''Test case for get_team_memberships_for_user
Get memberships from a user # noqa: E501
'''
pass
| 7 | 5 | 5 | 1 | 2 | 2 | 1 | 1.08 | 1 | 1 | 1 | 0 | 6 | 1 | 6 | 78 | 36 | 10 | 13 | 8 | 6 | 14 | 13 | 8 | 6 | 1 | 2 | 0 | 6 |
7,536 |
Asana/python-asana
|
Asana_python-asana/test/test_teams_api.py
|
test.test_teams_api.TestTeamsApi
|
class TestTeamsApi(unittest.TestCase):
"""TeamsApi unit test stubs"""
def setUp(self):
self.api = TeamsApi() # noqa: E501
def tearDown(self):
pass
def test_add_user_for_team(self):
"""Test case for add_user_for_team
Add a user to a team # noqa: E501
"""
pass
def test_create_team(self):
"""Test case for create_team
Create a team # noqa: E501
"""
pass
def test_get_team(self):
"""Test case for get_team
Get a team # noqa: E501
"""
pass
def test_get_teams_for_user(self):
"""Test case for get_teams_for_user
Get teams for a user # noqa: E501
"""
pass
def test_get_teams_for_workspace(self):
"""Test case for get_teams_for_workspace
Get teams in a workspace # noqa: E501
"""
pass
def test_remove_user_for_team(self):
"""Test case for remove_user_for_team
Remove a user from a team # noqa: E501
"""
pass
def test_update_team(self):
"""Test case for update_team
Update a team # noqa: E501
"""
pass
|
class TestTeamsApi(unittest.TestCase):
'''TeamsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_add_user_for_team(self):
'''Test case for add_user_for_team
Add a user to a team # noqa: E501
'''
pass
def test_create_team(self):
'''Test case for create_team
Create a team # noqa: E501
'''
pass
def test_get_team(self):
'''Test case for get_team
Get a team # noqa: E501
'''
pass
def test_get_teams_for_user(self):
'''Test case for get_teams_for_user
Get teams for a user # noqa: E501
'''
pass
def test_get_teams_for_workspace(self):
'''Test case for get_teams_for_workspace
Get teams in a workspace # noqa: E501
'''
pass
def test_remove_user_for_team(self):
'''Test case for remove_user_for_team
Remove a user from a team # noqa: E501
'''
pass
def test_update_team(self):
'''Test case for update_team
Update a team # noqa: E501
'''
pass
| 10 | 8 | 5 | 1 | 2 | 2 | 1 | 1.21 | 1 | 1 | 1 | 0 | 9 | 1 | 9 | 81 | 57 | 16 | 19 | 11 | 9 | 23 | 19 | 11 | 9 | 1 | 2 | 0 | 9 |
7,537 |
Asana/python-asana
|
Asana_python-asana/test/test_time_periods_api.py
|
test.test_time_periods_api.TestTimePeriodsApi
|
class TestTimePeriodsApi(unittest.TestCase):
"""TimePeriodsApi unit test stubs"""
def setUp(self):
self.api = TimePeriodsApi() # noqa: E501
def tearDown(self):
pass
def test_get_time_period(self):
"""Test case for get_time_period
Get a time period # noqa: E501
"""
pass
def test_get_time_periods(self):
"""Test case for get_time_periods
Get time periods # noqa: E501
"""
pass
|
class TestTimePeriodsApi(unittest.TestCase):
'''TimePeriodsApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_get_time_period(self):
'''Test case for get_time_period
Get a time period # noqa: E501
'''
pass
def test_get_time_periods(self):
'''Test case for get_time_periods
Get time periods # noqa: E501
'''
pass
| 5 | 3 | 4 | 1 | 2 | 2 | 1 | 0.89 | 1 | 1 | 1 | 0 | 4 | 1 | 4 | 76 | 22 | 6 | 9 | 6 | 4 | 8 | 9 | 6 | 4 | 1 | 2 | 0 | 4 |
7,538 |
Asana/python-asana
|
Asana_python-asana/test/test_time_tracking_entries_api.py
|
test.test_time_tracking_entries_api.TestTimeTrackingEntriesApi
|
class TestTimeTrackingEntriesApi(unittest.TestCase):
"""TimeTrackingEntriesApi unit test stubs"""
def setUp(self):
self.api = TimeTrackingEntriesApi() # noqa: E501
def tearDown(self):
pass
def test_create_time_tracking_entry(self):
"""Test case for create_time_tracking_entry
Create a time tracking entry # noqa: E501
"""
pass
def test_delete_time_tracking_entry(self):
"""Test case for delete_time_tracking_entry
Delete a time tracking entry # noqa: E501
"""
pass
def test_get_time_tracking_entries_for_task(self):
"""Test case for get_time_tracking_entries_for_task
Get time tracking entries for a task # noqa: E501
"""
pass
def test_get_time_tracking_entry(self):
"""Test case for get_time_tracking_entry
Get a time tracking entry # noqa: E501
"""
pass
def test_update_time_tracking_entry(self):
"""Test case for update_time_tracking_entry
Update a time tracking entry # noqa: E501
"""
pass
|
class TestTimeTrackingEntriesApi(unittest.TestCase):
'''TimeTrackingEntriesApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_time_tracking_entry(self):
'''Test case for create_time_tracking_entry
Create a time tracking entry # noqa: E501
'''
pass
def test_delete_time_tracking_entry(self):
'''Test case for delete_time_tracking_entry
Delete a time tracking entry # noqa: E501
'''
pass
def test_get_time_tracking_entries_for_task(self):
'''Test case for get_time_tracking_entries_for_task
Get time tracking entries for a task # noqa: E501
'''
pass
def test_get_time_tracking_entry(self):
'''Test case for get_time_tracking_entry
Get a time tracking entry # noqa: E501
'''
pass
def test_update_time_tracking_entry(self):
'''Test case for update_time_tracking_entry
Update a time tracking entry # noqa: E501
'''
pass
| 8 | 6 | 5 | 1 | 2 | 2 | 1 | 1.13 | 1 | 1 | 1 | 0 | 7 | 1 | 7 | 79 | 43 | 12 | 15 | 9 | 7 | 17 | 15 | 9 | 7 | 1 | 2 | 0 | 7 |
7,539 |
Asana/python-asana
|
Asana_python-asana/test/test_status_updates_api.py
|
test.test_status_updates_api.TestStatusUpdatesApi
|
class TestStatusUpdatesApi(unittest.TestCase):
"""StatusUpdatesApi unit test stubs"""
def setUp(self):
self.api = StatusUpdatesApi() # noqa: E501
def tearDown(self):
pass
def test_create_status_for_object(self):
"""Test case for create_status_for_object
Create a status update # noqa: E501
"""
pass
def test_delete_status(self):
"""Test case for delete_status
Delete a status update # noqa: E501
"""
pass
def test_get_status(self):
"""Test case for get_status
Get a status update # noqa: E501
"""
pass
def test_get_statuses_for_object(self):
"""Test case for get_statuses_for_object
Get status updates from an object # noqa: E501
"""
pass
|
class TestStatusUpdatesApi(unittest.TestCase):
'''StatusUpdatesApi unit test stubs'''
def setUp(self):
pass
def tearDown(self):
pass
def test_create_status_for_object(self):
'''Test case for create_status_for_object
Create a status update # noqa: E501
'''
pass
def test_delete_status(self):
'''Test case for delete_status
Delete a status update # noqa: E501
'''
pass
def test_get_status(self):
'''Test case for get_status
Get a status update # noqa: E501
'''
pass
def test_get_statuses_for_object(self):
'''Test case for get_statuses_for_object
Get status updates from an object # noqa: E501
'''
pass
| 7 | 5 | 5 | 1 | 2 | 2 | 1 | 1.08 | 1 | 1 | 1 | 0 | 6 | 1 | 6 | 78 | 36 | 10 | 13 | 8 | 6 | 14 | 13 | 8 | 6 | 1 | 2 | 0 | 6 |
7,540 |
Asana/python-asana
|
Asana_python-asana/asana/api/portfolios_api.py
|
asana.api.portfolios_api.PortfoliosApi
|
class PortfoliosApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def add_custom_field_setting_for_portfolio(self, body, portfolio_gid, **kwargs): # noqa: E501
"""Add a custom field to a portfolio # noqa: E501
Custom fields are associated with portfolios by way of custom field settings. This method creates a setting for the portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_custom_field_setting_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the custom field setting. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: CustomFieldSettingResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.add_custom_field_setting_for_portfolio_with_http_info(body, portfolio_gid, **kwargs) # noqa: E501
else:
(data) = self.add_custom_field_setting_for_portfolio_with_http_info(body, portfolio_gid, **kwargs) # noqa: E501
return data
def add_custom_field_setting_for_portfolio_with_http_info(self, body, portfolio_gid, **kwargs): # noqa: E501
"""Add a custom field to a portfolio # noqa: E501
Custom fields are associated with portfolios by way of custom field settings. This method creates a setting for the portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_custom_field_setting_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the custom field setting. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: CustomFieldSettingResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_custom_field_setting_for_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `add_custom_field_setting_for_portfolio`") # noqa: E501
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `add_custom_field_setting_for_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/addCustomFieldSetting', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/portfolios/{portfolio_gid}/addCustomFieldSetting', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/addCustomFieldSetting', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def add_item_for_portfolio(self, body, portfolio_gid, **kwargs): # noqa: E501
"""Add a portfolio item # noqa: E501
Add an item to a portfolio. Returns an empty data block. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_item_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the item being inserted. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.add_item_for_portfolio_with_http_info(body, portfolio_gid, **kwargs) # noqa: E501
else:
(data) = self.add_item_for_portfolio_with_http_info(body, portfolio_gid, **kwargs) # noqa: E501
return data
def add_item_for_portfolio_with_http_info(self, body, portfolio_gid, **kwargs): # noqa: E501
"""Add a portfolio item # noqa: E501
Add an item to a portfolio. Returns an empty data block. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_item_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the item being inserted. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_item_for_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `add_item_for_portfolio`") # noqa: E501
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `add_item_for_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/addItem', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/portfolios/{portfolio_gid}/addItem', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/addItem', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def add_members_for_portfolio(self, body, portfolio_gid, opts, **kwargs): # noqa: E501
"""Add users to a portfolio # noqa: E501
Adds the specified list of users as members of the portfolio. Returns the updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_members_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the members being added. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.add_members_for_portfolio_with_http_info(body, portfolio_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.add_members_for_portfolio_with_http_info(body, portfolio_gid, opts, **kwargs) # noqa: E501
return data
def add_members_for_portfolio_with_http_info(self, body, portfolio_gid, opts, **kwargs): # noqa: E501
"""Add users to a portfolio # noqa: E501
Adds the specified list of users as members of the portfolio. Returns the updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_members_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the members being added. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method add_members_for_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `add_members_for_portfolio`") # noqa: E501
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `add_members_for_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/addMembers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/portfolios/{portfolio_gid}/addMembers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/addMembers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_portfolio(self, body, opts, **kwargs): # noqa: E501
"""Create a portfolio # noqa: E501
Creates a new portfolio in the given workspace with the supplied name. Note that portfolios created in the Asana UI may have some state (like the “Priority” custom field) which is automatically added to the portfolio when it is created. Portfolios created via our API will *not* be created with the same initial state to allow integrations to create their own starting state on a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_portfolio(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The portfolio to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.create_portfolio_with_http_info(body, opts, **kwargs) # noqa: E501
else:
(data) = self.create_portfolio_with_http_info(body, opts, **kwargs) # noqa: E501
return data
def create_portfolio_with_http_info(self, body, opts, **kwargs): # noqa: E501
"""Create a portfolio # noqa: E501
Creates a new portfolio in the given workspace with the supplied name. Note that portfolios created in the Asana UI may have some state (like the “Priority” custom field) which is automatically added to the portfolio when it is created. Portfolios created via our API will *not* be created with the same initial state to allow integrations to create their own starting state on a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_portfolio_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The portfolio to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `create_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/portfolios', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/portfolios', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_portfolio(self, portfolio_gid, **kwargs): # noqa: E501
"""Delete a portfolio # noqa: E501
An existing portfolio can be deleted by making a DELETE request on the URL for that portfolio. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_portfolio(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.delete_portfolio_with_http_info(portfolio_gid, **kwargs) # noqa: E501
else:
(data) = self.delete_portfolio_with_http_info(portfolio_gid, **kwargs) # noqa: E501
return data
def delete_portfolio_with_http_info(self, portfolio_gid, **kwargs): # noqa: E501
"""Delete a portfolio # noqa: E501
An existing portfolio can be deleted by making a DELETE request on the URL for that portfolio. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_portfolio_with_http_info(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `delete_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/portfolios/{portfolio_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_items_for_portfolio(self, portfolio_gid, opts, **kwargs): # noqa: E501
"""Get portfolio items # noqa: E501
Get a list of the items in compact form in a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_items_for_portfolio(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_items_for_portfolio_with_http_info(portfolio_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_items_for_portfolio_with_http_info(portfolio_gid, opts, **kwargs) # noqa: E501
return data
def get_items_for_portfolio_with_http_info(self, portfolio_gid, opts, **kwargs): # noqa: E501
"""Get portfolio items # noqa: E501
Get a list of the items in compact form in a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_items_for_portfolio_with_http_info(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_items_for_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `get_items_for_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/items', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/portfolios/{portfolio_gid}/items',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/items', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_portfolio(self, portfolio_gid, opts, **kwargs): # noqa: E501
"""Get a portfolio # noqa: E501
Returns the complete portfolio record for a single portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_portfolio(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_portfolio_with_http_info(portfolio_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.get_portfolio_with_http_info(portfolio_gid, opts, **kwargs) # noqa: E501
return data
def get_portfolio_with_http_info(self, portfolio_gid, opts, **kwargs): # noqa: E501
"""Get a portfolio # noqa: E501
Returns the complete portfolio record for a single portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_portfolio_with_http_info(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `get_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/portfolios/{portfolio_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_portfolios(self, workspace, opts, **kwargs): # noqa: E501
"""Get multiple portfolios # noqa: E501
Returns a list of the portfolios in compact representation that are owned by the current API user. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_portfolios(workspace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace: The workspace or organization to filter portfolios on. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str owner: The user who owns the portfolio. Currently, API users can only get a list of portfolios that they themselves own, unless the request is made from a Service Account. In the case of a Service Account, if this parameter is specified, then all portfolios owned by this parameter are returned. Otherwise, all portfolios across the workspace are returned.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseArray
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.get_portfolios_with_http_info(workspace, opts, **kwargs) # noqa: E501
else:
(data) = self.get_portfolios_with_http_info(workspace, opts, **kwargs) # noqa: E501
return data
def get_portfolios_with_http_info(self, workspace, opts, **kwargs): # noqa: E501
"""Get multiple portfolios # noqa: E501
Returns a list of the portfolios in compact representation that are owned by the current API user. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_portfolios_with_http_info(workspace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace: The workspace or organization to filter portfolios on. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str owner: The user who owns the portfolio. Currently, API users can only get a list of portfolios that they themselves own, unless the request is made from a Service Account. In the case of a Service Account, if this parameter is specified, then all portfolios owned by this parameter are returned. Otherwise, all portfolios across the workspace are returned.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseArray
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_portfolios" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'workspace' is set
if (workspace is None):
raise ValueError("Missing the required parameter `workspace` when calling `get_portfolios`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = {}
query_params = opts
query_params['workspace'] = workspace
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
query_params["limit"] = query_params.get("limit", self.api_client.configuration.page_limit)
return PageIterator(
self.api_client,
{
"resource_path": '/portfolios',
"method": 'GET',
"path_params": path_params,
"query_params": query_params,
"header_params": header_params,
"body": body_params,
"post_params": form_params,
"files": local_var_files,
"response_type": object,
"auth_settings": auth_settings,
"async_req": params.get('async_req'),
"_return_http_data_only": params.get('_return_http_data_only'),
"_preload_content": params.get('_preload_content', True),
"_request_timeout": params.get('_request_timeout'),
"collection_formats": collection_formats
},
**kwargs
).items()
else:
return self.api_client.call_api(
'/portfolios', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def remove_custom_field_setting_for_portfolio(self, body, portfolio_gid, **kwargs): # noqa: E501
"""Remove a custom field from a portfolio # noqa: E501
Removes a custom field setting from a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_custom_field_setting_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the custom field setting being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.remove_custom_field_setting_for_portfolio_with_http_info(body, portfolio_gid, **kwargs) # noqa: E501
else:
(data) = self.remove_custom_field_setting_for_portfolio_with_http_info(body, portfolio_gid, **kwargs) # noqa: E501
return data
def remove_custom_field_setting_for_portfolio_with_http_info(self, body, portfolio_gid, **kwargs): # noqa: E501
"""Remove a custom field from a portfolio # noqa: E501
Removes a custom field setting from a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_custom_field_setting_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the custom field setting being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_custom_field_setting_for_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `remove_custom_field_setting_for_portfolio`") # noqa: E501
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `remove_custom_field_setting_for_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/removeCustomFieldSetting', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/portfolios/{portfolio_gid}/removeCustomFieldSetting', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/removeCustomFieldSetting', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def remove_item_for_portfolio(self, body, portfolio_gid, **kwargs): # noqa: E501
"""Remove a portfolio item # noqa: E501
Remove an item from a portfolio. Returns an empty data block. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_item_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the item being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.remove_item_for_portfolio_with_http_info(body, portfolio_gid, **kwargs) # noqa: E501
else:
(data) = self.remove_item_for_portfolio_with_http_info(body, portfolio_gid, **kwargs) # noqa: E501
return data
def remove_item_for_portfolio_with_http_info(self, body, portfolio_gid, **kwargs): # noqa: E501
"""Remove a portfolio item # noqa: E501
Remove an item from a portfolio. Returns an empty data block. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_item_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the item being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_item_for_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `remove_item_for_portfolio`") # noqa: E501
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `remove_item_for_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/removeItem', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/portfolios/{portfolio_gid}/removeItem', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/removeItem', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def remove_members_for_portfolio(self, body, portfolio_gid, opts, **kwargs): # noqa: E501
"""Remove users from a portfolio # noqa: E501
Removes the specified list of users from members of the portfolio. Returns the updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_members_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the members being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.remove_members_for_portfolio_with_http_info(body, portfolio_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.remove_members_for_portfolio_with_http_info(body, portfolio_gid, opts, **kwargs) # noqa: E501
return data
def remove_members_for_portfolio_with_http_info(self, body, portfolio_gid, opts, **kwargs): # noqa: E501
"""Remove users from a portfolio # noqa: E501
Removes the specified list of users from members of the portfolio. Returns the updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_members_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the members being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_members_for_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `remove_members_for_portfolio`") # noqa: E501
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `remove_members_for_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/removeMembers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/portfolios/{portfolio_gid}/removeMembers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}/removeMembers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def update_portfolio(self, body, portfolio_gid, opts, **kwargs): # noqa: E501
"""Update a portfolio # noqa: E501
An existing portfolio can be updated by making a PUT request on the URL for that portfolio. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the portfolio. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = kwargs.get("_return_http_data_only", True)
if kwargs.get('async_req'):
return self.update_portfolio_with_http_info(body, portfolio_gid, opts, **kwargs) # noqa: E501
else:
(data) = self.update_portfolio_with_http_info(body, portfolio_gid, opts, **kwargs) # noqa: E501
return data
def update_portfolio_with_http_info(self, body, portfolio_gid, opts, **kwargs): # noqa: E501
"""Update a portfolio # noqa: E501
An existing portfolio can be updated by making a PUT request on the URL for that portfolio. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the portfolio. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('header_params')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
all_params.append('full_payload')
all_params.append('item_limit')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method update_portfolio" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if (body is None):
raise ValueError("Missing the required parameter `body` when calling `update_portfolio`") # noqa: E501
# verify the required parameter 'portfolio_gid' is set
if (portfolio_gid is None):
raise ValueError("Missing the required parameter `portfolio_gid` when calling `update_portfolio`") # noqa: E501
collection_formats = {}
path_params = {}
path_params['portfolio_gid'] = portfolio_gid # noqa: E501
query_params = {}
query_params = opts
header_params = kwargs.get("header_params", {})
form_params = []
local_var_files = {}
body_params = body
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json; charset=UTF-8']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json; charset=UTF-8']) # noqa: E501
# Authentication setting
auth_settings = ['personalAccessToken'] # noqa: E501
# hard checking for True boolean value because user can provide full_payload or async_req with any data type
if kwargs.get("full_payload", False) is True or kwargs.get('async_req', False) is True:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
elif self.api_client.configuration.return_page_iterator:
(data) = self.api_client.call_api(
'/portfolios/{portfolio_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats
)
if params.get('_return_http_data_only') == False:
return data
return data["data"] if data else data
else:
return self.api_client.call_api(
'/portfolios/{portfolio_gid}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=object, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
class PortfoliosApi(object):
'''NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
'''
def __init__(self, api_client=None):
pass
def add_custom_field_setting_for_portfolio(self, body, portfolio_gid, **kwargs):
'''Add a custom field to a portfolio # noqa: E501
Custom fields are associated with portfolios by way of custom field settings. This method creates a setting for the portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_custom_field_setting_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the custom field setting. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: CustomFieldSettingResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def add_custom_field_setting_for_portfolio_with_http_info(self, body, portfolio_gid, **kwargs):
'''Add a custom field to a portfolio # noqa: E501
Custom fields are associated with portfolios by way of custom field settings. This method creates a setting for the portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_custom_field_setting_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the custom field setting. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: CustomFieldSettingResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def add_item_for_portfolio(self, body, portfolio_gid, **kwargs):
'''Add a portfolio item # noqa: E501
Add an item to a portfolio. Returns an empty data block. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_item_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the item being inserted. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def add_item_for_portfolio_with_http_info(self, body, portfolio_gid, **kwargs):
'''Add a portfolio item # noqa: E501
Add an item to a portfolio. Returns an empty data block. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_item_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the item being inserted. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def add_members_for_portfolio(self, body, portfolio_gid, opts, **kwargs):
'''Add users to a portfolio # noqa: E501
Adds the specified list of users as members of the portfolio. Returns the updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_members_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the members being added. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def add_members_for_portfolio_with_http_info(self, body, portfolio_gid, opts, **kwargs):
'''Add users to a portfolio # noqa: E501
Adds the specified list of users as members of the portfolio. Returns the updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_members_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the members being added. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_portfolio(self, body, opts, **kwargs):
'''Create a portfolio # noqa: E501
Creates a new portfolio in the given workspace with the supplied name. Note that portfolios created in the Asana UI may have some state (like the “Priority” custom field) which is automatically added to the portfolio when it is created. Portfolios created via our API will *not* be created with the same initial state to allow integrations to create their own starting state on a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_portfolio(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The portfolio to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def create_portfolio_with_http_info(self, body, opts, **kwargs):
'''Create a portfolio # noqa: E501
Creates a new portfolio in the given workspace with the supplied name. Note that portfolios created in the Asana UI may have some state (like the “Priority” custom field) which is automatically added to the portfolio when it is created. Portfolios created via our API will *not* be created with the same initial state to allow integrations to create their own starting state on a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_portfolio_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The portfolio to create. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_portfolio(self, portfolio_gid, **kwargs):
'''Delete a portfolio # noqa: E501
An existing portfolio can be deleted by making a DELETE request on the URL for that portfolio. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_portfolio(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def delete_portfolio_with_http_info(self, portfolio_gid, **kwargs):
'''Delete a portfolio # noqa: E501
An existing portfolio can be deleted by making a DELETE request on the URL for that portfolio. Returns an empty data record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_portfolio_with_http_info(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_items_for_portfolio(self, portfolio_gid, opts, **kwargs):
'''Get portfolio items # noqa: E501
Get a list of the items in compact form in a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_items_for_portfolio(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_items_for_portfolio_with_http_info(self, portfolio_gid, opts, **kwargs):
'''Get portfolio items # noqa: E501
Get a list of the items in compact form in a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_items_for_portfolio_with_http_info(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: ProjectResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_portfolio(self, portfolio_gid, opts, **kwargs):
'''Get a portfolio # noqa: E501
Returns the complete portfolio record for a single portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_portfolio(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_portfolio_with_http_info(self, portfolio_gid, opts, **kwargs):
'''Get a portfolio # noqa: E501
Returns the complete portfolio record for a single portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_portfolio_with_http_info(portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_portfolios(self, workspace, opts, **kwargs):
'''Get multiple portfolios # noqa: E501
Returns a list of the portfolios in compact representation that are owned by the current API user. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_portfolios(workspace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace: The workspace or organization to filter portfolios on. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str owner: The user who owns the portfolio. Currently, API users can only get a list of portfolios that they themselves own, unless the request is made from a Service Account. In the case of a Service Account, if this parameter is specified, then all portfolios owned by this parameter are returned. Otherwise, all portfolios across the workspace are returned.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def get_portfolios_with_http_info(self, workspace, opts, **kwargs):
'''Get multiple portfolios # noqa: E501
Returns a list of the portfolios in compact representation that are owned by the current API user. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_portfolios_with_http_info(workspace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str workspace: The workspace or organization to filter portfolios on. (required)
:param int limit: Results per page. The number of objects to return per page. The value must be between 1 and 100.
:param str offset: Offset token. An offset to the next page returned by the API. A pagination request will return an offset token, which can be used as an input parameter to the next request. If an offset is not passed in, the API will return the first page of results. *Note: You can only pass in an offset that was returned to you via a previously paginated request.*
:param str owner: The user who owns the portfolio. Currently, API users can only get a list of portfolios that they themselves own, unless the request is made from a Service Account. In the case of a Service Account, if this parameter is specified, then all portfolios owned by this parameter are returned. Otherwise, all portfolios across the workspace are returned.
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseArray
If the method is called asynchronously,
returns the request thread.
'''
pass
def remove_custom_field_setting_for_portfolio(self, body, portfolio_gid, **kwargs):
'''Remove a custom field from a portfolio # noqa: E501
Removes a custom field setting from a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_custom_field_setting_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the custom field setting being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def remove_custom_field_setting_for_portfolio_with_http_info(self, body, portfolio_gid, **kwargs):
'''Remove a custom field from a portfolio # noqa: E501
Removes a custom field setting from a portfolio. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_custom_field_setting_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the custom field setting being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def remove_item_for_portfolio(self, body, portfolio_gid, **kwargs):
'''Remove a portfolio item # noqa: E501
Remove an item from a portfolio. Returns an empty data block. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_item_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the item being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def remove_item_for_portfolio_with_http_info(self, body, portfolio_gid, **kwargs):
'''Remove a portfolio item # noqa: E501
Remove an item from a portfolio. Returns an empty data block. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_item_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the item being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:return: EmptyResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def remove_members_for_portfolio(self, body, portfolio_gid, opts, **kwargs):
'''Remove users from a portfolio # noqa: E501
Removes the specified list of users from members of the portfolio. Returns the updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_members_for_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the members being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def remove_members_for_portfolio_with_http_info(self, body, portfolio_gid, opts, **kwargs):
'''Remove users from a portfolio # noqa: E501
Removes the specified list of users from members of the portfolio. Returns the updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_members_for_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: Information about the members being removed. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_portfolio(self, body, portfolio_gid, opts, **kwargs):
'''Update a portfolio # noqa: E501
An existing portfolio can be updated by making a PUT request on the URL for that portfolio. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_portfolio(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the portfolio. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
def update_portfolio_with_http_info(self, body, portfolio_gid, opts, **kwargs):
'''Update a portfolio # noqa: E501
An existing portfolio can be updated by making a PUT request on the URL for that portfolio. Only the fields provided in the `data` block will be updated; any unspecified fields will remain unchanged. Returns the complete updated portfolio record. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_portfolio_with_http_info(body, portfolio_gid, async_req=True)
>>> result = thread.get()
:param async_req bool
:param dict body: The updated fields for the portfolio. (required)
:param str portfolio_gid: Globally unique identifier for the portfolio. (required)
:param list[str] opt_fields: This endpoint returns a resource which excludes some properties by default. To include those optional properties, set this query parameter to a comma-separated list of the properties you wish to include.
:return: PortfolioResponseData
If the method is called asynchronously,
returns the request thread.
'''
pass
| 26 | 25 | 69 | 8 | 46 | 22 | 5 | 0.48 | 1 | 4 | 2 | 0 | 25 | 1 | 25 | 25 | 1,746 | 214 | 1,139 | 181 | 1,113 | 544 | 509 | 181 | 483 | 9 | 1 | 2 | 125 |
7,541 |
AshleySetter/frange
|
frange/frange/frange.py
|
frange.frange.frange
|
class frange():
"""
Return an object can be used to generate a generator or an array
of floats from start (inclusive) to stop (exclusive) by step.
This object stores the start, stop, step and length of
the data. Uses less memory than storing a large array.
Example
-------
An example of how to use this class to generate some data is
as follows for some time data between 0 and 2 in steps of
1e-3 (0.001)::
you can create an frange object like so
$ time = frange(0, 2, 1e-3)
you can print the length of the array it will generate
$ printlen(time) # prints length of frange, just like an array or list
you can create a generator
$ generator = time.get_generator() # gets a generator instance
$ for i in generator: # iterates through printing each element
$ print(i)
you can create a numpy array
$ array = time.get_array() # gets an array instance
$ newarray = 5 * array # multiplies array by 5
you can also get the start, stop and step by accessing the slice parameters
$ start = time.slice.start
$ stop = time.slice.stop
$ step = time.slice.step
"""
def __init__(self, start, stop, step):
"""
Intialises frange class instance. Sets start, top, step and
len properties.
Parameters
----------
start : float
starting point
stop : float
stopping point
step : float
stepping interval
"""
self.slice = slice(start, stop, step)
self.len = self.get_array().size
return None
def get_generator(self):
"""
Returns a generator for the frange object instance.
Returns
-------
gen : generator
A generator that yields successive samples from start (inclusive)
to stop (exclusive) in step steps.
"""
s = self.slice
gen = drange(s.start, s.stop, s.step) # intialises the generator
return gen
def get_array(self):
"""
Returns an numpy array containing the values from start (inclusive)
to stop (exclusive) in step steps.
Returns
-------
array : ndarray
Array of values from start (inclusive)
to stop (exclusive) in step steps.
"""
s = self.slice
array = _np.arange(s.start, s.stop, s.step)
return array
# def __array__(self): # supposedly allows numpy to treat object itself as an array but it doesn't work?
# array = self.get_array()
# return array
def __len__(self):
return self.len
|
class frange():
'''
Return an object can be used to generate a generator or an array
of floats from start (inclusive) to stop (exclusive) by step.
This object stores the start, stop, step and length of
the data. Uses less memory than storing a large array.
Example
-------
An example of how to use this class to generate some data is
as follows for some time data between 0 and 2 in steps of
1e-3 (0.001)::
you can create an frange object like so
$ time = frange(0, 2, 1e-3)
you can print the length of the array it will generate
$ printlen(time) # prints length of frange, just like an array or list
you can create a generator
$ generator = time.get_generator() # gets a generator instance
$ for i in generator: # iterates through printing each element
$ print(i)
you can create a numpy array
$ array = time.get_array() # gets an array instance
$ newarray = 5 * array # multiplies array by 5
you can also get the start, stop and step by accessing the slice parameters
$ start = time.slice.start
$ stop = time.slice.stop
$ step = time.slice.step
'''
def __init__(self, start, stop, step):
'''
Intialises frange class instance. Sets start, top, step and
len properties.
Parameters
----------
start : float
starting point
stop : float
stopping point
step : float
stepping interval
'''
pass
def get_generator(self):
'''
Returns a generator for the frange object instance.
Returns
-------
gen : generator
A generator that yields successive samples from start (inclusive)
to stop (exclusive) in step steps.
'''
pass
def get_array(self):
'''
Returns an numpy array containing the values from start (inclusive)
to stop (exclusive) in step steps.
Returns
-------
array : ndarray
Array of values from start (inclusive)
to stop (exclusive) in step steps.
'''
pass
def __len__(self):
pass
| 5 | 4 | 12 | 1 | 4 | 8 | 1 | 3.93 | 0 | 1 | 0 | 0 | 4 | 2 | 4 | 4 | 87 | 14 | 15 | 11 | 10 | 59 | 15 | 11 | 10 | 1 | 0 | 0 | 4 |
7,542 |
AshleySetter/optoanalysis
|
AshleySetter_optoanalysis/optoanalysis/optoanalysis/optoanalysis.py
|
optoanalysis.optoanalysis.DataObject
|
class DataObject():
"""
Creates an object containing data and all it's properties.
Attributes
----------
filepath : string
filepath to the file containing the data used to initialise
this particular instance of the DataObject class
filename : string
filename of the file containing the data used to initialise
this particular instance of the DataObject class
time : frange
Contains the time data as an frange object. Can get a generator
or array of this object.
voltage : ndarray
Contains the voltage data in Volts
SampleFreq : sample frequency used to sample the data (when it was
taken by the oscilloscope)
freqs : ndarray
Contains the frequencies corresponding to the PSD (Pulse Spectral
Density)
PSD : ndarray
Contains the values for the PSD (Pulse Spectral Density) as calculated
at each frequency contained in freqs
"""
def __init__(self, filepath=None, voltage=None, time=None, SampleFreq=None, timeStart=None, RelativeChannelNo=None, PointsToLoad=-1, calcPSD=True, NPerSegmentPSD=1000000, NormaliseByMonitorOutput=False):
"""
Parameters
----------
filepath : string, optional
The filepath to the data file to initialise this object instance.
voltage : ndarray, optional
Array of voltages recorded by the measurement device, to be used as an alternative to filepath when the file to be loaded is not supported natively.
If this argument is passed, one of either the time or SampleFreq variables must be provided
time : ndarray, optional
Array of times corresponding to the voltage measurements, only used if voltage is passed
SampleFreq : float, optional
The sample frequency of the voltage measurements, if the time data is not provided, only used if voltage is passed or
if loading a .dat file produced by the labview NI5122 daq card, where it is used to manually specify the sample frequency
timeStart : float, optional
The start time of the time data
RelativeChannelNo : int, optional
If loading a .bin file produced by the Saleae datalogger, used to specify
the channel number
If loading a .dat file produced by the labview NI5122 daq card, used to
specifiy the channel number if two channels where saved, if left None with
.dat files it will assume that the file to load only contains one channel.
If NormaliseByMonitorOutput is True then RelativeChannelNo specifies the
monitor channel for loading a .dat file produced by the labview NI5122 daq card.
PointsToLoad : int, optional
Number of first points to read. -1 means all points (i.e. the complete file)
WORKS WITH NI5122 DATA SO FAR ONLY!!!
calcPSD : bool, optional
Whether to calculate the PSD upon loading the file, can take some time
off the loading and reduce memory usage if frequency space info is not required
NPerSegmentPSD : int, optional
NPerSegment to pass to scipy.signal.welch to calculate the PSD
NormaliseByMonitorOutput : bool, optional
If True the particle signal trace will be divided by the monitor output, which is
specified by the channel number set in the RelativeChannelNo parameter.
WORKS WITH NI5122 DATA SO FAR ONLY!!!
Initialisation - assigns values to the following attributes:
- filepath
- filename
- filedir
- time
- voltage
- freqs
- PSD
"""
self.filepath = filepath
if self.filepath != None:
self.filename = filepath.split("/")[-1]
self.filedir = self.filepath[0:-len(self.filename)]
self.load_time_data(RelativeChannelNo, SampleFreq, PointsToLoad, NormaliseByMonitorOutput)
else:
if voltage is not None:
self.load_time_data_from_signal(voltage, time, SampleFreq, timeStart)
else:
raise ValueError("Must provide one of filepath or voltage to instantiate a DataObject instance")
print("calcPSD: ", calcPSD)
if calcPSD:
print("running self.get_PSD")
self.get_PSD(NPerSegmentPSD)
return None
def load_time_data_from_signal(self, voltage, time=None, SampleFreq=None, timeStart=None):
"""
Loads the voltage and time data provided as arrays.
Must provide the voltage signal and either provide the time data, or the sample frequency.
Sets the instance properties:
self.voltage
self.SampleFreq
self.timeStart
self.timeEnd
self.timeStep
self.time
Parameters
----------
voltage : ndarray
Array of voltages recorded by the measurement device
time : ndarray, optional
Array of times corresponding to the voltage measurements
SampleFreq : float, optional
The sample frequency of the voltage measurements, if the time data is not provided
timeStart : float, optional
The start time of the time data
"""
if voltage is None:
raise ValueError("Must provide a voltage array to load time data from a signal")
if time is None and SampleFreq is None:
raise ValueError("Must provide a value for either time or SampleFreq if loading from voltage array data")
if time != None:
self.timeStart = time[0]
self.timeEnd = time[-1]
self.timeStep = time[1] - time[0]
self.SampleFreq = 1 / self.timeStep
if SampleFreq:
self.SampleFreq = SampleFreq
self.time = frange(self.timeStart, self.timeEnd + self.timeStep, self.timeStep)
elif SampleFreq != None:
self.SampleFreq = SampleFreq
self.timeStep = 1 / self.SampleFreq
self.timeStart = timeStart
self.timeEnd = timeStart + len(voltage) * self.timeStep
self.time = frange(self.timeStart, self.timeEnd + self.timeStep, self.timeStep)
self.voltage = voltage
return None
def load_time_data(self, RelativeChannelNo=None, SampleFreq=None, PointsToLoad=-1, NormaliseByMonitorOutput=False):
"""
Loads the time and voltage data and the wave description from the associated file.
Sets the instance properties:
self.voltage
self.SampleFreq
self.timeStart
self.timeEnd
self.timeStep
self.time
Parameters
----------
RelativeChannelNo : int|str, optional
Channel to load data from (number or letter) used in following file formats:
- saleae data files - number
- .dat file produced by the labview NI5122 daq card - number
- .mat files from MATLAB version < 7.3 - letter
If loading a .dat file produced by the labview NI5122 daq card, used to
specifiy the channel number if two channels where saved, if left None with
.dat files it will assume that the file to load only contains one channel.
If NormaliseByMonitorOutput is True then RelativeChannelNo specifies the
monitor channel for loading a .dat file produced by the labview NI5122 daq card.
SampleFreq : float, optional
Manual selection of sample frequency for loading labview NI5122 daq files
PointsToLoad : int, optional
Number of first points to read. -1 means all points (i.e., the complete file)
WORKS WITH NI5122 DATA SO FAR ONLY!!!
NormaliseByMonitorOutput : bool, optional
If True the particle signal trace will be divided by the monitor output, which is
specified by the channel number set in the RelativeChannelNo parameter.
WORKS WITH NI5122 DATA SO FAR ONLY!!!
"""
f = open(self.filepath, 'rb')
raw = f.read()
f.close()
FileExtension = self.filepath.split('.')[-1]
if FileExtension == "raw" or FileExtension == "trc":
with _warnings.catch_warnings(): # supress missing data warning and raise a missing
# data warning from optoanalysis with the filepath
_warnings.simplefilter("ignore")
try:
waveDescription, timeParams, self.voltage, _, missingdata = optoanalysis.LeCroy.InterpretWaveform(raw, noTimeArray=True)
except IndexError as error:
print('problem with file {}'.format(self.filepath), flush=True)
raise(error)
if missingdata:
_warnings.warn("Waveform not of expected length. File {} may be missing data.".format(self.filepath))
self.SampleFreq = (1 / waveDescription["HORIZ_INTERVAL"])
elif FileExtension == "bin":
if RelativeChannelNo == None:
raise ValueError("If loading a .bin file from the Saleae data logger you must enter a relative channel number to load")
timeParams, self.voltage = optoanalysis.Saleae.interpret_waveform(raw, RelativeChannelNo)
self.SampleFreq = 1/timeParams[2]
elif FileExtension == "dat": #for importing a file written by labview using the NI5122 daq card
if SampleFreq == None:
raise ValueError("If loading a .dat file from the NI5122 daq card you must enter a SampleFreq")
if RelativeChannelNo == None:
self.voltage = _np.fromfile(self.filepath, dtype='>h',count=PointsToLoad)
elif RelativeChannelNo != None:
filedata = _np.fromfile(self.filepath, dtype='>h',count=PointsToLoad)
if NormaliseByMonitorOutput == True:
if RelativeChannelNo == 0:
monitorsignal = filedata[:len(filedata):2]
self.voltage = filedata[1:len(filedata):2]/monitorsignal
elif RelativeChannelNo == 1:
monitorsignal = filedata[1:len(filedata):2]
self.voltage = filedata[:len(filedata):2]/monitorsignal
elif NormaliseByMonitorOutput == False:
self.voltage = filedata[RelativeChannelNo:len(filedata):2]
timeParams = (0,(len(self.voltage)-1)/SampleFreq,1/SampleFreq)
self.SampleFreq = 1/timeParams[2]
elif FileExtension == "tdms": # for importing a file written by labview form the NI7961 FPGA with the RecordDataPC VI
if SampleFreq == None:
raise ValueError("If loading a .tdms file saved from the FPGA you must enter a SampleFreq")
self.SampleFreq = SampleFreq
dt = 1/self.SampleFreq
FIFO_SIZE = 262143 # this is the maximum size of the DMA FIFO on the NI 7961 FPGA with the NI 5781 DAC card
tdms_file = _TdmsFile(self.filepath)
channel = tdms_file.object('Measured_Data', 'data')
data = channel.data[FIFO_SIZE:] # dump first 1048575 points of data
# as this is the values that had already filled the buffer
# from before when the record code started running
volts_per_unit = 2/(2**14)
self.voltage = volts_per_unit*data
timeParams = [0, (data.shape[0]-1)*dt, dt]
elif FileExtension == 'txt': # .txt file created by LeCroy Oscilloscope
data = []
with open(self.filepath, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
data.append(row)
data = _np.array(data[5:]).astype(float).transpose()
t0 = data[0][0]
tend = data[0][-1]
dt = data[0][1] - data[0][0]
self.SampleFreq = 1/dt
self.voltage = data[1]
del(data)
timeParams = [t0, tend, dt]
elif FileExtension == "mat": # MATLAB version < 7.3
if RelativeChannelNo is not None:
channel = RelativeChannelNo
else:
channel = "B"
data = loadmat(self.filepath)
dt = data["Tinterval"][0][0]
length = data["Length"][0][0]
t0 = data["Tstart"][0][0]
self.SampleFreq = 1/dt
self.voltage = data[channel].flatten()
timeParams = [t0, t0 + (length-1)*dt, dt]
elif FileExtension.lower() == 'csv': # .CSV files created by oscilloscopes or this package
data = []
with open(self.filepath, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if len(row) != 0:
data.append(row)
data = _np.array(data)
if data[15][1] == 'TDS1001B':
horizontal = data[:,3].astype(float) # horizontal time signal - pre scaling
verticle = data[:,4].astype(float) # verticle voltage signal - pre scaling
# meta data
N_data_points = data[0, 1].astype(float)
dt = data[1, 1].astype(float)
index_of_trigger = data[2, 1].astype(float)
verticle_units = data[7, 1]
verticle_scale = data[8, 1].astype(float)
verticle_offset = data[9, 1].astype(float)
horizontal_units = data[10, 1]
horizontal_scale = data[11, 1].astype(float)
Yzero = data[13, 1].astype(float)
time = horizontal*horizontal_scale
voltage = (verticle - verticle_offset)*verticle_scale
t0 = time[0]
tend = time[-1]
timeParams = [t0, tend, dt]
del(data)
del(time)
self.SampleFreq = 1/dt
self.voltage = voltage
elif data[0][1] == 'DPO2024B':
column_names = data[15]
data_arrs = _np.array(data[16:-1])
data_arrs = _np.array(data_arrs.tolist()).astype(float)
data_arrs = data_arrs.transpose()
horizontal = data_arrs[0] # horizontal time signal - pre scaling
verticle = data_arrs[1] # verticle voltage signal - pre scaling
# meta data
horizontal_units = data[4][1]
horizontal_scale = float(data[5][1])
dt = float(data[6][1])
N_data_points = int(data[8][1])
probe_attentuation = float(data[10][1])
verticle_units = data[11][1]
verticle_offset = float(data[12][1])
verticle_scale = float(data[13][1])
time = horizontal #*horizontal_scale
voltage = verticle #(verticle - verticle_offset) #*verticle_scale
dt = time[1]-time[0] # dt from meta-data is not reliable
t0 = time[0]
tend = time[-1]
timeParams = [t0, tend, dt]
del(data)
del(time)
self.SampleFreq = 1/dt
self.voltage = voltage
elif data[0, 0] == 'time' and data[0, 1] == 'voltage':
time, voltage = data[1:].T.astype(float)
dt = time[1]-time[0] # dt from meta-data is not reliable
t0 = time[0]
tend = time[-1]
timeParams = [t0, tend, dt]
del(data)
del(time)
self.SampleFreq = 1/dt
self.voltage = voltage
elif ("Time" in data[0, 0] and "Channel" in data[0, 1]): # data from picoscope
column_names = data[0]
units = data[1]
data_arrs = _np.array(data[3:-1])
data_arrs = _np.array(data_arrs.tolist()).astype(float)
data_arrs = data_arrs.transpose()
ureg = UnitRegistry()
if (RelativeChannelNo == None):
channel_number = 1
horizontal = data_arrs[0] # horizontal time signal - pre scaling
verticle = data_arrs[channel_number] # verticle voltage signal - pre scaling
time_scaling = ureg(units[0]).to("seconds").to_tuple()[0]
time = horizontal * time_scaling
volts_scaling = ureg(units[channel_number]).to("volts").to_tuple()[0]
voltage = verticle * volts_scaling
dt = time[1]-time[0] # dt from meta-data is not reliable
t0 = time[0]
tend = time[-1]
timeParams = [t0, tend, dt]
del(data)
del(time)
self.SampleFreq = 1/dt
self.voltage = voltage
else:
raise ValueError("CSV generated by this Oscillioscope is not supported")
else:
raise ValueError("Filetype not supported")
startTime, endTime, Timestep = timeParams
self.timeStart = startTime
self.timeEnd = endTime
self.timeStep = Timestep
self.time = frange(startTime, endTime+Timestep, Timestep)
return None
def get_time_data(self, timeStart=None, timeEnd=None):
"""
Gets the time and voltage data.
Parameters
----------
timeStart : float, optional
The time get data from.
By default it uses the first time point
timeEnd : float, optional
The time to finish getting data from.
By default it uses the last time point
Returns
-------
time : ndarray
array containing the value of time (in seconds) at which the
voltage is sampled
voltage : ndarray
array containing the sampled voltages
"""
if timeStart == None:
timeStart = self.timeStart
if timeEnd == None:
timeEnd = self.timeEnd
time = self.time.get_array()
StartIndex = _np.where(time == take_closest(time, timeStart))[0][0]
EndIndex = _np.where(time == take_closest(time, timeEnd))[0][0]
if EndIndex == len(time) - 1:
EndIndex = EndIndex + 1 # so that it does not remove the last element
return time[StartIndex:EndIndex], self.voltage[StartIndex:EndIndex]
def write_time_data(self, filename):
"""
Writes time data to a csv file.
Parameters
----------
filename : string
filename of csv file to be written
"""
t = self.time.get_array()
v = self.voltage
df = _pd.DataFrame(_np.array([v, t]).T, columns=['voltage', 'time'])
df = df.set_index(df.columns[1])
df.to_csv(filename)
return None
def plot_time_data(self, timeStart=None, timeEnd=None, units='s', show_fig=True):
"""
plot time data against voltage data.
Parameters
----------
timeStart : float, optional
The time to start plotting from.
By default it uses the first time point
timeEnd : float, optional
The time to finish plotting at.
By default it uses the last time point
units : string, optional
units of time to plot on the x axis - defaults to s
show_fig : bool, optional
If True runs plt.show() before returning figure
if False it just returns the figure object.
(the default is True, it shows the figure)
Returns
-------
fig : matplotlib.figure.Figure object
The figure object created
ax : matplotlib.axes.Axes object
The subplot object created
"""
unit_prefix = units[:-1] # removed the last char
if timeStart == None:
timeStart = self.timeStart
if timeEnd == None:
timeEnd = self.timeEnd
time = self.time.get_array()
StartIndex = _np.where(time == take_closest(time, timeStart))[0][0]
EndIndex = _np.where(time == take_closest(time, timeEnd))[0][0]
fig = _plt.figure(figsize=properties['default_fig_size'])
ax = fig.add_subplot(111)
ax.plot(unit_conversion(time[StartIndex:EndIndex], unit_prefix),
self.voltage[StartIndex:EndIndex])
ax.set_xlabel("time ({})".format(units))
ax.set_ylabel("voltage (V)")
ax.set_xlim([timeStart, timeEnd])
if show_fig == True:
_plt.show()
return fig, ax
def get_PSD(self, NPerSegment=1000000, window="hann", timeStart=None, timeEnd=None, override=False):
"""
Extracts the power spectral density (PSD) from the data.
Parameters
----------
NPerSegment : int, optional
Length of each segment used in scipy.welch
default = 1000000
window : str or tuple or array_like, optional
Desired window to use. See get_window for a list of windows
and required parameters. If window is array_like it will be
used directly as the window and its length will be used for
nperseg.
default = "hann"
Returns
-------
freqs : ndarray
Array containing the frequencies at which the PSD has been
calculated
PSD : ndarray
Array containing the value of the PSD at the corresponding
frequency value in V**2/Hz
"""
print("Calculating power spectral density")
if timeStart == None and timeEnd == None:
freqs, PSD = calc_PSD(self.voltage, self.SampleFreq, NPerSegment=NPerSegment)
self.PSD = PSD
self.freqs = freqs
else:
if timeStart == None:
timeStart = self.timeStart
if timeEnd == None:
timeEnd = self.timeEnd
time = self.time.get_array()
StartIndex = _np.where(time == take_closest(time, timeStart))[0][0]
EndIndex = _np.where(time == take_closest(time, timeEnd))[0][0]
if EndIndex == len(time) - 1:
EndIndex = EndIndex + 1 # so that it does not remove the last element
freqs, PSD = calc_PSD(self.voltage[StartIndex:EndIndex], self.SampleFreq, NPerSegment=NPerSegment)
if override == True:
self.freqs = freqs
self.PSD = PSD
return freqs, PSD
def plot_PSD(self, xlim=None, units="kHz", show_fig=True, timeStart=None, timeEnd=None, *args, **kwargs):
"""
plot the pulse spectral density.
Parameters
----------
xlim : array_like, optional
The x limits of the plotted PSD [LowerLimit, UpperLimit]
Default value is [0, SampleFreq/2]
units : string, optional
Units of frequency to plot on the x axis - defaults to kHz
show_fig : bool, optional
If True runs plt.show() before returning figure
if False it just returns the figure object.
(the default is True, it shows the figure)
Returns
-------
fig : matplotlib.figure.Figure object
The figure object created
ax : matplotlib.axes.Axes object
The subplot object created
"""
# self.get_PSD()
if timeStart == None and timeEnd == None:
freqs = self.freqs
PSD = self.PSD
else:
freqs, PSD = self.get_PSD(timeStart=timeStart, timeEnd=timeEnd)
unit_prefix = units[:-2]
if xlim == None:
xlim = [0, unit_conversion(self.SampleFreq/2, unit_prefix)]
fig = _plt.figure(figsize=properties['default_fig_size'])
ax = fig.add_subplot(111)
ax.semilogy(unit_conversion(freqs, unit_prefix), PSD, *args, **kwargs)
ax.set_xlabel("Frequency ({})".format(units))
ax.set_xlim(xlim)
ax.grid(which="major")
ax.set_ylabel("$S_{xx}$ ($V^2/Hz$)")
if show_fig == True:
_plt.show()
return fig, ax
def calc_area_under_PSD(self, lowerFreq, upperFreq):
"""
Sums the area under the PSD from lowerFreq to upperFreq.
Parameters
----------
lowerFreq : float
The lower limit of frequency to sum from
upperFreq : float
The upper limit of frequency to sum to
Returns
-------
AreaUnderPSD : float
The area under the PSD from lowerFreq to upperFreq
"""
Freq_startAreaPSD = take_closest(self.freqs, lowerFreq)
index_startAreaPSD = int(_np.where(self.freqs == Freq_startAreaPSD)[0][0])
Freq_endAreaPSD = take_closest(self.freqs, upperFreq)
index_endAreaPSD = int(_np.where(self.freqs == Freq_endAreaPSD)[0][0])
AreaUnderPSD = sum(self.PSD[index_startAreaPSD: index_endAreaPSD])
return AreaUnderPSD
def get_fit(self, TrapFreq, WidthOfPeakToFit, A_Initial=0.1e10, Gamma_Initial=400, silent=False, MakeFig=True, show_fig=True, plot_initial=True, timeStart=None, timeEnd=None, NPerSegment=1000000):
"""
Function that fits to a peak to the PSD to extract the
frequency, A factor and Gamma (damping) factor.
Parameters
----------
TrapFreq : float
The approximate trapping frequency to use initially
as the centre of the peak
WidthOfPeakToFit : float
The width of the peak to be fitted to. This limits the
region that the fitting function can see in order to
stop it from fitting to the wrong peak
A_Initial : float, optional
The initial value of the A parameter to use in fitting
Gamma_Initial : float, optional
The initial value of the Gamma parameter to use in fitting
Silent : bool, optional
Whether to print any output when running this function
defaults to False
MakeFig : bool, optional
Whether to construct and return the figure object showing
the fitting. defaults to True
show_fig : bool, optional
Whether to show the figure object when it has been created.
defaults to True
timeStart : float, optional
Time at which to start the data to use for fitting
timeEnd : float, optional
Time at which to end the data to use for fitting
Returns
-------
A : uncertainties.ufloat
Fitting constant A
A = γ**2*2*Γ_0*(K_b*T_0)/(π*m)
where:
γ = conversionFactor
Γ_0 = Damping factor due to environment
π = pi
OmegaTrap : uncertainties.ufloat
The trapping frequency in the z axis (in angular frequency)
Gamma : uncertainties.ufloat
The damping factor Gamma = Γ = Γ_0 + δΓ
where:
Γ_0 = Damping factor due to environment
δΓ = extra damping due to feedback or other effects
fig : matplotlib.figure.Figure object
figure object containing the plot
ax : matplotlib.axes.Axes object
axes with the data plotted of the:
- initial data
- smoothed data
- initial fit
- final fit
"""
if MakeFig == True:
Params, ParamsErr, fig, ax = fit_PSD(
self, WidthOfPeakToFit, TrapFreq, A_Initial, Gamma_Initial, MakeFig=MakeFig, show_fig=show_fig, plot_initial=plot_initial, timeStart=timeStart, timeEnd=timeEnd, NPerSegment=NPerSegment)
else:
Params, ParamsErr, _ , _ = fit_PSD(
self, WidthOfPeakToFit, TrapFreq, A_Initial, Gamma_Initial, MakeFig=MakeFig, show_fig=show_fig, plot_initial=plot_initial, timeStart=timeStart, timeEnd=timeEnd, NPerSegment=NPerSegment)
if silent == False:
print("\n")
print("A: {} +- {}% ".format(Params[0],
ParamsErr[0] / Params[0] * 100))
print(
"Trap Frequency: {} +- {}% ".format(Params[1], ParamsErr[1] / Params[1] * 100))
print(
"Big Gamma: {} +- {}% ".format(Params[2], ParamsErr[2] / Params[2] * 100))
self.A = _uncertainties.ufloat(Params[0], ParamsErr[0])
self.OmegaTrap = _uncertainties.ufloat(Params[1], ParamsErr[1])
self.Gamma = _uncertainties.ufloat(Params[2], ParamsErr[2])
if MakeFig == True:
return self.A, self.OmegaTrap, self.Gamma, fig, ax
else:
return self.A, self.OmegaTrap, self.Gamma, None, None
def get_fit_from_peak(self, lowerLimit, upperLimit, NumPointsSmoothing=1, silent=False, MakeFig=True, show_fig=True, plot_initial=True):
"""
Finds approximate values for the peaks central frequency, height,
and FWHM by looking for the heighest peak in the frequency range defined
by the input arguments. It then uses the central frequency as the trapping
frequency, peak height to approximate the A value and the FWHM to an approximate
the Gamma (damping) value.
Parameters
----------
lowerLimit : float
The lower frequency limit of the range in which it looks for a peak
upperLimit : float
The higher frequency limit of the range in which it looks for a peak
NumPointsSmoothing : float
The number of points of moving-average smoothing it applies before fitting the
peak.
Silent : bool, optional
Whether it prints the values fitted or is silent.
show_fig : bool, optional
Whether it makes and shows the figure object or not.
Returns
-------
OmegaTrap : ufloat
Trapping frequency
A : ufloat
A parameter
Gamma : ufloat
Gamma, the damping parameter
"""
lowerIndex = _np.where(self.freqs ==
take_closest(self.freqs, lowerLimit))[0][0]
upperIndex = _np.where(self.freqs ==
take_closest(self.freqs, upperLimit))[0][0]
if lowerIndex == upperIndex:
_warnings.warn("range is too small, returning NaN", UserWarning)
val = _uncertainties.ufloat(_np.NaN, _np.NaN)
return val, val, val, val, val
MaxPSD = max(self.PSD[lowerIndex:upperIndex])
centralIndex = _np.where(self.PSD == MaxPSD)[0][0]
CentralFreq = self.freqs[centralIndex]
approx_A = MaxPSD * 1e16 # 1e16 was calibrated for a number of saves to be approximately the correct conversion factor between the height of the PSD and the A factor in the fitting
MinPSD = min(self.PSD[lowerIndex:upperIndex])
# need to get this on log scale
HalfMax = MinPSD + (MaxPSD - MinPSD) / 2
try:
LeftSideOfPeakIndex = _np.where(self.PSD ==
take_closest(self.PSD[lowerIndex:centralIndex], HalfMax))[0][0]
LeftSideOfPeak = self.freqs[LeftSideOfPeakIndex]
except IndexError:
_warnings.warn("range is too small, returning NaN", UserWarning)
val = _uncertainties.ufloat(_np.NaN, _np.NaN)
return val, val, val, val, val
try:
RightSideOfPeakIndex = _np.where(self.PSD ==
take_closest(self.PSD[centralIndex:upperIndex], HalfMax))[0][0]
RightSideOfPeak = self.freqs[RightSideOfPeakIndex]
except IndexError:
_warnings.warn("range is too small, returning NaN", UserWarning)
val = _uncertainties.ufloat(_np.NaN, _np.NaN)
return val, val, val, val, val
FWHM = RightSideOfPeak - LeftSideOfPeak
approx_Gamma = FWHM/4
try:
A, OmegaTrap, Gamma, fig, ax \
= self.get_fit(CentralFreq,
(upperLimit-lowerLimit)/2,
A_Initial=approx_A,
Gamma_Initial=approx_Gamma,
silent=silent,
MakeFig=MakeFig,
show_fig=show_fig,
plot_initial=plot_initial)
except (TypeError, ValueError) as e:
_warnings.warn("range is too small to fit, returning NaN", UserWarning)
val = _uncertainties.ufloat(_np.NaN, _np.NaN)
return val, val, val, val, val
OmegaTrap = self.OmegaTrap
A = self.A
Gamma = self.Gamma
omegaArray = 2 * pi * \
self.freqs[LeftSideOfPeakIndex:RightSideOfPeakIndex]
PSDArray = self.PSD[LeftSideOfPeakIndex:RightSideOfPeakIndex]
return OmegaTrap, A, Gamma, fig, ax
def get_fit_auto(self, CentralFreq, MaxWidth=15000, MinWidth=500, WidthIntervals=500, MakeFig=True, show_fig=True, silent=False, plot_initial=True):
"""
Tries a range of regions to search for peaks and runs the one with the least error
and returns the parameters with the least errors.
Parameters
----------
CentralFreq : float
The central frequency to use for the fittings.
MaxWidth : float, optional
The maximum bandwidth to use for the fitting of the peaks.
MinWidth : float, optional
The minimum bandwidth to use for the fitting of the peaks.
WidthIntervals : float, optional
The intervals to use in going between the MaxWidth and MinWidth.
show_fig : bool, optional
Whether to plot and show the final (best) fitting or not.
Returns
-------
OmegaTrap : ufloat
Trapping frequency
A : ufloat
A parameter
Gamma : ufloat
Gamma, the damping parameter
fig : matplotlib.figure.Figure object
The figure object created showing the PSD of the data
with the fit
ax : matplotlib.axes.Axes object
The axes object created showing the PSD of the data
with the fit
"""
MinTotalSumSquaredError = _np.infty
for Width in _np.arange(MaxWidth, MinWidth - WidthIntervals, -WidthIntervals):
try:
OmegaTrap, A, Gamma,_ , _ \
= self.get_fit_from_peak(
CentralFreq - Width / 2,
CentralFreq + Width / 2,
silent=True,
MakeFig=False,
show_fig=False)
except RuntimeError:
_warnings.warn("Couldn't find good fit with width {}".format(
Width), RuntimeWarning)
val = _uncertainties.ufloat(_np.NaN, _np.NaN)
OmegaTrap = val
A = val
Gamma = val
TotalSumSquaredError = (
A.std_dev / A.n)**2 + (Gamma.std_dev / Gamma.n)**2 + (OmegaTrap.std_dev / OmegaTrap.n)**2
#print("totalError: {}".format(TotalSumSquaredError))
if TotalSumSquaredError < MinTotalSumSquaredError:
MinTotalSumSquaredError = TotalSumSquaredError
BestWidth = Width
if silent != True:
print("found best")
try:
OmegaTrap, A, Gamma, fig, ax \
= self.get_fit_from_peak(CentralFreq - BestWidth / 2,
CentralFreq + BestWidth / 2,
MakeFig=MakeFig,
show_fig=show_fig,
silent=silent,
plot_initial=plot_initial)
except UnboundLocalError:
raise ValueError("A best width was not found, try increasing the number of widths tried by either decreasing WidthIntervals or MinWidth or increasing MaxWidth")
OmegaTrap = self.OmegaTrap
A = self.A
Gamma = self.Gamma
self.FTrap = OmegaTrap/(2*pi)
return OmegaTrap, A, Gamma, fig, ax
def calc_gamma_from_variance_autocorrelation_fit(self, NumberOfOscillations, GammaGuess=None, silent=False, MakeFig=True, show_fig=True):
"""
Calculates the total damping, i.e. Gamma, by splitting the time trace
into chunks of NumberOfOscillations oscillations and calculated the
variance of each of these chunks. This array of varainces is then used
for the autocorrleation. The autocorrelation is fitted with an exponential
relaxation function and the function returns the parameters with errors.
Parameters
----------
NumberOfOscillations : int
The number of oscillations each chunk of the timetrace
used to calculate the variance should contain.
GammaGuess : float, optional
Inital guess for BigGamma (in radians)
Silent : bool, optional
Whether it prints the values fitted or is silent.
MakeFig : bool, optional
Whether to construct and return the figure object showing
the fitting. defaults to True
show_fig : bool, optional
Whether to show the figure object when it has been created.
defaults to True
Returns
-------
Gamma : ufloat
Big Gamma, the total damping in radians
fig : matplotlib.figure.Figure object
The figure object created showing the autocorrelation
of the data with the fit
ax : matplotlib.axes.Axes object
The axes object created showing the autocorrelation
of the data with the fit
"""
try:
SplittedArraySize = int(self.SampleFreq/self.FTrap.n) * NumberOfOscillations
except KeyError:
ValueError('You forgot to do the spectrum fit to specify self.FTrap exactly.')
VoltageArraySize = len(self.voltage)
SnippetsVariances = _np.var(self.voltage[:VoltageArraySize-_np.mod(VoltageArraySize,SplittedArraySize)].reshape(-1,SplittedArraySize),axis=1)
autocorrelation = calc_autocorrelation(SnippetsVariances)
time = _np.array(range(len(autocorrelation))) * SplittedArraySize / self.SampleFreq
if GammaGuess==None:
Gamma_Initial = (time[4]-time[0])/(autocorrelation[0]-autocorrelation[4])
else:
Gamma_Initial = GammaGuess
if MakeFig == True:
Params, ParamsErr, fig, ax = fit_autocorrelation(
autocorrelation, time, Gamma_Initial, MakeFig=MakeFig, show_fig=show_fig)
else:
Params, ParamsErr, _ , _ = fit_autocorrelation(
autocorrelation, time, Gamma_Initial, MakeFig=MakeFig, show_fig=show_fig)
if silent == False:
print("\n")
print(
"Big Gamma: {} +- {}% ".format(Params[0], ParamsErr[0] / Params[0] * 100))
Gamma = _uncertainties.ufloat(Params[0], ParamsErr[0])
if MakeFig == True:
return Gamma, fig, ax
else:
return Gamma, None, None
def calc_gamma_from_energy_autocorrelation_fit(self, GammaGuess=None, silent=False, MakeFig=True, show_fig=True):
"""
Calculates the total damping, i.e. Gamma, by calculating the energy each
point in time. This energy array is then used for the autocorrleation.
The autocorrelation is fitted with an exponential relaxation function and
the function returns the parameters with errors.
Parameters
----------
GammaGuess : float, optional
Inital guess for BigGamma (in radians)
silent : bool, optional
Whether it prints the values fitted or is silent.
MakeFig : bool, optional
Whether to construct and return the figure object showing
the fitting. defaults to True
show_fig : bool, optional
Whether to show the figure object when it has been created.
defaults to True
Returns
-------
Gamma : ufloat
Big Gamma, the total damping in radians
fig : matplotlib.figure.Figure object
The figure object created showing the autocorrelation
of the data with the fit
ax : matplotlib.axes.Axes object
The axes object created showing the autocorrelation
of the data with the fit
"""
autocorrelation = calc_autocorrelation(self.voltage[:-1]**2*self.OmegaTrap.n**2+(_np.diff(self.voltage)*self.SampleFreq)**2)
time = self.time.get_array()[:len(autocorrelation)]
if GammaGuess==None:
Gamma_Initial = (time[4]-time[0])/(autocorrelation[0]-autocorrelation[4])
else:
Gamma_Initial = GammaGuess
if MakeFig == True:
Params, ParamsErr, fig, ax = fit_autocorrelation(
autocorrelation, time, Gamma_Initial, MakeFig=MakeFig, show_fig=show_fig)
else:
Params, ParamsErr, _ , _ = fit_autocorrelation(
autocorrelation, time, Gamma_Initial, MakeFig=MakeFig, show_fig=show_fig)
if silent == False:
print("\n")
print(
"Big Gamma: {} +- {}% ".format(Params[0], ParamsErr[0] / Params[0] * 100))
Gamma = _uncertainties.ufloat(Params[0], ParamsErr[0])
if MakeFig == True:
return Gamma, fig, ax
else:
return Gamma, None, None
def calc_gamma_from_position_autocorrelation_fit(self, GammaGuess=None, FreqTrapGuess=None, silent=False, MakeFig=True, show_fig=True):
"""
Calculates the total damping, i.e. Gamma, by calculating the autocorrleation
of the position-time trace. The autocorrelation is fitted with an exponential
relaxation function derived in Tongcang Li's 2013 thesis (DOI: 10.1007/978-1-4614-6031-2)
and the function (equation 4.20 in the thesis) returns the parameters with errors.
Parameters
----------
GammaGuess : float, optional
Inital guess for BigGamma (in radians)
FreqTrapGuess : float, optional
Inital guess for the trapping Frequency in Hz
silent : bool, optional
Whether it prints the values fitted or is silent.
MakeFig : bool, optional
Whether to construct and return the figure object showing
the fitting. defaults to True
show_fig : bool, optional
Whether to show the figure object when it has been created.
defaults to True
Returns
-------
Gamma : ufloat
Big Gamma, the total damping in radians
OmegaTrap : ufloat
Trapping frequency in radians
fig : matplotlib.figure.Figure object
The figure object created showing the autocorrelation
of the data with the fit
ax : matplotlib.axes.Axes object
The axes object created showing the autocorrelation
of the data with the fit
"""
autocorrelation = calc_autocorrelation(self.voltage)
time = self.time.get_array()[:len(autocorrelation)]
if GammaGuess==None:
Gamma_Initial = (autocorrelation[0]-autocorrelation[int(self.SampleFreq/self.FTrap.n)])/(time[int(self.SampleFreq/self.FTrap.n)]-time[0])*2*_np.pi
else:
Gamma_Initial = GammaGuess
if FreqTrapGuess==None:
FreqTrap_Initial = self.FTrap.n
else:
FreqTrap_Initial = FreqTrapGuess
if MakeFig == True:
Params, ParamsErr, fig, ax = fit_autocorrelation(
autocorrelation, time, Gamma_Initial, FreqTrap_Initial, method='position', MakeFig=MakeFig, show_fig=show_fig)
else:
Params, ParamsErr, _ , _ = fit_autocorrelation(
autocorrelation, time, Gamma_Initial, FreqTrap_Initial, method='position', MakeFig=MakeFig, show_fig=show_fig)
if silent == False:
print("\n")
print(
"Big Gamma: {} +- {}% ".format(Params[0], ParamsErr[0] / Params[0] * 100))
print(
"Trap Frequency: {} +- {}% ".format(Params[1], ParamsErr[1] / Params[1] * 100))
Gamma = _uncertainties.ufloat(Params[0], ParamsErr[0])
OmegaTrap = _uncertainties.ufloat(Params[1], ParamsErr[1])
if MakeFig == True:
return Gamma, OmegaTrap, fig, ax
else:
return Gamma, OmegaTrap, None, None
def extract_parameters(self, P_mbar, P_Error, method="chang"):
"""
Extracts the Radius, mass and Conversion factor for a particle.
Parameters
----------
P_mbar : float
The pressure in mbar when the data was taken.
P_Error : float
The error in the pressure value (as a decimal e.g. 15% = 0.15)
Returns
-------
Radius : uncertainties.ufloat
The radius of the particle in m
Mass : uncertainties.ufloat
The mass of the particle in kg
ConvFactor : uncertainties.ufloat
The conversion factor between volts/m
"""
[R, M, ConvFactor], [RErr, MErr, ConvFactorErr] = \
extract_parameters(P_mbar, P_Error,
self.A.n, self.A.std_dev,
self.Gamma.n, self.Gamma.std_dev,
method = method)
self.Radius = _uncertainties.ufloat(R, RErr)
self.Mass = _uncertainties.ufloat(M, MErr)
self.ConvFactor = _uncertainties.ufloat(ConvFactor, ConvFactorErr)
return self.Radius, self.Mass, self.ConvFactor
def extract_ZXY_motion(self, ApproxZXYFreqs, uncertaintyInFreqs, ZXYPeakWidths, subSampleFraction=1, NPerSegmentPSD=1000000, MakeFig=True, show_fig=True):
"""
Extracts the x, y and z signals (in volts) from the voltage signal. Does this by finding the highest peaks in the signal about the approximate frequencies, using the uncertaintyinfreqs parameter as the width it searches. It then uses the ZXYPeakWidths to construct bandpass IIR filters for each frequency and filtering them. If too high a sample frequency has been used to collect the data scipy may not be able to construct a filter good enough, in this case increasing the subSampleFraction may be nessesary.
Parameters
----------
ApproxZXYFreqs : array_like
A sequency containing 3 elements, the approximate
z, x and y frequency respectively.
uncertaintyInFreqs : float
The uncertainty in the z, x and y frequency respectively.
ZXYPeakWidths : array_like
A sequency containing 3 elements, the widths of the
z, x and y frequency peaks respectively.
subSampleFraction : int, optional
How much to sub-sample the data by before filtering,
effectively reducing the sample frequency by this
fraction.
NPerSegmentPSD : int, optional
NPerSegment to pass to scipy.signal.welch to calculate the PSD
show_fig : bool, optional
Whether to show the figures produced of the PSD of
the original signal along with the filtered x, y and z.
Returns
-------
self.zVolts : ndarray
The z signal in volts extracted by bandpass IIR filtering
self.xVolts : ndarray
The x signal in volts extracted by bandpass IIR filtering
self.yVolts : ndarray
The y signal in volts extracted by bandpass IIR filtering
time : ndarray
The array of times corresponding to the above 3 arrays
fig : matplotlib.figure.Figure object
figure object containing a plot of the PSD of the original
signal with the z, x and y filtered signals
ax : matplotlib.axes.Axes object
axes object corresponding to the above figure
"""
[zf, xf, yf] = ApproxZXYFreqs
zf, xf, yf = get_ZXY_freqs(
self, zf, xf, yf, bandwidth=uncertaintyInFreqs)
[zwidth, xwidth, ywidth] = ZXYPeakWidths
self.zVolts, self.xVolts, self.yVolts, time, fig, ax = get_ZXY_data(
self, zf, xf, yf, subSampleFraction, zwidth, xwidth, ywidth, MakeFig=MakeFig, show_fig=show_fig, NPerSegmentPSD=NPerSegmentPSD)
return self.zVolts, self.xVolts, self.yVolts, time, fig, ax
def filter_data(self, freq, FractionOfSampleFreq=1, PeakWidth=10000,
filterImplementation="filtfilt",
timeStart=None, timeEnd=None,
NPerSegmentPSD=1000000,
PyCUDA=False, MakeFig=True, show_fig=True):
"""
filter out data about a central frequency with some bandwidth using an IIR filter.
Parameters
----------
freq : float
The frequency of the peak of interest in the PSD
FractionOfSampleFreq : integer, optional
The fraction of the sample frequency to sub-sample the data by.
This sometimes needs to be done because a filter with the appropriate
frequency response may not be generated using the sample rate at which
the data was taken. Increasing this number means the x, y and z signals
produced by this function will be sampled at a lower rate but a higher
number means a higher chance that the filter produced will have a nice
frequency response.
PeakWidth : float, optional
The width of the pass-band of the IIR filter to be generated to
filter the peak. Defaults to 10KHz
filterImplementation : string, optional
filtfilt or lfilter - use scipy.filtfilt or lfilter
ifft - uses built in IFFT_filter
default: filtfilt
timeStart : float, optional
Starting time for filtering. Defaults to start of time data.
timeEnd : float, optional
Ending time for filtering. Defaults to end of time data.
NPerSegmentPSD : int, optional
NPerSegment to pass to scipy.signal.welch to calculate the PSD
PyCUDA : bool, optional
Only important for the 'ifft'-method
If True, uses PyCUDA to accelerate the FFT and IFFT
via using your NVIDIA-GPU
If False, performs FFT and IFFT with conventional
scipy.fftpack
MakeFig : bool, optional
If True - generate figure showing filtered and unfiltered PSD
Defaults to True.
show_fig : bool, optional
If True - plot unfiltered and filtered PSD
Defaults to True.
Returns
-------
timedata : ndarray
Array containing the time data
FiletedData : ndarray
Array containing the filtered signal in volts with time.
fig : matplotlib.figure.Figure object
The figure object created showing the PSD of the filtered
and unfiltered signal
ax : matplotlib.axes.Axes object
The axes object created showing the PSD of the filtered
and unfiltered signal
"""
if timeStart == None:
timeStart = self.timeStart
if timeEnd == None:
timeEnd = self.timeEnd
time = self.time.get_array()
StartIndex = _np.where(time == take_closest(time, timeStart))[0][0]
EndIndex = _np.where(time == take_closest(time, timeEnd))[0][0]
input_signal = self.voltage[StartIndex: EndIndex][0::FractionOfSampleFreq]
SAMPLEFREQ = self.SampleFreq / FractionOfSampleFreq
if filterImplementation == "filtfilt" or filterImplementation == "lfilter":
if filterImplementation == "filtfilt":
ApplyFilter = scipy.signal.filtfilt
elif filterImplementation == "lfilter":
ApplyFilter = scipy.signal.lfilter
b, a = make_butterworth_bandpass_b_a(freq, PeakWidth, SAMPLEFREQ)
print("filtering data")
filteredData = ApplyFilter(b, a, input_signal)
if(_np.isnan(filteredData).any()):
raise ValueError(
"Value Error: FractionOfSampleFreq must be higher, a sufficiently small sample frequency should be used to produce a working IIR filter.")
elif filterImplementation == "ifft":
filteredData = IFFT_filter(input_signal, SAMPLEFREQ, freq-PeakWidth/2, freq+PeakWidth/2, PyCUDA = PyCUDA)
else:
raise ValueError("filterImplementation must be one of [filtfilt, lfilter, ifft] you entered: {}".format(filterImplementation))
if MakeFig == True:
f, PSD = scipy.signal.welch(
input_signal, SAMPLEFREQ, nperseg=NPerSegmentPSD)
f_filtdata, PSD_filtdata = scipy.signal.welch(filteredData, SAMPLEFREQ, nperseg=NPerSegmentPSD)
fig, ax = _plt.subplots(figsize=properties["default_fig_size"])
ax.plot(self.freqs, self.PSD, label='original data')
ax.plot(f, PSD, label='subsampled data')
ax.plot(f_filtdata, PSD_filtdata, label="filtered data")
ax.legend(loc="best")
ax.semilogy()
ax.set_xlim([freq - PeakWidth, freq + PeakWidth])
else:
fig = None
ax = None
if show_fig == True:
_plt.show()
timedata = time[StartIndex: EndIndex][0::FractionOfSampleFreq]
return timedata, filteredData, fig, ax
def plot_phase_space_sns(self, freq, ConvFactor, PeakWidth=10000, FractionOfSampleFreq=1, kind="hex", timeStart=None, timeEnd =None, PointsOfPadding=500, units="nm", logscale=False, cmap=None, marginalColor=None, gridsize=200, show_fig=True, ShowPSD=False, alpha=0.5, *args, **kwargs):
"""
Plots the phase space of a peak in the PSD.
Parameters
----------
freq : float
The frequenecy of the peak (Trapping frequency of the dimension of interest)
ConvFactor : float (or ufloat)
The conversion factor between Volts and Meters
PeakWidth : float, optional
The width of the peak. Defaults to 10KHz
FractionOfSampleFreq : int, optional
The fraction of the sample freq to use to filter the data.
Defaults to 1.
kind : string, optional
kind of plot to draw - pass to jointplot from seaborne
timeStart : float, optional
Starting time for data from which to calculate the phase space.
Defaults to start of time data.
timeEnd : float, optional
Ending time for data from which to calculate the phase space.
Defaults to start of time data.
PointsOfPadding : float, optional
How many points of the data at the beginning and end to disregard for plotting
the phase space, to remove filtering artifacts. Defaults to 500.
units : string, optional
Units of position to plot on the axis - defaults to nm
cmap : matplotlib.colors.ListedColormap, optional
cmap to use for plotting the jointplot
marginalColor : string, optional
color to use for marginal plots
gridsize : int, optional
size of the grid to use with kind="hex"
show_fig : bool, optional
Whether to show the figure before exiting the function
Defaults to True.
ShowPSD : bool, optional
Where to show the PSD of the unfiltered and the
filtered signal used to make the phase space
plot. Defaults to False.
Returns
-------
fig : matplotlib.figure.Figure object
figure object containing the phase space plot
JP : seaborn.jointplot object
joint plot object containing the phase space plot
"""
if cmap == None:
if logscale == True:
cmap = properties['default_log_cmap']
else:
cmap = properties['default_linear_cmap']
unit_prefix = units[:-1]
_, PosArray, VelArray = self.calc_phase_space(freq, ConvFactor, PeakWidth=PeakWidth, FractionOfSampleFreq=FractionOfSampleFreq, timeStart=timeStart, timeEnd=timeEnd, PointsOfPadding=PointsOfPadding, ShowPSD=ShowPSD)
_plt.close('all')
PosArray = unit_conversion(PosArray, unit_prefix) # converts m to units required (nm by default)
VelArray = unit_conversion(VelArray, unit_prefix) # converts m/s to units required (nm/s by default)
VarPos = _np.var(PosArray)
VarVel = _np.var(VelArray)
MaxPos = _np.max(PosArray)
MaxVel = _np.max(VelArray)
if MaxPos > MaxVel / (2 * pi * freq):
_plotlimit = MaxPos * 1.1
else:
_plotlimit = MaxVel / (2 * pi * freq) * 1.1
print("Plotting Phase Space")
if marginalColor == None:
try:
marginalColor = tuple((cmap.colors[len(cmap.colors)/2][:-1]))
except AttributeError:
try:
marginalColor = cmap(2)
except:
marginalColor = properties['default_base_color']
if kind == "hex": # gridsize can only be passed if kind="hex"
JP1 = _sns.jointplot(_pd.Series(PosArray[1:], name="$z$ ({}) \n filepath=%s".format(units) % (self.filepath)),
_pd.Series(VelArray / (2 * pi * freq), name="$v_z$/$\omega$ ({})".format(units)),
stat_func=None,
xlim=[-_plotlimit, _plotlimit],
ylim=[-_plotlimit, _plotlimit],
size=max(properties['default_fig_size']),
kind=kind,
marginal_kws={'hist_kws': {'log': logscale},},
cmap=cmap,
color=marginalColor,
gridsize=gridsize,
alpha=alpha,
*args,
**kwargs,
)
else:
JP1 = _sns.jointplot(_pd.Series(PosArray[1:], name="$z$ ({}) \n filepath=%s".format(units) % (self.filepath)),
_pd.Series(VelArray / (2 * pi * freq), name="$v_z$/$\omega$ ({})".format(units)),
stat_func=None,
xlim=[-_plotlimit, _plotlimit],
ylim=[-_plotlimit, _plotlimit],
size=max(properties['default_fig_size']),
kind=kind,
marginal_kws={'hist_kws': {'log': logscale},},
cmap=cmap,
color=marginalColor,
alpha=alpha,
*args,
**kwargs,
)
fig = JP1.fig
if show_fig == True:
print("Showing Phase Space")
_plt.show()
return fig, JP1
def plot_phase_space(self, freq, ConvFactor, PeakWidth=10000, FractionOfSampleFreq=1, timeStart=None, timeEnd =None, PointsOfPadding=500, units="nm", show_fig=True, ShowPSD=False, xlabel='', ylabel='', *args, **kwargs):
unit_prefix = units[:-1]
xlabel = xlabel + "({})".format(units)
ylabel = ylabel + "({})".format(units)
_, PosArray, VelArray = self.calc_phase_space(freq, ConvFactor, PeakWidth=PeakWidth, FractionOfSampleFreq=FractionOfSampleFreq, timeStart=timeStart, timeEnd=timeEnd, PointsOfPadding=PointsOfPadding, ShowPSD=ShowPSD)
PosArray = unit_conversion(PosArray, unit_prefix) # converts m to units required (nm by default)
VelArray = unit_conversion(VelArray, unit_prefix) # converts m/s to units required (nm/s by default)
VelArray = VelArray/(2*pi*freq) # converst nm/s to nm/radian
PosArray = PosArray[1:]
fig, axscatter, axhistx, axhisty, cb = _qplots.joint_plot(PosArray, VelArray, *args, **kwargs)
axscatter.set_xlabel(xlabel)
axscatter.set_ylabel(ylabel)
if show_fig == True:
_plt.show()
return fig, axscatter, axhistx, axhisty, cb
def calc_phase_space(self, freq, ConvFactor, PeakWidth=10000, FractionOfSampleFreq=1, timeStart=None, timeEnd =None, PointsOfPadding=500, ShowPSD=False):
"""
Calculates the position and velocity (in m) for use in plotting the phase space distribution.
Parameters
----------
freq : float
The frequenecy of the peak (Trapping frequency of the dimension of interest)
ConvFactor : float (or ufloat)
The conversion factor between Volts and Meters
PeakWidth : float, optional
The width of the peak. Defaults to 10KHz
FractionOfSampleFreq : int, optional
The fraction of the sample freq to use to filter the data.
Defaults to 1.
timeStart : float, optional
Starting time for data from which to calculate the phase space.
Defaults to start of time data.
timeEnd : float, optional
Ending time for data from which to calculate the phase space.
Defaults to start of time data.
PointsOfPadding : float, optional
How many points of the data at the beginning and end to disregard for plotting
the phase space, to remove filtering artifacts. Defaults to 500
ShowPSD : bool, optional
Where to show the PSD of the unfiltered and the filtered signal used
to make the phase space plot. Defaults to False.
*args, **kwargs : optional
args and kwargs passed to qplots.joint_plot
Returns
-------
time : ndarray
time corresponding to position and velocity
PosArray : ndarray
Array of position of the particle in time
VelArray : ndarray
Array of velocity of the particle in time
"""
_, Pos, fig, ax = self.filter_data(
freq, FractionOfSampleFreq, PeakWidth, MakeFig=ShowPSD, show_fig=ShowPSD, timeStart=timeStart, timeEnd=timeEnd)
time = self.time.get_array()
if timeStart != None:
StartIndex = _np.where(time == take_closest(time, timeStart))[0][0]
else:
StartIndex = 0
if timeEnd != None:
EndIndex = _np.where(time == take_closest(time, timeEnd))[0][0]
else:
EndIndex = -1
Pos = Pos[PointsOfPadding : -PointsOfPadding+1]
time = time[StartIndex:EndIndex][::FractionOfSampleFreq][PointsOfPadding : -PointsOfPadding+1]
if type(ConvFactor) == _uncertainties.core.Variable:
conv = ConvFactor.n
else:
conv = ConvFactor
PosArray = Pos / conv # converts V to m
VelArray = _np.diff(PosArray) * (self.SampleFreq / FractionOfSampleFreq) # calcs velocity (in m/s) by differtiating position
return time, PosArray, VelArray
|
class DataObject():
'''
Creates an object containing data and all it's properties.
Attributes
----------
filepath : string
filepath to the file containing the data used to initialise
this particular instance of the DataObject class
filename : string
filename of the file containing the data used to initialise
this particular instance of the DataObject class
time : frange
Contains the time data as an frange object. Can get a generator
or array of this object.
voltage : ndarray
Contains the voltage data in Volts
SampleFreq : sample frequency used to sample the data (when it was
taken by the oscilloscope)
freqs : ndarray
Contains the frequencies corresponding to the PSD (Pulse Spectral
Density)
PSD : ndarray
Contains the values for the PSD (Pulse Spectral Density) as calculated
at each frequency contained in freqs
'''
def __init__(self, filepath=None, voltage=None, time=None, SampleFreq=None, timeStart=None, RelativeChannelNo=None, PointsToLoad=-1, calcPSD=True, NPerSegmentPSD=1000000, NormaliseByMonitorOutput=False):
'''
Parameters
----------
filepath : string, optional
The filepath to the data file to initialise this object instance.
voltage : ndarray, optional
Array of voltages recorded by the measurement device, to be used as an alternative to filepath when the file to be loaded is not supported natively.
If this argument is passed, one of either the time or SampleFreq variables must be provided
time : ndarray, optional
Array of times corresponding to the voltage measurements, only used if voltage is passed
SampleFreq : float, optional
The sample frequency of the voltage measurements, if the time data is not provided, only used if voltage is passed or
if loading a .dat file produced by the labview NI5122 daq card, where it is used to manually specify the sample frequency
timeStart : float, optional
The start time of the time data
RelativeChannelNo : int, optional
If loading a .bin file produced by the Saleae datalogger, used to specify
the channel number
If loading a .dat file produced by the labview NI5122 daq card, used to
specifiy the channel number if two channels where saved, if left None with
.dat files it will assume that the file to load only contains one channel.
If NormaliseByMonitorOutput is True then RelativeChannelNo specifies the
monitor channel for loading a .dat file produced by the labview NI5122 daq card.
PointsToLoad : int, optional
Number of first points to read. -1 means all points (i.e. the complete file)
WORKS WITH NI5122 DATA SO FAR ONLY!!!
calcPSD : bool, optional
Whether to calculate the PSD upon loading the file, can take some time
off the loading and reduce memory usage if frequency space info is not required
NPerSegmentPSD : int, optional
NPerSegment to pass to scipy.signal.welch to calculate the PSD
NormaliseByMonitorOutput : bool, optional
If True the particle signal trace will be divided by the monitor output, which is
specified by the channel number set in the RelativeChannelNo parameter.
WORKS WITH NI5122 DATA SO FAR ONLY!!!
Initialisation - assigns values to the following attributes:
- filepath
- filename
- filedir
- time
- voltage
- freqs
- PSD
'''
pass
def load_time_data_from_signal(self, voltage, time=None, SampleFreq=None, timeStart=None):
'''
Loads the voltage and time data provided as arrays.
Must provide the voltage signal and either provide the time data, or the sample frequency.
Sets the instance properties:
self.voltage
self.SampleFreq
self.timeStart
self.timeEnd
self.timeStep
self.time
Parameters
----------
voltage : ndarray
Array of voltages recorded by the measurement device
time : ndarray, optional
Array of times corresponding to the voltage measurements
SampleFreq : float, optional
The sample frequency of the voltage measurements, if the time data is not provided
timeStart : float, optional
The start time of the time data
'''
pass
def load_time_data_from_signal(self, voltage, time=None, SampleFreq=None, timeStart=None):
'''
Loads the time and voltage data and the wave description from the associated file.
Sets the instance properties:
self.voltage
self.SampleFreq
self.timeStart
self.timeEnd
self.timeStep
self.time
Parameters
----------
RelativeChannelNo : int|str, optional
Channel to load data from (number or letter) used in following file formats:
- saleae data files - number
- .dat file produced by the labview NI5122 daq card - number
- .mat files from MATLAB version < 7.3 - letter
If loading a .dat file produced by the labview NI5122 daq card, used to
specifiy the channel number if two channels where saved, if left None with
.dat files it will assume that the file to load only contains one channel.
If NormaliseByMonitorOutput is True then RelativeChannelNo specifies the
monitor channel for loading a .dat file produced by the labview NI5122 daq card.
SampleFreq : float, optional
Manual selection of sample frequency for loading labview NI5122 daq files
PointsToLoad : int, optional
Number of first points to read. -1 means all points (i.e., the complete file)
WORKS WITH NI5122 DATA SO FAR ONLY!!!
NormaliseByMonitorOutput : bool, optional
If True the particle signal trace will be divided by the monitor output, which is
specified by the channel number set in the RelativeChannelNo parameter.
WORKS WITH NI5122 DATA SO FAR ONLY!!!
'''
pass
def get_time_data(self, timeStart=None, timeEnd=None):
'''
Gets the time and voltage data.
Parameters
----------
timeStart : float, optional
The time get data from.
By default it uses the first time point
timeEnd : float, optional
The time to finish getting data from.
By default it uses the last time point
Returns
-------
time : ndarray
array containing the value of time (in seconds) at which the
voltage is sampled
voltage : ndarray
array containing the sampled voltages
'''
pass
def write_time_data(self, filename):
'''
Writes time data to a csv file.
Parameters
----------
filename : string
filename of csv file to be written
'''
pass
def plot_time_data(self, timeStart=None, timeEnd=None, units='s', show_fig=True):
'''
plot time data against voltage data.
Parameters
----------
timeStart : float, optional
The time to start plotting from.
By default it uses the first time point
timeEnd : float, optional
The time to finish plotting at.
By default it uses the last time point
units : string, optional
units of time to plot on the x axis - defaults to s
show_fig : bool, optional
If True runs plt.show() before returning figure
if False it just returns the figure object.
(the default is True, it shows the figure)
Returns
-------
fig : matplotlib.figure.Figure object
The figure object created
ax : matplotlib.axes.Axes object
The subplot object created
'''
pass
def get_PSD(self, NPerSegment=1000000, window="hann", timeStart=None, timeEnd=None, override=False):
'''
Extracts the power spectral density (PSD) from the data.
Parameters
----------
NPerSegment : int, optional
Length of each segment used in scipy.welch
default = 1000000
window : str or tuple or array_like, optional
Desired window to use. See get_window for a list of windows
and required parameters. If window is array_like it will be
used directly as the window and its length will be used for
nperseg.
default = "hann"
Returns
-------
freqs : ndarray
Array containing the frequencies at which the PSD has been
calculated
PSD : ndarray
Array containing the value of the PSD at the corresponding
frequency value in V**2/Hz
'''
pass
def plot_PSD(self, xlim=None, units="kHz", show_fig=True, timeStart=None, timeEnd=None, *args, **kwargs):
'''
plot the pulse spectral density.
Parameters
----------
xlim : array_like, optional
The x limits of the plotted PSD [LowerLimit, UpperLimit]
Default value is [0, SampleFreq/2]
units : string, optional
Units of frequency to plot on the x axis - defaults to kHz
show_fig : bool, optional
If True runs plt.show() before returning figure
if False it just returns the figure object.
(the default is True, it shows the figure)
Returns
-------
fig : matplotlib.figure.Figure object
The figure object created
ax : matplotlib.axes.Axes object
The subplot object created
'''
pass
def calc_area_under_PSD(self, lowerFreq, upperFreq):
'''
Sums the area under the PSD from lowerFreq to upperFreq.
Parameters
----------
lowerFreq : float
The lower limit of frequency to sum from
upperFreq : float
The upper limit of frequency to sum to
Returns
-------
AreaUnderPSD : float
The area under the PSD from lowerFreq to upperFreq
'''
pass
def get_fit(self, TrapFreq, WidthOfPeakToFit, A_Initial=0.1e10, Gamma_Initial=400, silent=False, MakeFig=True, show_fig=True, plot_initial=True, timeStart=None, timeEnd=None, NPerSegment=1000000):
'''
Function that fits to a peak to the PSD to extract the
frequency, A factor and Gamma (damping) factor.
Parameters
----------
TrapFreq : float
The approximate trapping frequency to use initially
as the centre of the peak
WidthOfPeakToFit : float
The width of the peak to be fitted to. This limits the
region that the fitting function can see in order to
stop it from fitting to the wrong peak
A_Initial : float, optional
The initial value of the A parameter to use in fitting
Gamma_Initial : float, optional
The initial value of the Gamma parameter to use in fitting
Silent : bool, optional
Whether to print any output when running this function
defaults to False
MakeFig : bool, optional
Whether to construct and return the figure object showing
the fitting. defaults to True
show_fig : bool, optional
Whether to show the figure object when it has been created.
defaults to True
timeStart : float, optional
Time at which to start the data to use for fitting
timeEnd : float, optional
Time at which to end the data to use for fitting
Returns
-------
A : uncertainties.ufloat
Fitting constant A
A = γ**2*2*Γ_0*(K_b*T_0)/(π*m)
where:
γ = conversionFactor
Γ_0 = Damping factor due to environment
π = pi
OmegaTrap : uncertainties.ufloat
The trapping frequency in the z axis (in angular frequency)
Gamma : uncertainties.ufloat
The damping factor Gamma = Γ = Γ_0 + δΓ
where:
Γ_0 = Damping factor due to environment
δΓ = extra damping due to feedback or other effects
fig : matplotlib.figure.Figure object
figure object containing the plot
ax : matplotlib.axes.Axes object
axes with the data plotted of the:
- initial data
- smoothed data
- initial fit
- final fit
'''
pass
def get_fit_from_peak(self, lowerLimit, upperLimit, NumPointsSmoothing=1, silent=False, MakeFig=True, show_fig=True, plot_initial=True):
'''
Finds approximate values for the peaks central frequency, height,
and FWHM by looking for the heighest peak in the frequency range defined
by the input arguments. It then uses the central frequency as the trapping
frequency, peak height to approximate the A value and the FWHM to an approximate
the Gamma (damping) value.
Parameters
----------
lowerLimit : float
The lower frequency limit of the range in which it looks for a peak
upperLimit : float
The higher frequency limit of the range in which it looks for a peak
NumPointsSmoothing : float
The number of points of moving-average smoothing it applies before fitting the
peak.
Silent : bool, optional
Whether it prints the values fitted or is silent.
show_fig : bool, optional
Whether it makes and shows the figure object or not.
Returns
-------
OmegaTrap : ufloat
Trapping frequency
A : ufloat
A parameter
Gamma : ufloat
Gamma, the damping parameter
'''
pass
def get_fit_auto(self, CentralFreq, MaxWidth=15000, MinWidth=500, WidthIntervals=500, MakeFig=True, show_fig=True, silent=False, plot_initial=True):
'''
Tries a range of regions to search for peaks and runs the one with the least error
and returns the parameters with the least errors.
Parameters
----------
CentralFreq : float
The central frequency to use for the fittings.
MaxWidth : float, optional
The maximum bandwidth to use for the fitting of the peaks.
MinWidth : float, optional
The minimum bandwidth to use for the fitting of the peaks.
WidthIntervals : float, optional
The intervals to use in going between the MaxWidth and MinWidth.
show_fig : bool, optional
Whether to plot and show the final (best) fitting or not.
Returns
-------
OmegaTrap : ufloat
Trapping frequency
A : ufloat
A parameter
Gamma : ufloat
Gamma, the damping parameter
fig : matplotlib.figure.Figure object
The figure object created showing the PSD of the data
with the fit
ax : matplotlib.axes.Axes object
The axes object created showing the PSD of the data
with the fit
'''
pass
def calc_gamma_from_variance_autocorrelation_fit(self, NumberOfOscillations, GammaGuess=None, silent=False, MakeFig=True, show_fig=True):
'''
Calculates the total damping, i.e. Gamma, by splitting the time trace
into chunks of NumberOfOscillations oscillations and calculated the
variance of each of these chunks. This array of varainces is then used
for the autocorrleation. The autocorrelation is fitted with an exponential
relaxation function and the function returns the parameters with errors.
Parameters
----------
NumberOfOscillations : int
The number of oscillations each chunk of the timetrace
used to calculate the variance should contain.
GammaGuess : float, optional
Inital guess for BigGamma (in radians)
Silent : bool, optional
Whether it prints the values fitted or is silent.
MakeFig : bool, optional
Whether to construct and return the figure object showing
the fitting. defaults to True
show_fig : bool, optional
Whether to show the figure object when it has been created.
defaults to True
Returns
-------
Gamma : ufloat
Big Gamma, the total damping in radians
fig : matplotlib.figure.Figure object
The figure object created showing the autocorrelation
of the data with the fit
ax : matplotlib.axes.Axes object
The axes object created showing the autocorrelation
of the data with the fit
'''
pass
def calc_gamma_from_energy_autocorrelation_fit(self, GammaGuess=None, silent=False, MakeFig=True, show_fig=True):
'''
Calculates the total damping, i.e. Gamma, by calculating the energy each
point in time. This energy array is then used for the autocorrleation.
The autocorrelation is fitted with an exponential relaxation function and
the function returns the parameters with errors.
Parameters
----------
GammaGuess : float, optional
Inital guess for BigGamma (in radians)
silent : bool, optional
Whether it prints the values fitted or is silent.
MakeFig : bool, optional
Whether to construct and return the figure object showing
the fitting. defaults to True
show_fig : bool, optional
Whether to show the figure object when it has been created.
defaults to True
Returns
-------
Gamma : ufloat
Big Gamma, the total damping in radians
fig : matplotlib.figure.Figure object
The figure object created showing the autocorrelation
of the data with the fit
ax : matplotlib.axes.Axes object
The axes object created showing the autocorrelation
of the data with the fit
'''
pass
def calc_gamma_from_position_autocorrelation_fit(self, GammaGuess=None, FreqTrapGuess=None, silent=False, MakeFig=True, show_fig=True):
'''
Calculates the total damping, i.e. Gamma, by calculating the autocorrleation
of the position-time trace. The autocorrelation is fitted with an exponential
relaxation function derived in Tongcang Li's 2013 thesis (DOI: 10.1007/978-1-4614-6031-2)
and the function (equation 4.20 in the thesis) returns the parameters with errors.
Parameters
----------
GammaGuess : float, optional
Inital guess for BigGamma (in radians)
FreqTrapGuess : float, optional
Inital guess for the trapping Frequency in Hz
silent : bool, optional
Whether it prints the values fitted or is silent.
MakeFig : bool, optional
Whether to construct and return the figure object showing
the fitting. defaults to True
show_fig : bool, optional
Whether to show the figure object when it has been created.
defaults to True
Returns
-------
Gamma : ufloat
Big Gamma, the total damping in radians
OmegaTrap : ufloat
Trapping frequency in radians
fig : matplotlib.figure.Figure object
The figure object created showing the autocorrelation
of the data with the fit
ax : matplotlib.axes.Axes object
The axes object created showing the autocorrelation
of the data with the fit
'''
pass
def extract_parameters(self, P_mbar, P_Error, method="chang"):
'''
Extracts the Radius, mass and Conversion factor for a particle.
Parameters
----------
P_mbar : float
The pressure in mbar when the data was taken.
P_Error : float
The error in the pressure value (as a decimal e.g. 15% = 0.15)
Returns
-------
Radius : uncertainties.ufloat
The radius of the particle in m
Mass : uncertainties.ufloat
The mass of the particle in kg
ConvFactor : uncertainties.ufloat
The conversion factor between volts/m
'''
pass
def extract_ZXY_motion(self, ApproxZXYFreqs, uncertaintyInFreqs, ZXYPeakWidths, subSampleFraction=1, NPerSegmentPSD=1000000, MakeFig=True, show_fig=True):
'''
Extracts the x, y and z signals (in volts) from the voltage signal. Does this by finding the highest peaks in the signal about the approximate frequencies, using the uncertaintyinfreqs parameter as the width it searches. It then uses the ZXYPeakWidths to construct bandpass IIR filters for each frequency and filtering them. If too high a sample frequency has been used to collect the data scipy may not be able to construct a filter good enough, in this case increasing the subSampleFraction may be nessesary.
Parameters
----------
ApproxZXYFreqs : array_like
A sequency containing 3 elements, the approximate
z, x and y frequency respectively.
uncertaintyInFreqs : float
The uncertainty in the z, x and y frequency respectively.
ZXYPeakWidths : array_like
A sequency containing 3 elements, the widths of the
z, x and y frequency peaks respectively.
subSampleFraction : int, optional
How much to sub-sample the data by before filtering,
effectively reducing the sample frequency by this
fraction.
NPerSegmentPSD : int, optional
NPerSegment to pass to scipy.signal.welch to calculate the PSD
show_fig : bool, optional
Whether to show the figures produced of the PSD of
the original signal along with the filtered x, y and z.
Returns
-------
self.zVolts : ndarray
The z signal in volts extracted by bandpass IIR filtering
self.xVolts : ndarray
The x signal in volts extracted by bandpass IIR filtering
self.yVolts : ndarray
The y signal in volts extracted by bandpass IIR filtering
time : ndarray
The array of times corresponding to the above 3 arrays
fig : matplotlib.figure.Figure object
figure object containing a plot of the PSD of the original
signal with the z, x and y filtered signals
ax : matplotlib.axes.Axes object
axes object corresponding to the above figure
'''
pass
def filter_data(self, freq, FractionOfSampleFreq=1, PeakWidth=10000,
filterImplementation="filtfilt",
timeStart=None, timeEnd=None,
NPerSegmentPSD=1000000,
PyCUDA=False, MakeFig=True, show_fig=True):
'''
filter out data about a central frequency with some bandwidth using an IIR filter.
Parameters
----------
freq : float
The frequency of the peak of interest in the PSD
FractionOfSampleFreq : integer, optional
The fraction of the sample frequency to sub-sample the data by.
This sometimes needs to be done because a filter with the appropriate
frequency response may not be generated using the sample rate at which
the data was taken. Increasing this number means the x, y and z signals
produced by this function will be sampled at a lower rate but a higher
number means a higher chance that the filter produced will have a nice
frequency response.
PeakWidth : float, optional
The width of the pass-band of the IIR filter to be generated to
filter the peak. Defaults to 10KHz
filterImplementation : string, optional
filtfilt or lfilter - use scipy.filtfilt or lfilter
ifft - uses built in IFFT_filter
default: filtfilt
timeStart : float, optional
Starting time for filtering. Defaults to start of time data.
timeEnd : float, optional
Ending time for filtering. Defaults to end of time data.
NPerSegmentPSD : int, optional
NPerSegment to pass to scipy.signal.welch to calculate the PSD
PyCUDA : bool, optional
Only important for the 'ifft'-method
If True, uses PyCUDA to accelerate the FFT and IFFT
via using your NVIDIA-GPU
If False, performs FFT and IFFT with conventional
scipy.fftpack
MakeFig : bool, optional
If True - generate figure showing filtered and unfiltered PSD
Defaults to True.
show_fig : bool, optional
If True - plot unfiltered and filtered PSD
Defaults to True.
Returns
-------
timedata : ndarray
Array containing the time data
FiletedData : ndarray
Array containing the filtered signal in volts with time.
fig : matplotlib.figure.Figure object
The figure object created showing the PSD of the filtered
and unfiltered signal
ax : matplotlib.axes.Axes object
The axes object created showing the PSD of the filtered
and unfiltered signal
'''
pass
def plot_phase_space_sns(self, freq, ConvFactor, PeakWidth=10000, FractionOfSampleFreq=1, kind="hex", timeStart=None, timeEnd =None, PointsOfPadding=500, units="nm", logscale=False, cmap=None, marginalColor=None, gridsize=200, show_fig=True, ShowPSD=False, alpha=0.5, *args, **kwargs):
'''
Plots the phase space of a peak in the PSD.
Parameters
----------
freq : float
The frequenecy of the peak (Trapping frequency of the dimension of interest)
ConvFactor : float (or ufloat)
The conversion factor between Volts and Meters
PeakWidth : float, optional
The width of the peak. Defaults to 10KHz
FractionOfSampleFreq : int, optional
The fraction of the sample freq to use to filter the data.
Defaults to 1.
kind : string, optional
kind of plot to draw - pass to jointplot from seaborne
timeStart : float, optional
Starting time for data from which to calculate the phase space.
Defaults to start of time data.
timeEnd : float, optional
Ending time for data from which to calculate the phase space.
Defaults to start of time data.
PointsOfPadding : float, optional
How many points of the data at the beginning and end to disregard for plotting
the phase space, to remove filtering artifacts. Defaults to 500.
units : string, optional
Units of position to plot on the axis - defaults to nm
cmap : matplotlib.colors.ListedColormap, optional
cmap to use for plotting the jointplot
marginalColor : string, optional
color to use for marginal plots
gridsize : int, optional
size of the grid to use with kind="hex"
show_fig : bool, optional
Whether to show the figure before exiting the function
Defaults to True.
ShowPSD : bool, optional
Where to show the PSD of the unfiltered and the
filtered signal used to make the phase space
plot. Defaults to False.
Returns
-------
fig : matplotlib.figure.Figure object
figure object containing the phase space plot
JP : seaborn.jointplot object
joint plot object containing the phase space plot
'''
pass
def plot_phase_space_sns(self, freq, ConvFactor, PeakWidth=10000, FractionOfSampleFreq=1, kind="hex", timeStart=None, timeEnd =None, PointsOfPadding=500, units="nm", logscale=False, cmap=None, marginalColor=None, gridsize=200, show_fig=True, ShowPSD=False, alpha=0.5, *args, **kwargs):
pass
def calc_phase_space(self, freq, ConvFactor, PeakWidth=10000, FractionOfSampleFreq=1, timeStart=None, timeEnd =None, PointsOfPadding=500, ShowPSD=False):
'''
Calculates the position and velocity (in m) for use in plotting the phase space distribution.
Parameters
----------
freq : float
The frequenecy of the peak (Trapping frequency of the dimension of interest)
ConvFactor : float (or ufloat)
The conversion factor between Volts and Meters
PeakWidth : float, optional
The width of the peak. Defaults to 10KHz
FractionOfSampleFreq : int, optional
The fraction of the sample freq to use to filter the data.
Defaults to 1.
timeStart : float, optional
Starting time for data from which to calculate the phase space.
Defaults to start of time data.
timeEnd : float, optional
Ending time for data from which to calculate the phase space.
Defaults to start of time data.
PointsOfPadding : float, optional
How many points of the data at the beginning and end to disregard for plotting
the phase space, to remove filtering artifacts. Defaults to 500
ShowPSD : bool, optional
Where to show the PSD of the unfiltered and the filtered signal used
to make the phase space plot. Defaults to False.
*args, **kwargs : optional
args and kwargs passed to qplots.joint_plot
Returns
-------
time : ndarray
time corresponding to position and velocity
PosArray : ndarray
Array of position of the particle in time
VelArray : ndarray
Array of velocity of the particle in time
'''
pass
| 22 | 21 | 66 | 6 | 31 | 30 | 6 | 1 | 0 | 16 | 0 | 0 | 21 | 21 | 21 | 21 | 1,436 | 157 | 656 | 193 | 630 | 655 | 531 | 186 | 509 | 28 | 0 | 4 | 117 |
7,543 |
AshleySetter/optoanalysis
|
AshleySetter_optoanalysis/optoanalysis/optoanalysis/optoanalysis.py
|
optoanalysis.optoanalysis.ORGTableData
|
class ORGTableData():
"""
Class for reading in general data from org-mode tables.
The table must be formatted as in the example below:
```
| RunNo | ColumnName1 | ColumnName2 |
|-------+-------------+-------------|
| 3 | 14 | 15e3 |
```
In this case the run number would be 3 and the ColumnName2-value would
be 15e3 (15000.0).
"""
def __init__(self, filename):
"""
Opens the org-mode table file, reads the file in as a string,
and runs parse_orgtable in order to read the pressure.
"""
with open(filename, 'r') as file:
fileContents = file.readlines()
self.ORGTableData = parse_orgtable(fileContents)
def get_value(self, ColumnName, RunNo):
"""
Retreives the value of the collumn named ColumnName associated
with a particular run number.
Parameters
----------
ColumnName : string
The name of the desired org-mode table's collumn
RunNo : int
The run number for which to retreive the pressure value
Returns
-------
Value : float
The value for the column's name and associated run number
"""
Value = float(self.ORGTableData[self.ORGTableData.RunNo == '{}'.format(
RunNo)][ColumnName])
return Value
|
class ORGTableData():
'''
Class for reading in general data from org-mode tables.
The table must be formatted as in the example below:
```
| RunNo | ColumnName1 | ColumnName2 |
|-------+-------------+-------------|
| 3 | 14 | 15e3 |
```
In this case the run number would be 3 and the ColumnName2-value would
be 15e3 (15000.0).
'''
def __init__(self, filename):
'''
Opens the org-mode table file, reads the file in as a string,
and runs parse_orgtable in order to read the pressure.
'''
pass
def get_value(self, ColumnName, RunNo):
'''
Retreives the value of the collumn named ColumnName associated
with a particular run number.
Parameters
----------
ColumnName : string
The name of the desired org-mode table's collumn
RunNo : int
The run number for which to retreive the pressure value
Returns
-------
Value : float
The value for the column's name and associated run number
'''
pass
| 3 | 3 | 15 | 2 | 4 | 9 | 1 | 3.22 | 0 | 1 | 0 | 0 | 2 | 1 | 2 | 2 | 48 | 10 | 9 | 7 | 6 | 29 | 8 | 6 | 5 | 1 | 0 | 1 | 2 |
7,544 |
AshleySetter/optoanalysis
|
AshleySetter_optoanalysis/optoanalysis/optoanalysis/thermo/thermo.py
|
optoanalysis.thermo.thermo.ThermoObject
|
class ThermoObject(optoanalysis.DataObject):
"""
Creates an object containing some data and all it's properties
for thermodynamics analysis.
Attributes
----------
SampleFreq : float
The sample frequency used in generating the data.
time : ndarray
Contains the time data in seconds
voltage : ndarray
Contains the voltage data in Volts - with noise and clean signals
all added together
SampleFreq : sample frequency used to sample the data (when it was
taken by the oscilloscope)
freqs : ndarray
Contains the frequencies corresponding to the PSD (Pulse Spectral
Density)
PSD : ndarray
Contains the values for the PSD (Pulse Spectral Density) as calculated
at each frequency contained in freqs
"""
def __init__(self, filepath, RelativeChannelNo=None, SampleFreq=None, PointsToLoad=-1, calcPSD=True, NPerSegmentPSD=1000000, NormaliseByMonitorOutput=False):
"""
Parameters
----------
filepath : string
The filepath to the data file to initialise this object instance.
RelativeChannelNo : int, optional
If loading a .bin file produced by the Saleae datalogger, used to specify
the channel number
If loading a .dat file produced by the labview NI5122 daq card, used to
specifiy the channel number if two channels where saved, if left None with
.dat files it will assume that the file to load only contains one channel.
If NormaliseByMonitorOutput is True then RelativeChannelNo specifies the
monitor channel for loading a .dat file produced by the labview NI5122 daq card.
SampleFreq : float, optional
If loading a .dat file produced by the labview NI5122 daq card, used to
manually specify the sample frequency
PointsToLoad : int, optional
Number of first points to read. -1 means all points (i.e. the complete file)
WORKS WITH NI5122 DATA SO FAR ONLY!!!
calcPSD : bool, optional
Whether to calculate the PSD upon loading the file, can take some time
off the loading and reduce memory usage if frequency space info is not required
NPerSegmentPSD : int, optional
NPerSegment to pass to scipy.signal.welch to calculate the PSD
NormaliseByMonitorOutput : bool, optional
If True the particle signal trace will be divided by the monitor output, which is
specified by the channel number set in the RelativeChannelNo parameter.
WORKS WITH NI5122 DATA SO FAR ONLY!!!
"""
super(ThermoObject, self).__init__(filepath, RelativeChannelNo=RelativeChannelNo, SampleFreq=SampleFreq, PointsToLoad=PointsToLoad, calcPSD=calcPSD, NPerSegmentPSD=NPerSegmentPSD,NormaliseByMonitorOutput=NormaliseByMonitorOutput) # calls the init func from optoanalysis
return None
@_jit
def calc_hamiltonian(self, mass, omega_array):
"""
Calculates the standard (pot+kin) Hamiltonian of your system.
Parameters
----------
mass : float
The mass of the particle in kg
omega_array : array
array which represents omega at every point in your time trace
and should therefore have the same length as self.position_data
Requirements
------------
self.position_data : array
Already filtered for the degree of freedom of intrest and converted into meters.
Returns
-------
Hamiltonian : array
The calculated Hamiltonian
"""
Kappa_t= mass*omega_array**2
self.E_pot = 0.5*Kappa_t*self.position_data**2
self.E_kin = 0.5*mass*(_np.insert(_np.diff(self.position_data), 0, (self.position_data[1]-self.position_data[0]))*self.SampleFreq)**2
self.Hamiltonian = self.E_pot + self.E_kin
return self.Hamiltonian
@_jit
def calc_phase_space_density(self, mass, omega_array, temperature_array):
"""
Calculates the partition function of your system at each point in time.
Parameters
----------
mass : float
The mass of the particle in kg
omega_array : array
array which represents omega at every point in your time trace
and should therefore have the same length as the Hamiltonian
temperature_array : array
array which represents the temperature at every point in your time trace
and should therefore have the same length as the Hamiltonian
Requirements
------------
self.position_data : array
Already filtered for the degree of freedom of intrest and converted into meters.
Returns:
-------
Phasespace-density : array
The Partition Function at every point in time over a given trap-frequency and temperature change.
"""
return self.calc_hamiltonian(mass, omega_array)/calc_partition_function(mass, omega_array,temperature_array)
@_jit
def extract_thermodynamic_quantities(self,temperature_array):
"""
Calculates the thermodynamic quantities of your system at each point in time.
Calculated Quantities: self.Q (heat),self.W (work), self.Delta_E_kin, self.Delta_E_pot
self.Delta_E (change of Hamiltonian),
Parameters
----------
temperature_array : array
array which represents the temperature at every point in your time trace
and should therefore have the same length as the Hamiltonian
Requirements
------------
execute calc_hamiltonian on the DataObject first
Returns:
-------
Q : array
The heat exchanged by the particle at every point in time over a given trap-frequency and temperature change.
W : array
The work "done" by the particle at every point in time over a given trap-frequency and temperature change.
"""
beta = 1/(_scipy.constants.Boltzmann*temperature_array)
self.Q = self.Hamiltonian*(_np.insert(_np.diff(beta),0,beta[1]-beta[0])*self.SampleFreq)
self.W = self.Hamiltonian-self.Q
self.Delta_E_kin = _np.diff(self.E_kin)*self.SampleFreq
self.Delta_E_pot = _np.diff(self.E_pot)*self.SampleFreq
self.Delta_E = _np.diff(self.Hamiltonian)*self.SampleFreq
return self.Q, self.W
def calc_mean_and_variance_of_variances(self, NumberOfOscillations):
"""
Calculates the mean and variance of a set of varainces.
This set is obtained by splitting the timetrace into chunks
of points with a length of NumberOfOscillations oscillations.
Parameters
----------
NumberOfOscillations : int
The number of oscillations each chunk of the timetrace
used to calculate the variance should contain.
Returns
-------
Mean : float
Variance : float
"""
SplittedArraySize = int(self.SampleFreq/self.FTrap.n) * NumberOfOscillations
VoltageArraySize = len(self.voltage)
SnippetsVariances = _np.var(self.voltage[:VoltageArraySize-_np.mod(VoltageArraySize,SplittedArraySize)].reshape(-1,SplittedArraySize),axis=1)
return _np.mean(SnippetsVariances), _np.var(SnippetsVariances)
|
class ThermoObject(optoanalysis.DataObject):
'''
Creates an object containing some data and all it's properties
for thermodynamics analysis.
Attributes
----------
SampleFreq : float
The sample frequency used in generating the data.
time : ndarray
Contains the time data in seconds
voltage : ndarray
Contains the voltage data in Volts - with noise and clean signals
all added together
SampleFreq : sample frequency used to sample the data (when it was
taken by the oscilloscope)
freqs : ndarray
Contains the frequencies corresponding to the PSD (Pulse Spectral
Density)
PSD : ndarray
Contains the values for the PSD (Pulse Spectral Density) as calculated
at each frequency contained in freqs
'''
def __init__(self, filepath, RelativeChannelNo=None, SampleFreq=None, PointsToLoad=-1, calcPSD=True, NPerSegmentPSD=1000000, NormaliseByMonitorOutput=False):
'''
Parameters
----------
filepath : string
The filepath to the data file to initialise this object instance.
RelativeChannelNo : int, optional
If loading a .bin file produced by the Saleae datalogger, used to specify
the channel number
If loading a .dat file produced by the labview NI5122 daq card, used to
specifiy the channel number if two channels where saved, if left None with
.dat files it will assume that the file to load only contains one channel.
If NormaliseByMonitorOutput is True then RelativeChannelNo specifies the
monitor channel for loading a .dat file produced by the labview NI5122 daq card.
SampleFreq : float, optional
If loading a .dat file produced by the labview NI5122 daq card, used to
manually specify the sample frequency
PointsToLoad : int, optional
Number of first points to read. -1 means all points (i.e. the complete file)
WORKS WITH NI5122 DATA SO FAR ONLY!!!
calcPSD : bool, optional
Whether to calculate the PSD upon loading the file, can take some time
off the loading and reduce memory usage if frequency space info is not required
NPerSegmentPSD : int, optional
NPerSegment to pass to scipy.signal.welch to calculate the PSD
NormaliseByMonitorOutput : bool, optional
If True the particle signal trace will be divided by the monitor output, which is
specified by the channel number set in the RelativeChannelNo parameter.
WORKS WITH NI5122 DATA SO FAR ONLY!!!
'''
pass
@_jit
def calc_hamiltonian(self, mass, omega_array):
'''
Calculates the standard (pot+kin) Hamiltonian of your system.
Parameters
----------
mass : float
The mass of the particle in kg
omega_array : array
array which represents omega at every point in your time trace
and should therefore have the same length as self.position_data
Requirements
------------
self.position_data : array
Already filtered for the degree of freedom of intrest and converted into meters.
Returns
-------
Hamiltonian : array
The calculated Hamiltonian
'''
pass
@_jit
def calc_phase_space_density(self, mass, omega_array, temperature_array):
'''
Calculates the partition function of your system at each point in time.
Parameters
----------
mass : float
The mass of the particle in kg
omega_array : array
array which represents omega at every point in your time trace
and should therefore have the same length as the Hamiltonian
temperature_array : array
array which represents the temperature at every point in your time trace
and should therefore have the same length as the Hamiltonian
Requirements
------------
self.position_data : array
Already filtered for the degree of freedom of intrest and converted into meters.
Returns:
-------
Phasespace-density : array
The Partition Function at every point in time over a given trap-frequency and temperature change.
'''
pass
@_jit
def extract_thermodynamic_quantities(self,temperature_array):
'''
Calculates the thermodynamic quantities of your system at each point in time.
Calculated Quantities: self.Q (heat),self.W (work), self.Delta_E_kin, self.Delta_E_pot
self.Delta_E (change of Hamiltonian),
Parameters
----------
temperature_array : array
array which represents the temperature at every point in your time trace
and should therefore have the same length as the Hamiltonian
Requirements
------------
execute calc_hamiltonian on the DataObject first
Returns:
-------
Q : array
The heat exchanged by the particle at every point in time over a given trap-frequency and temperature change.
W : array
The work "done" by the particle at every point in time over a given trap-frequency and temperature change.
'''
pass
def calc_mean_and_variance_of_variances(self, NumberOfOscillations):
'''
Calculates the mean and variance of a set of varainces.
This set is obtained by splitting the timetrace into chunks
of points with a length of NumberOfOscillations oscillations.
Parameters
----------
NumberOfOscillations : int
The number of oscillations each chunk of the timetrace
used to calculate the variance should contain.
Returns
-------
Mean : float
Variance : float
'''
pass
| 9 | 6 | 28 | 3 | 5 | 20 | 1 | 4.39 | 1 | 2 | 0 | 0 | 5 | 8 | 5 | 5 | 170 | 20 | 28 | 22 | 19 | 123 | 25 | 19 | 19 | 1 | 1 | 0 | 5 |
7,545 |
AshleySetter/optoanalysis
|
AshleySetter_optoanalysis/optoanalysis/optoanalysis/LeCroy/LeCroy.py
|
optoanalysis.LeCroy.LeCroy.HDO6104
|
class HDO6104:
"""
Class for communicating with the Teledyne LeCroy Oscilloscope.
"""
def __init__(self, address='152.78.194.16'):
"""
Initialises the connection to the Oscilloscope.
Parameters
----------
address : string
IP address of the oscilloscope.
"""
self.address = address
import vxi11
self.connection = vxi11.Instrument(address)
self.write = self.connection.write
self.read = self.connection.read
self.ask = self.connection.ask
self.read_raw = self.connection.read_raw
return None
def raw(self, channel=1):
"""
Reads the raw input from the oscilloscope.
Parameters
----------
channel : int
channel number of read
Returns
-------
rawData : bytes
raw binary data read from the oscilloscope
"""
self.waitOPC()
self.write('COMM_FORMAT DEF9,WORD,BIN')
self.write('C%u:WAVEFORM?' % channel)
return self.read_raw()
def data(self, channel=1):
"""
Reads the raw input from the scope and interprets it
returning the header information, time, voltage and
raw integers read with the ADC.
Parameters
----------
channel : int
channel number of read
Returns
-------
WAVEDESC : dict
dictionary containing some properties of the time trace and oscilloscope
settings extracted from the header file.
x : ndarray
The array of time values recorded by the oscilloscope
y : ndarray
The array of voltage values recorded by the oscilloscope
integers : ndarray
The array of raw integers recorded from the ADC and stored in the binary file
"""
raw = self.raw(channel) # Grab waveform from scope
return InterpretWaveform(raw)
def waitOPC(self):
"""
Waits for a response from the oscilloscope indicating that
processing is complete and it is ready to receive more commands.
Function sleeps until the oscilloscope is ready.
"""
from time import sleep
self.write('WAIT')
while not self.opc():
sleep(1)
def opc(self):
"""
Asks the oscilloscope if it is done processing data.
Returns
-------
IsDoneProcessing : bool
returns False if oscilloscope is still busy,
True is oscilloscope is done processing last commands.
"""
return self.ask('*OPC?')[-1] == '1'
|
class HDO6104:
'''
Class for communicating with the Teledyne LeCroy Oscilloscope.
'''
def __init__(self, address='152.78.194.16'):
'''
Initialises the connection to the Oscilloscope.
Parameters
----------
address : string
IP address of the oscilloscope.
'''
pass
def raw(self, channel=1):
'''
Reads the raw input from the oscilloscope.
Parameters
----------
channel : int
channel number of read
Returns
-------
rawData : bytes
raw binary data read from the oscilloscope
'''
pass
def data(self, channel=1):
'''
Reads the raw input from the scope and interprets it
returning the header information, time, voltage and
raw integers read with the ADC.
Parameters
----------
channel : int
channel number of read
Returns
-------
WAVEDESC : dict
dictionary containing some properties of the time trace and oscilloscope
settings extracted from the header file.
x : ndarray
The array of time values recorded by the oscilloscope
y : ndarray
The array of voltage values recorded by the oscilloscope
integers : ndarray
The array of raw integers recorded from the ADC and stored in the binary file
'''
pass
def waitOPC(self):
'''
Waits for a response from the oscilloscope indicating that
processing is complete and it is ready to receive more commands.
Function sleeps until the oscilloscope is ready.
'''
pass
def opc(self):
'''
Asks the oscilloscope if it is done processing data.
Returns
-------
IsDoneProcessing : bool
returns False if oscilloscope is still busy,
True is oscilloscope is done processing last commands.
'''
pass
| 6 | 6 | 16 | 1 | 5 | 10 | 1 | 2.2 | 0 | 0 | 0 | 0 | 5 | 6 | 5 | 5 | 90 | 11 | 25 | 15 | 17 | 55 | 25 | 15 | 17 | 2 | 0 | 1 | 6 |
7,546 |
Aslan11/wilos-cli
|
Aslan11_wilos-cli/wilos/writers.py
|
wilos.writers.Stdout
|
class Stdout(BaseWriter):
def __init__(self, output_file):
self.Result = namedtuple("Result",
"summary, temp, precipChange, humidity")
enums = dict(
RED="red",
BLUE="blue",
YELLOW="yellow",
GREEN="green",
WHITE="white",
)
self.colors = type('Enum', (), enums)
def live_weather(self, live_weather):
"""Prints the live weather in a pretty format"""
summary = live_weather['currently']['summary']
self.summary(summary)
click.echo()
def title(self, title):
"""Prints the title"""
title = " What's it like out side {0}? ".format(title)
click.secho("{:=^62}".format(title), fg=self.colors.WHITE)
click.echo()
def summary(self, summary):
"""Prints the ASCII Icon"""
if summary is not None:
if summary == 'Clear':
click.secho("""
________ \ | /
/ ____/ /__ ____ ______ .-.
/ / / / _ \/ __ `/ ___/ ‒ ( ) ‒
/ /___/ / __/ /_/ / / `-᾿
\____/_/\___/\__,_/_/ / | \\
""", fg=self.colors.YELLOW)
click.echo()
elif summary == 'Partly Cloudy':
click.secho("""
____ __ __ ________ __
/ __ \____ ______/ /_/ /_ __ / ____/ /___ __ ______/ /_ __ \ | /
/ /_/ / __ `/ ___/ __/ / / / / / / / / __ \/ / / / __ / / / / .-.
/ ____/ /_/ / / / /_/ / /_/ / / /___/ / /_/ / /_/ / /_/ / /_/ / ‒ ( .-.
/_/ \__,_/_/ \__/_/\__, / \____/_/\____/\__,_/\__,_/\__, / `( ).
/____/ /____/ / (___(__)
""", fg=self.colors.WHITE)
elif summary == 'Flurries':
click.secho("""
________ _ .--.
/ ____/ /_ ____________(_)__ _____ .-( ).
/ /_ / / / / / ___/ ___/ / _ \/ ___/ (___.__)__)
/ __/ / / /_/ / / / / / / __(__ ) * *
/_/ /_/\__,_/_/ /_/ /_/\___/____/ *
""", fg=self.colors.BLUE)
click.echo()
elif summary == 'Overcast' or summary == 'Mostly Cloudy':
click.secho("""
____ __
/ __ \_ _____ ______________ ______/ /_ .--.
/ / / / | / / _ \/ ___/ ___/ __ `/ ___/ __/ .( ).-.
/ /_/ /| |/ / __/ / / /__/ /_/ (__ ) /_ (___.__( ).
\____/ |___/\___/_/ \___/\__,_/____/\__/ (___(__)
""", fg=self.colors.WHITE)
click.echo()
elif summary == 'Snow':
click.secho("""
_____ .--.
/ ___/____ ____ _ __ .-( ).
\__ \/ __ \/ __ \ | /| / / (___.__)__)
___/ / / / / /_/ / |/ |/ / * * *
/____/_/ /_/\____/|__/|__/ * *
""", fg=self.colors.BLUE)
click.echo()
elif summary == 'Light Snow':
click.secho("""
__ _ __ __ _____
/ / (_)___ _/ /_ / /_ / ___/____ ____ _ __ .--.
/ / / / __ `/ __ \/ __/ \__ \/ __ \/ __ \ | /| / / .-( ).
/ /___/ / /_/ / / / / /_ ___/ / / / / /_/ / |/ |/ / (___.__)__)
/_____/_/\__, /_/ /_/\__/ /____/_/ /_/\____/|__/|__/ * * *
/____/
""", fg=self.colors.BLUE)
click.echo()
elif summary == 'Light Rain' or summary == 'Drizzle':
click.secho("""
__ _ __ __ ____ _
/ / (_)___ _/ /_ / /_ / __ \____ _(_)___ .--.
/ / / / __ `/ __ \/ __/ / /_/ / __ `/ / __ \ .-( ).
/ /___/ / /_/ / / / / /_ / _, _/ /_/ / / / / / (___.__)__)
/_____/_/\__, /_/ /_/\__/ /_/ |_|\__,_/_/_/ /_/ / / /
/____/
""", fg=self.colors.BLUE)
elif summary == 'Rain':
click.secho("""
____ _
/ __ \____ _(_)___ .--.
/ /_/ / __ `/ / __ \ .-( ).
/ _, _/ /_/ / / / / / (___.__)__)
/_/ |_|\__,_/_/_/ /_/ / / /
""", fg=self.colors.BLUE)
else:
click.secho("{:=^62}".format(str(summary)), fg=self.colors.GREEN)
|
class Stdout(BaseWriter):
def __init__(self, output_file):
pass
def live_weather(self, live_weather):
'''Prints the live weather in a pretty format'''
pass
def title(self, title):
'''Prints the title'''
pass
def summary(self, summary):
'''Prints the ASCII Icon'''
pass
| 5 | 3 | 31 | 6 | 24 | 1 | 3 | 0.03 | 1 | 3 | 0 | 0 | 4 | 2 | 4 | 6 | 127 | 28 | 96 | 9 | 91 | 3 | 30 | 9 | 25 | 10 | 2 | 2 | 13 |
7,547 |
AtomHash/evernode
|
AtomHash_evernode/evernode/middleware/route_before_middleware.py
|
evernode.middleware.route_before_middleware.RouteBeforeMiddleware
|
class RouteBeforeMiddleware:
""" add prefix to url """
wsgi_app = None
flask_app = None
prefix = None
def __init__(self, wsgi_app, flask_app, prefix=None):
self.wsgi_app = wsgi_app
self.flask_app = flask_app
self.prefix = flask_app.config['FORMATTED_PREFIX']
def __call__(self, environ, start_response):
with self.flask_app.app_context():
if environ['PATH_INFO'].strip('/').lower().startswith(self.prefix):
environ['PATH_INFO'] = \
environ['PATH_INFO'][len(self.prefix) + 1:]
environ['SCRIPT_NAME'] = self.prefix
return self.wsgi_app(environ, start_response)
if 404 in self.flask_app.error_handler_spec:
response = self.flask_app.error_handler_spec[404][NotFound](
NotFound, environ=environ)
start_response(
response.status(),
[('Content-Type', response.mimetype())])
return [response.content().encode()]
json_response = JsonResponse(404, environ=environ)
start_response(
json_response.status(),
[('Content-Type', json_response.mimetype())])
return [json_response.content().encode()]
|
class RouteBeforeMiddleware:
''' add prefix to url '''
def __init__(self, wsgi_app, flask_app, prefix=None):
pass
def __call__(self, environ, start_response):
pass
| 3 | 1 | 12 | 0 | 12 | 0 | 2 | 0.04 | 0 | 1 | 1 | 0 | 2 | 0 | 2 | 2 | 30 | 2 | 27 | 8 | 24 | 1 | 21 | 8 | 18 | 3 | 0 | 2 | 4 |
7,548 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/paginate.py
|
evernode.classes.paginate.Paginate
|
class Paginate:
""" Make pagination easy """
__filters = []
model = None
limit = None
max_pages = None
def __init__(self, model, limit):
self.__filters = []
self.model = model
self.limit = limit
self.max_pages = self.__total_pages()
def __total_pages(self) -> int:
""" Return max pages created by limit """
row_count = self.model.query.count()
if isinstance(row_count, int):
return int(row_count / self.limit)
return None
def __filter_query(self) -> str:
""" Generate a WHERE/AND string for SQL"""
filter_query = 'WHERE %s'
bind_values = {}
if not self.__filters:
return None
for filter in self.__filters:
bind = {
'name': Security.random_string(5),
'value': filter['value']}
filter_str = '%s %s :%s' % \
(filter['column'], filter['operator'], bind['name'])
bind_values[bind['name']] = bind['value']
filter_query = filter_query % (filter_str + ' AND %s')
return {
'query': filter_query.replace(' AND %s', ''),
'binds': bind_values}
def add_filter(self, column, operator, value):
self.__filters.append({
'column': column,
'operator': operator,
'value': value
})
return self
def page(self, page_number=0) -> list:
""" Return [models] by page_number based on limit """
# workaround flask-sqlalchemy/issues/516
offset = page_number * self.limit
sql = 'SELECT * FROM %s {} LIMIT :li OFFSET :o' \
% (self.model.__tablename__)
filter_query = self.__filter_query()
if filter_query is None:
sql = text(sql.format(''))
result = self.model.db.engine.execute(
sql, li=self.limit, o=offset)
else:
filter_query['binds']['li'] = self.limit
filter_query['binds']['o'] = offset
sql = text(sql.format(filter_query['query']))
result = self.model.db.engine.execute(
sql, **filter_query['binds'])
result_keys = result.keys()
result_models = []
for row in result:
model = self.model()
key_count = 0
for key in result_keys:
setattr(model, key, row[key_count])
key_count = key_count + 1
result_models.append(model)
return result_models
def links(self, base_link, current_page) -> dict:
""" Return JSON paginate links """
max_pages = self.max_pages - 1 if \
self.max_pages > 0 else self.max_pages
base_link = '/%s' % (base_link.strip("/"))
self_page = current_page
prev = current_page - 1 if current_page is not 0 else None
prev_link = '%s/page/%s/%s' % (base_link, prev, self.limit) if \
prev is not None else None
next = current_page + 1 if current_page < max_pages else None
next_link = '%s/page/%s/%s' % (base_link, next, self.limit) if \
next is not None else None
first = 0
last = max_pages
return {
'self': '%s/page/%s/%s' % (base_link, self_page, self.limit),
'prev': prev_link,
'next': next_link,
'first': '%s/page/%s/%s' % (base_link, first, self.limit),
'last': '%s/page/%s/%s' % (base_link, last, self.limit),
}
def json_paginate(self, base_url, page_number):
""" Return a dict for a JSON paginate """
data = self.page(page_number)
first_id = None
last_id = None
if data:
first_id = data[0].id
last_id = data[-1].id
return {
'meta': {
'total_pages': self.max_pages,
'first_id': first_id,
'last_id': last_id,
'current_page': page_number
},
'data': self.page(page_number),
'links': self.links(base_url, page_number)
}
|
class Paginate:
''' Make pagination easy '''
def __init__(self, model, limit):
pass
def __total_pages(self) -> int:
''' Return max pages created by limit '''
pass
def __filter_query(self) -> str:
''' Generate a WHERE/AND string for SQL'''
pass
def add_filter(self, column, operator, value):
pass
def page(self, page_number=0) -> list:
''' Return [models] by page_number based on limit '''
pass
def links(self, base_link, current_page) -> dict:
''' Return JSON paginate links '''
pass
def json_paginate(self, base_url, page_number):
''' Return a dict for a JSON paginate '''
pass
| 8 | 6 | 14 | 0 | 14 | 1 | 3 | 0.07 | 0 | 4 | 0 | 0 | 7 | 0 | 7 | 7 | 115 | 8 | 100 | 38 | 92 | 7 | 69 | 38 | 61 | 6 | 0 | 2 | 19 |
7,549 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/middleware.py
|
evernode.classes.middleware.Middleware
|
class Middleware:
""" Provides useful defaults for creating fast middleware """
status = False
response = Response
app = Flask
def __init__(self):
self.app = current_app
self.status = self.condition()
if self.status is False:
self.create_response()
def condition(self) -> bool:
""" A condition to validate or invalidate a request """
return False
def create_response(self):
""" Default response for if condition is false(invalid) """
self.response = JsonResponse(401)
|
class Middleware:
''' Provides useful defaults for creating fast middleware '''
def __init__(self):
pass
def condition(self) -> bool:
''' A condition to validate or invalidate a request '''
pass
def create_response(self):
''' Default response for if condition is false(invalid) '''
pass
| 4 | 3 | 4 | 0 | 3 | 1 | 1 | 0.23 | 0 | 2 | 1 | 2 | 3 | 0 | 3 | 3 | 19 | 3 | 13 | 7 | 9 | 3 | 13 | 7 | 9 | 2 | 0 | 1 | 4 |
7,550 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/load_modules.py
|
evernode.classes.load_modules.LoadModules
|
class LoadModules:
""" Loads folders with routes.py into application """
routes = []
app = None
evernode_app = None
def __init__(self, evernode_app):
self.evernode_app = evernode_app
self.app = evernode_app.app
self.construct_routes()
def __call__(self):
""" After init, add urls to flask app """
routes = self.routes
for route in routes:
call = importlib.import_module(route['callback']['module'])
class_to_call = getattr(call, route['callback']['class'])
method_to_call = getattr(
class_to_call, route['callback']['function'])
defaults = {}
if route['middleware'] is not None:
defaults = {'middleware': route['middleware']}
self.app.add_url_rule(
route['url'],
route['name'],
method_to_call,
methods=route['methods'],
defaults=defaults)
def make_route(self, route) -> dict:
""" Construct a route to be parsed into flask App """
middleware = route['middleware'] if 'middleware' in route else None
# added to ALL requests to support xhr cross-site requests
route['methods'].append('OPTIONS')
return {
'url': route['url'],
'name': route['name'],
'methods': route['methods'],
'middleware': middleware,
'callback': {
'module': route['function'].__module__,
'class': route['function'].__qualname__.rsplit('.', 1)[0],
'function': route['function'].__name__
}
}
def construct_routes(self):
""" Gets modules routes.py and converts to module imports """
modules = self.evernode_app.get_modules()
for module_name in modules:
with self.app.app_context():
module = importlib.import_module(
'modules.%s.routes' % (module_name))
for route in module.routes:
self.routes.append(self.make_route(route))
if self.app.config['DEBUG']:
print('--- Loaded Modules ---')
print("Loaded Modules: " + str(modules))
|
class LoadModules:
''' Loads folders with routes.py into application '''
def __init__(self, evernode_app):
pass
def __call__(self):
''' After init, add urls to flask app '''
pass
def make_route(self, route) -> dict:
''' Construct a route to be parsed into flask App '''
pass
def construct_routes(self):
''' Gets modules routes.py and converts to module imports '''
pass
| 5 | 4 | 12 | 0 | 11 | 1 | 3 | 0.1 | 0 | 2 | 0 | 0 | 4 | 0 | 4 | 4 | 58 | 4 | 49 | 19 | 44 | 5 | 32 | 19 | 27 | 4 | 0 | 3 | 10 |
7,551 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/load_language_files.py
|
evernode.classes.load_language_files.LoadLanguageFiles
|
class LoadLanguageFiles:
""" Loads modules and global language files """
app = None
evernode_app = None
module_packs = []
def __init__(self, evernode_app):
self.evernode_app = evernode_app
self.app = evernode_app.app
self.module_packs = []
self.app.config.update(dict(LANGUAGE_PACKS={}))
self.find_files()
def __call__(self):
""" after init parse each language file and save it """
for module_pack in self.module_packs:
language_pack = {module_pack['name']: {}}
current_pack = language_pack[module_pack['name']]
for language in module_pack['languages']:
current_pack.update({language: {}})
for file_pack in module_pack['file_packs']:
file = file_pack['file']
data = None
if os.path.exists(file):
data = Json.from_file(file)
else:
raise FileNotFoundError(file)
current_pack[file_pack['language']] \
.update({file_pack['name']: data})
self.app.config['LANGUAGE_PACKS'].update(language_pack)
def find_files(self):
""" Gets modules routes.py and converts to module imports """
modules = self.evernode_app.get_modules()
root_path = sys.path[0] if self.evernode_app.root_path is None \
else self.evernode_app.root_path
dirs = [dict(
dir=os.path.join(root_path, 'resources', 'lang'), module="root")]
for module_name in modules:
modules_folder = 'modules{}%s'.format(os.sep)
if module_name is not None:
modules_folder = modules_folder % (module_name.strip(os.sep))
else:
continue
path = os.path.join(
root_path, modules_folder, 'resources', 'lang')
if os.path.isdir(path):
dirs.append(dict(dir=path, module=module_name))
for dir in dirs:
module_pack = {
'name': dir['module'],
'languages': [],
'file_packs': []
}
for path, subdirs, files in os.walk(dir['dir']):
for subdir in subdirs:
module_pack['languages'].append(subdir)
for name in files:
if name.startswith('.'):
# ignore hidden files
continue
module_pack['file_packs'].append(dict(
file=os.path.join(path, name),
name=name.rsplit('.', 1)[0].lower(),
language=path.split("lang%s" % (os.sep), 1)[1].strip()
))
self.module_packs.append(module_pack)
for module_pack in self.module_packs:
module_pack['file_packs'] = \
list({v['file']: v for v in module_pack['file_packs']}
.values())
if self.app.config['DEBUG']:
print('--- Loaded Language Files ---')
print("Loaded Dirs: " + str(dirs))
print("Loaded Language Packs: " + str(self.module_packs))
|
class LoadLanguageFiles:
''' Loads modules and global language files '''
def __init__(self, evernode_app):
pass
def __call__(self):
''' after init parse each language file and save it '''
pass
def find_files(self):
''' Gets modules routes.py and converts to module imports '''
pass
| 4 | 3 | 22 | 0 | 21 | 1 | 6 | 0.06 | 0 | 5 | 1 | 0 | 3 | 0 | 3 | 3 | 75 | 3 | 68 | 25 | 64 | 4 | 52 | 25 | 48 | 12 | 0 | 4 | 18 |
7,552 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/jwt.py
|
evernode.classes.jwt.JWT
|
class JWT:
""" Gets request information to validate JWT """
token = None
app_key = None
app_secret = None
request = None
data = None
errors = []
def __init__(self):
self.token = None
self.data = None
self.errors = []
self.app_key = current_app.config['KEY']
self.app_secret = current_app.config['SECRET']
self.request = request
def get_http_token(self):
if 'Authorization' in request.headers:
token = request.headers['Authorization']
parsed_token = re.search('Bearer (.+)', token)
if parsed_token:
return parsed_token.group(1)
else:
return None
return None
def create_token(self, data, token_valid_for=180) -> str:
""" Create encrypted JWT """
jwt_token = jwt.encode({
'data': data,
'exp': datetime.utcnow() + timedelta(seconds=token_valid_for)},
self.app_secret, algorithm="HS256")
return Security.encrypt(jwt_token)
def verify_token(self, token) -> bool:
""" Verify encrypted JWT """
try:
self.data = jwt.decode(Security.decrypt(token), self.app_secret,
algorithms=["HS256"])
return True
except (Exception, BaseException) as error:
self.errors.append(error)
return False
return False
def verify_http_auth_token(self) -> bool:
""" Use request information to validate JWT """
authorization_token = self.get_http_token()
if authorization_token is not None:
if self.verify_token(authorization_token):
if self.data is not None:
self.data = self.data['data']
return True
return False
else:
return False
return False
def create_token_with_refresh_token(self, data, token_valid_for=180,
refresh_token_valid_for=86400):
""" Create an encrypted JWT with a refresh_token """
refresh_token = None
refresh_token = jwt.encode({
'exp':
datetime.utcnow() +
timedelta(seconds=refresh_token_valid_for)},
self.app_secret).decode("utf-8")
jwt_token = jwt.encode({
'data': data,
'refresh_token': refresh_token,
'exp': datetime.utcnow() + timedelta(seconds=token_valid_for)},
self.app_secret)
return Security.encrypt(jwt_token)
def verify_refresh_token(self, expired_token) -> bool:
""" Use request information to validate refresh JWT """
try:
decoded_token = jwt.decode(
Security.decrypt(expired_token),
self.app_secret,
options={'verify_exp': False})
if 'refresh_token' in decoded_token and \
decoded_token['refresh_token'] is not None:
try:
jwt.decode(decoded_token['refresh_token'], self.app_secret)
self.data = decoded_token
return True
except (Exception, BaseException) as error:
self.errors.append(error)
return False
except (Exception, BaseException) as error:
self.errors.append(error)
return False
return False
def verify_http_auth_refresh_token(self) -> bool:
""" Use expired token to check refresh token information """
authorization_token = self.get_http_token()
if authorization_token is not None:
if self.verify_refresh_token(authorization_token):
if self.data is not None:
self.data = self.data['data']
return True
return False
else:
return False
return False
|
class JWT:
''' Gets request information to validate JWT '''
def __init__(self):
pass
def get_http_token(self):
pass
def create_token(self, data, token_valid_for=180) -> str:
''' Create encrypted JWT '''
pass
def verify_token(self, token) -> bool:
''' Verify encrypted JWT '''
pass
def verify_http_auth_token(self) -> bool:
''' Use request information to validate JWT '''
pass
def create_token_with_refresh_token(self, data, token_valid_for=180,
refresh_token_valid_for=86400):
''' Create an encrypted JWT with a refresh_token '''
pass
def verify_refresh_token(self, expired_token) -> bool:
''' Use request information to validate refresh JWT '''
pass
def verify_http_auth_refresh_token(self) -> bool:
''' Use expired token to check refresh token information '''
pass
| 9 | 7 | 12 | 0 | 11 | 1 | 3 | 0.08 | 0 | 7 | 1 | 0 | 8 | 0 | 8 | 8 | 108 | 8 | 93 | 26 | 83 | 7 | 73 | 23 | 64 | 4 | 0 | 3 | 20 |
7,553 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/json_response.py
|
evernode.classes.json_response.JsonResponse
|
class JsonResponse(BaseResponse):
""" JsonResponse is a wrapper for BaseResponse """
__mimetype__ = "application/json; charset=utf-8"
def __init__(self, status_code=200, message=None, data=None, environ=None):
super().__init__(status_code, message=message,
data=data, environ=environ)
if message is None:
self.quick_response(status_code)
|
class JsonResponse(BaseResponse):
''' JsonResponse is a wrapper for BaseResponse '''
def __init__(self, status_code=200, message=None, data=None, environ=None):
pass
| 2 | 1 | 5 | 0 | 5 | 0 | 2 | 0.14 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 9 | 9 | 1 | 7 | 3 | 5 | 1 | 6 | 3 | 4 | 2 | 1 | 1 | 2 |
7,554 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/form_data.py
|
evernode.classes.form_data.FormData
|
class FormData:
json_form_data = None
field_arguments = []
file_arguments = []
values = {}
files = {}
def __init__(self):
self.field_arguments = []
self.file_arguments = []
self.values = {}
self.files = {}
self.json_form_data = self.get_json_form_data()
def get_json_form_data(self):
""" Load request Json Data, if any """
return request.get_json(silent=True, force=True)
def add_field(self, name, default=None, required=False, error=None):
""" Add a text/non-file field to parse for a value in the request """
if name is None:
return
self.field_arguments.append(dict(
name=name,
default=default,
required=required,
error=error))
def add_file(self, name, required=False, error=None, extensions=None):
""" Add a file field to parse on request (uploads) """
if name is None:
return
self.file_arguments.append(dict(
name=name,
required=required,
error=error,
extensions=extensions))
def file_save(self, name, filename=None, folder="", keep_ext=True) -> bool:
""" Easy save of a file """
if name in self.files:
file_object = self.files[name]
clean_filename = secure_filename(file_object.filename)
if filename is not None and keep_ext:
clean_filename = filename + ".%s" % \
(clean_filename.rsplit('.', 1)[1].lower())
elif filename is not None and not keep_ext:
clean_filename = filename
file_object.save(os.path.join(
current_app.config['UPLOADS']['FOLDER'],
folder, clean_filename))
return None
def parse(self, fail_callback=None):
""" Parse text fields and file fields for values and files """
# get text fields
for field in self.field_arguments:
self.values[field['name']] = self.__get_value(field['name'])
if self.values[field['name']] is None and field['required']:
if fail_callback is not None:
fail_callback()
self.__invalid_request(field['error'])
# get file fields
for file in self.file_arguments:
self.files[file['name']] = self.__get_file(file)
if self.files[file['name']] is None and file['required']:
if fail_callback is not None:
fail_callback()
self.__invalid_request(file['error'])
def __get_value(self, field_name):
""" Get request Json value by field name """
value = request.values.get(field_name)
if value is None:
if self.json_form_data is None:
value = None
elif field_name in self.json_form_data:
value = self.json_form_data[field_name]
return value
def __get_file(self, file):
""" Get request file and do a security check """
file_object = None
if file['name'] in request.files:
file_object = request.files[file['name']]
clean_filename = secure_filename(file_object.filename)
if clean_filename == '':
return file_object
if file_object and self.__allowed_extension(
clean_filename, file['extensions']):
return file_object
elif file['name'] not in request.files and file['required']:
return file_object
return file_object
def __allowed_extension(self, filename, extensions):
""" Check allowed file extensions """
allowed_extensions = current_app.config['UPLOADS']['EXTENSIONS']
if extensions is not None:
allowed_extensions = extensions
return '.' in filename and filename.rsplit('.', 1)[1].lower() in \
allowed_extensions
def __invalid_request(self, error):
""" Error response on failure """
# TODO: make this modifiable
error = {
'error': {
'message': error
}
}
abort(JsonResponse(status_code=400, data=error))
|
class FormData:
def __init__(self):
pass
def get_json_form_data(self):
''' Load request Json Data, if any '''
pass
def add_field(self, name, default=None, required=False, error=None):
''' Add a text/non-file field to parse for a value in the request '''
pass
def add_file(self, name, required=False, error=None, extensions=None):
''' Add a file field to parse on request (uploads) '''
pass
def file_save(self, name, filename=None, folder="", keep_ext=True) -> bool:
''' Easy save of a file '''
pass
def parse(self, fail_callback=None):
''' Parse text fields and file fields for values and files '''
pass
def __get_value(self, field_name):
''' Get request Json value by field name '''
pass
def __get_file(self, file):
''' Get request file and do a security check '''
pass
def __allowed_extension(self, filename, extensions):
''' Check allowed file extensions '''
pass
def __invalid_request(self, error):
''' Error response on failure '''
pass
| 11 | 9 | 10 | 0 | 8 | 1 | 3 | 0.13 | 0 | 3 | 1 | 0 | 10 | 0 | 10 | 10 | 112 | 10 | 90 | 24 | 79 | 12 | 70 | 24 | 59 | 7 | 0 | 3 | 29 |
7,555 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/fail2ban.py
|
evernode.classes.fail2ban.Fail2Ban
|
class Fail2Ban:
""" EverNode Fail2Ban """
__fail2ban_model = None
__location = None
__object_id = None
__ip = None
ban_for = None
max_attempts = None
def __init__(self, object_id=None, location="",
max_attempts=3, ip=None, ban_for=1800):
self.__object_id = object_id
self.ban_for = ban_for
self.max_attempts = max_attempts
self.__location = location
if ip is None:
self.__ip = request.remote_addr
self.__fail2ban_model = Fail2BanModel.where_unique(
self.__ip,
self.__object_id,
self.__location)
def object_id(self, object_id):
self.__object_id = object_id
self.__fail2ban_model = Fail2BanModel.where_unique(
self.__ip,
self.__object_id,
self.__location)
def add_attempt(self, number=1):
if self.__fail2ban_model is None:
self.__fail2ban_model = Fail2BanModel()
self.__fail2ban_model.ip = self.__ip
self.__fail2ban_model.object_id = self.__object_id
self.__fail2ban_model.location = self.__location
self.__fail2ban_model.attempts = 0
self.__fail2ban_model.add_attempt_or_ban(
number,
self.max_attempts,
valid_for=self.ban_for)
def clear(self, object_id, ip=None):
if ip is None:
ip = request.remote_addr
Fail2BanModel.delete_where_unique(ip, object_id, self.__location)
def is_banned(self):
if self.__fail2ban_model is None:
return False
return self.__fail2ban_model.is_banned()
|
class Fail2Ban:
''' EverNode Fail2Ban '''
def __init__(self, object_id=None, location="",
max_attempts=3, ip=None, ban_for=1800):
pass
def object_id(self, object_id):
pass
def add_attempt(self, number=1):
pass
def clear(self, object_id, ip=None):
pass
def is_banned(self):
pass
| 6 | 1 | 7 | 0 | 7 | 0 | 2 | 0.02 | 0 | 1 | 1 | 0 | 5 | 0 | 5 | 5 | 50 | 5 | 44 | 13 | 37 | 1 | 34 | 12 | 28 | 2 | 0 | 1 | 9 |
7,556 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/email.py
|
evernode.classes.email.Email
|
class Email:
""" Set up an email """
config_path = None
__addresses = []
__ccs = []
__files = []
__html = ''
__text = ''
__subject = ''
__data = {}
send_as_one = None
def __init__(self, send_as_one=False):
self.config_path = None
self.__addresses = []
self.__ccs = []
self.__files = []
self.__html = ''
self.__text = ''
self.__subject = ''
self.__data = {}
self.send_as_one = send_as_one
if 'CONFIG_PATH' in current_app.config:
self.config_path = current_app.config['CONFIG_PATH']
def add_address(self, address):
""" Add email address """
self.__addresses.append(address)
return self
def add_addresses(self, addresses):
""" Add addresses from array """
self.__addresses.extend(addresses)
return self
def add_cc(self, address):
""" Add carbon copy """
self.__ccs.append(address)
return self
def add_ccs(self, addresses):
""" Add carbon copy with array of addresses """
self.__ccs.extend(addresses)
return self
def add_file(self, absolute_file_path):
""" Add attachment to email """
self.__files.append(absolute_file_path)
return self
def html(self, html):
""" Set html content """
self.__html = html
return self
def text(self, text):
""" Set text content """
self.__text = text
return self
def subject(self, subject):
""" Set email subject """
self.__subject = subject
return self
def __create(self):
""" Construct the email """
self.__data = json.dumps({
'config_path': self.encode(self.config_path),
'subject': self.encode(self.__subject),
'text': self.encode(self.__text),
'html': self.encode(self.__html),
'files': self.__files,
'send_as_one': self.send_as_one,
'addresses': self.__addresses,
'ccs': self.__ccs,
})
def encode(self, value):
""" Encode parts of email to base64 for transfer """
return base64.b64encode(value.encode()).decode()
def send(self):
"""
Construct and execute sendemail.py script
Finds python binary by os.py, then
uses the /usr/bin/python to execute email script
"""
self.__create()
email_script = \
os.path.join(Path(__file__).parents[1], 'scripts', 'sendemail.py')
if os.path.exists(email_script):
subprocess.Popen(
[get_python_path(), email_script, self.__data],
stdin=None, stdout=None, stderr=None, close_fds=True)
|
class Email:
''' Set up an email '''
def __init__(self, send_as_one=False):
pass
def add_address(self, address):
''' Add email address '''
pass
def add_addresses(self, addresses):
''' Add addresses from array '''
pass
def add_cc(self, address):
''' Add carbon copy '''
pass
def add_ccs(self, addresses):
''' Add carbon copy with array of addresses '''
pass
def add_file(self, absolute_file_path):
''' Add attachment to email '''
pass
def html(self, html):
''' Set html content '''
pass
def text(self, text):
''' Set text content '''
pass
def subject(self, subject):
''' Set email subject '''
pass
def __create(self):
''' Construct the email '''
pass
def encode(self, value):
''' Encode parts of email to base64 for transfer '''
pass
def send(self):
'''
Construct and execute sendemail.py script
Finds python binary by os.py, then
uses the /usr/bin/python to execute email script
'''
pass
| 13 | 12 | 6 | 0 | 5 | 1 | 1 | 0.24 | 0 | 2 | 0 | 0 | 12 | 0 | 12 | 12 | 95 | 12 | 67 | 23 | 54 | 16 | 55 | 23 | 42 | 2 | 0 | 1 | 14 |
7,557 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/cron.py
|
evernode.classes.cron.Cron
|
class Cron(metaclass=Singleton):
"""
All you need to do is init Cron class:
cron = Cron()
Then add tasks to schedule
cron.schedule.every(1).seconds.do(test_job)
"""
schedule = schedule
start_time = None
__enabled = False
def __init__(self):
self.start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.__start()
def running(self):
""" Display running time and if Cron was enabled """
print('Running since: ' + self.start_time)
return self.__enabled
def __loop(self):
""" Run tasks forever """
while True:
self.schedule.run_pending()
time.sleep(1)
def __start(self):
""" Start a new thread to process Cron """
thread = Thread(target=self.__loop, args=())
thread.daemon = True # daemonize thread
thread.start()
self.__enabled = True
|
class Cron(metaclass=Singleton):
'''
All you need to do is init Cron class:
cron = Cron()
Then add tasks to schedule
cron.schedule.every(1).seconds.do(test_job)
'''
def __init__(self):
pass
def running(self):
''' Display running time and if Cron was enabled '''
pass
def __loop(self):
''' Run tasks forever '''
pass
def __start(self):
''' Start a new thread to process Cron '''
pass
| 5 | 4 | 5 | 0 | 4 | 1 | 1 | 0.53 | 1 | 2 | 0 | 0 | 4 | 0 | 4 | 18 | 33 | 5 | 19 | 9 | 14 | 10 | 19 | 9 | 14 | 2 | 3 | 1 | 5 |
7,558 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/base_response.py
|
evernode.classes.base_response.BaseResponse
|
class BaseResponse:
""" Base class for a HTTP response """
__mimetype__ = "text/plain; charset=utf-8"
environ = None
response_model = ResponseModel
response = Response
def __init__(self, status_code, message=None,
data=None, environ=None):
self.environ = environ
self.response_model = ResponseModel(
status_code, message, data=data)
def __call__(self, environ=None, start_response=None) -> Response:
""" Send response """
start_response(self.status(), [('Content-Type', self.mimetype())])
return [self.content()]
def status(self, status_code=None):
""" Set status or Get Status """
if status_code is not None:
self.response_model.status = status_code
# return string for response support
return str(self.response_model.status)
def message(self, message=None):
""" Set response message """
if message is not None:
self.response_model.message = message
return self.response_model.message
def data(self, data=None):
""" Set response data """
if data is not None:
self.response_model.data = data
return self.response_model.data
def content(self) -> str:
""" Get full content of response """
return str(self.response_model)
def mimetype(self) -> str:
""" Return private minetype """
return self.__mimetype__
def quick_response(self, status_code):
""" Quickly construct response using a status code """
translator = Translator(environ=self.environ)
if status_code == 404:
self.status(404)
self.message(translator.trans('http_messages.404'))
elif status_code == 401:
self.status(401)
self.message(translator.trans('http_messages.401'))
elif status_code == 400:
self.status(400)
self.message(translator.trans('http_messages.400'))
elif status_code == 200:
self.status(200)
self.message(translator.trans('http_messages.200'))
|
class BaseResponse:
''' Base class for a HTTP response '''
def __init__(self, status_code, message=None,
data=None, environ=None):
pass
def __call__(self, environ=None, start_response=None) -> Response:
''' Send response '''
pass
def status(self, status_code=None):
''' Set status or Get Status '''
pass
def message(self, message=None):
''' Set response message '''
pass
def data(self, data=None):
''' Set response data '''
pass
def content(self) -> str:
''' Get full content of response '''
pass
def mimetype(self) -> str:
''' Return private minetype '''
pass
def quick_response(self, status_code):
''' Quickly construct response using a status code '''
pass
| 9 | 8 | 6 | 0 | 5 | 1 | 2 | 0.21 | 0 | 3 | 2 | 1 | 8 | 0 | 8 | 8 | 60 | 8 | 43 | 15 | 33 | 9 | 38 | 14 | 29 | 5 | 0 | 1 | 15 |
7,559 |
AtomHash/evernode
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AtomHash_evernode/app/app/modules/core/controllers/core_ctrl.py
|
modules.core.controllers.core_ctrl.CoreController.test_json.JJ
|
class JJ(JsonModel):
bob = None
def __init__(self):
self.bob = None
self.time = datetime.now()
self.time2 = {'ti_me': datetime.now(), 'set': set('test')}
self.list = [1, datetime.now(), [{'test': [{
'date': datetime.now()}]}]]
self.time3 = {
'ti_me': ['s', [datetime.now(), 1], datetime.now(), 1]}
self.time4 = {
'ti_me': ['s', 'f', {'another_test': {
'another_date': datetime.now()}}]}
|
class JJ(JsonModel):
def __init__(self):
pass
| 2 | 0 | 11 | 0 | 11 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 1 | 5 | 1 | 4 | 14 | 1 | 13 | 8 | 11 | 0 | 9 | 8 | 7 | 1 | 1 | 0 | 1 |
7,560 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/app.py
|
evernode.classes.app.App
|
class App:
""" Creates a Custom Flask App """
app = Flask
root_path = None
config_path = None
prefix = None
def __init__(self, name, prefix=None, middleware=None,
root_path=None, config_path=None):
self.app = Flask(name)
self.root_path = root_path
self.config_path = config_path
self.__root_path()
self.load_config()
self.load_database()
self.load_cors()
self.load_modules()
self.load_language_files()
self.prefix = self.__format_prefix(prefix)
self.load_before_middleware(middleware)
def __root_path(self):
""" Just checks the root path if set """
if self.root_path is not None:
if os.path.isdir(self.root_path):
sys.path.append(self.root_path)
return
raise RuntimeError('EverNode requires a valid root path.'
' Directory: %s does not exist'
% (self.root_path))
def __format_prefix(self, prefix):
""" Format prefix """
api_version = None
if prefix is not None:
self.prefix = prefix
else:
if 'API' in self.app.config:
if self.prefix is None:
self.prefix = self.app.config['API']['PREFIX'] \
if 'PREFIX' in self.app.config['API'] else None
api_version = self.app.config['API']['VERSION'] \
if 'VERSION' in self.app.config['API'] else None
if self.prefix is not None and api_version is not None:
if '{v}' in self.prefix:
self.prefix = '%s' % \
(self.prefix.replace('{v}', api_version))
elif self.prefix is None:
self.prefix = ''
if self.prefix is not None:
self.prefix = self.prefix.strip('/')
self.app.config.update({'FORMATTED_PREFIX': self.prefix})
def get_modules(self) -> list:
""" Get the module names(folders) in root modules folder """
directory = None
if self.root_path is not None:
directory = os.path.join(self.root_path, 'modules')
else:
directory = os.path.join(sys.path[0], 'modules')
if os.path.isdir(directory):
return get_subdirectories(directory)
raise RuntimeError('EverNode requires a valid root modules folder.'
'Directory: %s does not exist' % (directory))
def load_database(self):
""" Load default database, init flask-SQLAlchemy """
if 'DISABLE_DATABASE' in self.app.config:
if self.app.config['DISABLE_DATABASE']:
return
if 'SQLALCHEMY_DATABASE_URI' not in self.app.config:
self.app.config['SQLALCHEMY_DATABASE_URI'] = \
self.app.config['SQLALCHEMY_BINDS']['DEFAULT']
db.init_app(self.app)
def load_cors(self):
""" Default cors allow all """
options = dict(
origins='*',
methods=[
'GET',
'HEAD',
'POST',
'OPTIONS',
'PUT',
'PATCH',
'DELETE'],
allow_headers='*',
expose_headers=None,
supports_credentials=False,
max_age=None,
send_wildcard=False,
vary_header=True,
resources=r'/*')
if 'CORS' in self.app.config:
if 'ORIGINS' in self.app.config['CORS']:
options['origins'] = \
self.app.config['CORS']['ORIGINS']
if 'METHODS' in self.app.config['CORS']:
options['methods'] = \
self.app.config['CORS']['METHODS']
if 'ALLOW_HEADERS' in self.app.config['CORS']:
options['allow_headers'] = \
self.app.config['CORS']['ALLOW_HEADERS']
if 'EXPOSE_HEADERS' in self.app.config['CORS']:
options['expose_headers'] = \
self.app.config['CORS']['EXPOSE_HEADERS']
if 'SUPPORTS_CREDENTIALS' in self.app.config['CORS']:
options['supports_credentials'] = \
self.app.config['CORS']['SUPPORTS_CREDENTIALS']
if 'MAX_AGE' in self.app.config['CORS']:
options['max_age'] = \
self.app.config['CORS']['MAX_AGE']
if 'SEND_WILDCARD' in self.app.config['CORS']:
options['send_wildcard'] = \
self.app.config['CORS']['SEND_WILDCARD']
if 'VARY_HEADER' in self.app.config['CORS']:
options['vary_header'] = \
self.app.config['CORS']['VARY_HEADER']
if 'RESOURCES' in self.app.config['CORS']:
options['resources'] = \
self.app.config['CORS']['RESOURCES']
CORS(self.app, **options)
def load_before_middleware(self, before_middleware):
""" Set before app middleware """
# prefix api middleware
self.app.wsgi_app = RouteBeforeMiddleware(
self.app.wsgi_app,
self.app)
# custom middleware
if before_middleware is not None:
for middleware in before_middleware:
if isinstance(middleware, dict):
self.app.wsgi_app = middleware['middleware'](
self.app.wsgi_app, self.app, middleware['kargs'])
else:
self.app.wsgi_app = middleware(self.app.wsgi_app, self.app)
def load_config(self):
""" Load EverNode config.json """
config_path = None
if self.config_path is not None:
config_path = os.path.join(self.config_path, 'config.json')
elif self.root_path is not None and self.config_path is None:
config_path = os.path.join(self.root_path, 'config.json')
else:
config_path = os.path.join(sys.path[0], 'config.json')
if os.path.exists(config_path):
config = Json.from_file(config_path)
if config is None:
raise RuntimeError('EverNode config.json requires valid json.')
self.app.config.update(config)
self.app.config.update(CONFIG_PATH=config_path)
return
raise FileNotFoundError(config_path)
def load_modules(self):
""" Load folders(custom modules) in modules folder """
LoadModules(self)()
def load_language_files(self):
""" Load language fiels in resources/lang dirs """
LoadLanguageFiles(self)()
|
class App:
''' Creates a Custom Flask App '''
def __init__(self, name, prefix=None, middleware=None,
root_path=None, config_path=None):
pass
def __root_path(self):
''' Just checks the root path if set '''
pass
def __format_prefix(self, prefix):
''' Format prefix '''
pass
def get_modules(self) -> list:
''' Get the module names(folders) in root modules folder '''
pass
def load_database(self):
''' Load default database, init flask-SQLAlchemy '''
pass
def load_cors(self):
''' Default cors allow all '''
pass
def load_before_middleware(self, before_middleware):
''' Set before app middleware '''
pass
def load_config(self):
''' Load EverNode config.json '''
pass
def load_modules(self):
''' Load folders(custom modules) in modules folder '''
pass
def load_language_files(self):
''' Load language fiels in resources/lang dirs '''
pass
| 11 | 10 | 15 | 0 | 14 | 1 | 4 | 0.08 | 0 | 8 | 4 | 0 | 10 | 0 | 10 | 10 | 164 | 10 | 142 | 22 | 130 | 12 | 100 | 21 | 89 | 11 | 0 | 3 | 43 |
7,561 |
AtomHash/evernode
|
AtomHash_evernode/evernode/bin/module.py
|
evernode.bin.module.Module
|
class Module:
""" Easy evernode modules """
module_name = None
module_path = None
branch = None
def __init__(self, module_name, command='init', branch='master'):
self.branch = branch
self.module_name = module_name
self.module_path = './%s' % (self.module_name)
getattr(self, command)()
def __touch(self, path):
with open(path, 'a'):
os.utime(path, None)
def download_file(self, url, file_name):
request.urlretrieve(url, file_name)
def easy_file_download(self, root, file):
file_name = file.rsplit('/', 1)[-1]
print('Downloading %s...' % (file_name))
self.download_file(file, os.path.join(
self.module_path, root, file_name))
def init(self):
self.make_structure()
self.easy_file_download(
'',
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/app/modules/mock_module/routes.py' % (self.branch)))
print("""
Done!
%s module created.
""" % (self.module_name))
def make_structure(self):
if os.path.isdir(self.module_path):
print('Error: Module already exists.')
sys.exit(1)
return
# make root folder
os.mkdir(self.module_path)
# make root __init__
self.__touch(
os.path.join(self.module_path, '__init__.py'))
# make sub folders
os.mkdir(os.path.join(self.module_path, 'controllers'))
os.mkdir(os.path.join(self.module_path, 'models'))
os.mkdir(os.path.join(self.module_path, 'classes'))
# make sub-folder __init__ files
self.__touch(
os.path.join(self.module_path, 'controllers', '__init__.py'))
self.__touch(
os.path.join(self.module_path, 'models', '__init__.py'))
self.__touch(
os.path.join(self.module_path, 'classes', '__init__.py'))
# make module resources folder
os.mkdir(os.path.join(self.module_path, 'resources'))
os.mkdir(os.path.join(self.module_path, 'resources', 'lang'))
os.mkdir(os.path.join(self.module_path, 'resources', 'lang', 'en'))
os.mkdir(os.path.join(self.module_path, 'resources', 'templates'))
|
class Module:
''' Easy evernode modules '''
def __init__(self, module_name, command='init', branch='master'):
pass
def __touch(self, path):
pass
def download_file(self, url, file_name):
pass
def easy_file_download(self, root, file):
pass
def init(self):
pass
def make_structure(self):
pass
| 7 | 1 | 9 | 0 | 8 | 1 | 1 | 0.12 | 0 | 0 | 0 | 0 | 6 | 0 | 6 | 6 | 63 | 7 | 50 | 11 | 43 | 6 | 39 | 11 | 32 | 2 | 0 | 1 | 7 |
7,562 |
AtomHash/evernode
|
AtomHash_evernode/evernode/bin/create.py
|
evernode.bin.create.Create
|
class Create:
""" Easy evernode app creation"""
app_name = None
dir_name = None
config_file = None
uwsgi_file = None
app_file = None
http_messages_file = None
branch = None
def __init__(self, app_name, branch='master'):
self.app_name = 'evernode_%s' % (app_name)
self.dir_name = './%s' % (self.app_name)
self.branch = branch
self.app_file = os.path.join(self.dir_name, 'app', 'app.py')
self.http_messages_file = os.path.join(
self.dir_name, 'app', 'resources',
'lang', 'en', 'http_messages.lang')
self.config_file = os.path.join(self.dir_name, 'app', 'config.json')
self.uwsgi_file = os.path.join(self.dir_name, 'uwsgi.ini')
print('Making folder structure.')
self.make_structure()
print('Downloading config.json...')
self.configure_config()
print('Downloading sample uwsgi.ini...')
self.download_sample_uwsgi()
print('Downloading sample app.py...')
self.download_sample_app()
print('Downloading sample resources/lang/en/http_messages.lang...')
self.download_sample_http_errors()
if click.confirm(
'Use a docker development enviroment? [Default=Yes]',
default=True):
self.configure_docker()
if click.confirm(
'Create a mock module? [Default=Yes]', default=True):
self.configure_module()
print("""
Done!
You can now start using EverNode.
%s folder created.
1. Navigate into the EverNode app
`$ cd %s`
2. If you downloaded the docker files
`$ cd docker`
`$ docker-compose up --build`
3. If you downloaded the mock module,
goto https://api.localhost/v1/hello-world
once the docker image has started.
4. If using a database, please init!
`$ cd app`
`$ flask db init`
`$ flask db migrate`
`$ flask db upgrade`
Notes:
Add `127.0.0.1 api.localhost`
to your hosts file.
""" % (self.app_name, self.app_name))
def __touch(self, path):
with open(path, 'a'):
os.utime(path, None)
def download_file(self, url, file_name):
request.urlretrieve(url, file_name)
def configure_config(self):
# download current config file from github
self.download_file(
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/app/config.json' % (self.branch)),
self.config_file)
config = Json.from_file(self.config_file)
config['NAME'] = self.app_name
config['SECRET'] = Security.generate_key()
config['KEY'] = Security.generate_key()
config['SQLALCHEMY_BINDS']['DEFAULT'] = \
'mysql://<db_user>:<password>@<host>/<db_name>'
Json.save_file(self.config_file, config)
def download_sample_uwsgi(self):
self.download_file(
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/uwsgi.ini' % (self.branch)),
self.uwsgi_file)
def download_sample_app(self):
self.download_file(
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/app/app.py' % (self.branch)),
self.app_file)
def download_sample_http_errors(self):
self.download_file(
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/app/resources/lang/en/http_messages.lang'
% (self.branch)),
self.http_messages_file)
def configure_module(self):
mock_module_path = os.path.join(
self.dir_name, 'app', 'modules', 'mock_module')
mock_module_files = [
{'mock_module': [
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/app/modules/mock_module/routes.py') % (self.branch)]},
{'controllers': [
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/app/modules/mock_module/controllers/'
'__init__.py') % (self.branch),
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/app/modules/mock_module/'
'controllers/mock_controller.py' % (self.branch))]},
{'models': [
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/app/modules/mock_module/'
'models/__init__.py' % (self.branch)),
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/app/modules/mock_module/'
'models/hello_world_model.py' % (self.branch))]}
]
for folder in mock_module_files:
for key, value in folder.items():
root = ''
if key is 'mock_module':
root = 'app/modules/mock_module'
elif key is 'controllers':
root = 'app/modules/mock_module/controllers'
elif key is 'models':
root = 'app/modules/mock_module/models'
os.mkdir(os.path.join(self.dir_name, root))
for file in value:
self.easy_file_download(root, file)
os.mkdir(os.path.join(mock_module_path, 'resources'))
os.mkdir(os.path.join(mock_module_path, 'resources', 'lang'))
os.mkdir(os.path.join(mock_module_path, 'resources', 'lang', 'en'))
os.mkdir(os.path.join(mock_module_path, 'resources', 'templates'))
self.__touch(os.path.join(mock_module_path, '__init__.py'))
def configure_docker(self):
needed_files = [
{'docker': [
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/docker/docker-compose.yml' % (self.branch))
]},
{'build': [
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/docker/build/supervisord.conf' % (self.branch)),
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/docker/build/Dockerfile' % (self.branch)),
]},
{'nginx': [
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/docker/build/nginx/nginx.conf' % (self.branch))
]},
{'ssls': [
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/docker/build/nginx/ssls/'
'api.localhost.crt' % (self.branch)),
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/docker/build/nginx/ssls/'
'api.localhost.key' % (self.branch))
]},
{'conf.d': [
('https://raw.githubusercontent.com/AtomHash/evernode/'
'%s/app/docker/build/nginx/conf.d/'
'api.localhost.conf' % (self.branch))
]}]
for folder in needed_files:
for key, value in folder.items():
root = ''
if key is 'docker':
root = 'docker'
elif key is 'build':
root = 'docker/build'
elif key is 'nginx':
root = 'docker/build/nginx'
elif key is 'ssls':
root = 'docker/build/nginx/ssls'
elif key is 'conf.d':
root = 'docker/build/nginx/conf.d'
os.mkdir(os.path.join(self.dir_name, root))
for file in value:
self.easy_file_download(root, file)
docker_compose = os.path.join(
self.dir_name, 'docker', 'docker-compose.yml')
with open(docker_compose, 'r') as docker_compose_opened:
try:
yml = yaml.load(docker_compose_opened)
yml['services'][self.app_name] = \
yml['services'].pop('evernode-development', None)
yml['services'][self.app_name]['container_name'] = \
self.app_name
del yml['services'][self.app_name]['volumes'][-1]
with open(docker_compose, 'w') as new_docker_compose:
yaml.dump(yml, new_docker_compose,
default_flow_style=False, allow_unicode=True)
except yaml.YAMLError as exc:
print('Error: Cannot parse docker-compose.yml')
dockerfile = os.path.join(
self.dir_name, 'docker', 'build', 'Dockerfile')
with open(dockerfile, 'r') as dockerfile_opened:
lines = dockerfile_opened.readlines()
lines[-1] = ('ENTRYPOINT pip3.6 install --upgrade -r /srv/app/'
'requirements.txt && python2.7 /usr/bin/supervisord')
with open(dockerfile, 'w') as df_opened_writable:
df_opened_writable.writelines(lines)
def easy_file_download(self, root, file):
file_name = file.rsplit('/', 1)[-1]
print('Downloading %s...' % (file_name))
self.download_file(file, os.path.join(
self.dir_name, root, file_name))
def make_structure(self):
if os.path.isdir(self.dir_name):
print('Error: Projects already exists.')
sys.exit(1)
return
# make root folder
os.mkdir(self.dir_name)
# make app folder
os.mkdir(os.path.join(self.dir_name, 'app'))
requirements_file = os.path.join(
self.dir_name, 'app', 'requirements.txt')
self.__touch(requirements_file)
with open(requirements_file, 'w') as requirements_file_writable:
requirements_file_writable.write('evernode')
# make app folder
os.mkdir(os.path.join(self.dir_name, 'logs'))
# make uploads folder
os.mkdir(os.path.join(self.dir_name, 'uploads'))
# make public folder
os.mkdir(os.path.join(self.dir_name, 'public'))
# make public static folder
os.mkdir(os.path.join(self.dir_name, 'public', 'static'))
# make app root modules folder
os.mkdir(os.path.join(self.dir_name, 'app', 'modules'))
self.__touch(
os.path.join(self.dir_name, 'app', 'modules', '__init__.py'))
# make app root resources folder
os.mkdir(os.path.join(self.dir_name, 'app', 'resources'))
os.mkdir(os.path.join(self.dir_name, 'app', 'resources', 'lang'))
os.mkdir(os.path.join(self.dir_name, 'app', 'resources', 'lang', 'en'))
os.mkdir(os.path.join(self.dir_name, 'app', 'resources', 'templates'))
|
class Create:
''' Easy evernode app creation'''
def __init__(self, app_name, branch='master'):
pass
def __touch(self, path):
pass
def download_file(self, url, file_name):
pass
def configure_config(self):
pass
def download_sample_uwsgi(self):
pass
def download_sample_app(self):
pass
def download_sample_http_errors(self):
pass
def configure_module(self):
pass
def configure_docker(self):
pass
def easy_file_download(self, root, file):
pass
def make_structure(self):
pass
| 12 | 1 | 20 | 0 | 20 | 1 | 3 | 0.04 | 0 | 0 | 0 | 0 | 11 | 0 | 11 | 11 | 246 | 12 | 224 | 43 | 212 | 10 | 124 | 37 | 112 | 10 | 0 | 3 | 29 |
7,563 |
AtomHash/evernode
|
AtomHash_evernode/evernode/middleware/jwt_middleware.py
|
evernode.middleware.jwt_middleware.JWTMiddleware
|
class JWTMiddleware(Middleware):
""" Middleware to conditionally accept a JWT request """
def condition(self) -> bool:
""" Check a JWT token """
return JWT().verify_http_authorization_token()
def create_response(self):
""" is condition false, return 401"""
self.response = JsonResponse(401)
|
class JWTMiddleware(Middleware):
''' Middleware to conditionally accept a JWT request '''
def condition(self) -> bool:
''' Check a JWT token '''
pass
def create_response(self):
''' is condition false, return 401'''
pass
| 3 | 3 | 3 | 0 | 2 | 1 | 1 | 0.6 | 1 | 3 | 2 | 0 | 2 | 1 | 2 | 5 | 10 | 2 | 5 | 4 | 2 | 3 | 5 | 4 | 2 | 1 | 1 | 0 | 2 |
7,564 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/json.py
|
evernode.classes.json.Json
|
class Json():
""" help break down and construct json objects """
__exclude_list = []
def __init__(self, value):
self.value = value
@staticmethod
def string(value) -> str:
""" string dict/object/value to JSON """
return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
@staticmethod
def parse(string, is_file=False, obj=False):
""" Convert a JSON string to dict/object """
try:
if obj is False:
if is_file:
return system_json.load(string)
return system_json.loads(string, encoding='utf8')
else:
if is_file:
return system_json.load(
string,
object_hook=lambda d: namedtuple('j', d.keys())
(*d.values()), ensure_ascii=False, encoding='utf8')
return system_json.loads(
string,
object_hook=lambda d: namedtuple('j', d.keys())
(*d.values()), encoding='utf8')
except (Exception, BaseException) as error:
try:
if current_app.config['DEBUG']:
raise error
except RuntimeError as flask_error:
raise flask_error
return None
@staticmethod
def from_file(file_path) -> dict:
""" Load JSON file """
with io.open(file_path, 'r', encoding='utf-8') as json_stream:
return Json.parse(json_stream, True)
@staticmethod
def save_file(file_path, data):
with open(file_path, 'w') as json_file:
system_json.dump(
data,
json_file,
ensure_ascii=False,
indent=4)
def safe_object(self) -> dict:
""" Create an object ready for JSON serialization """
return self.__iterate_value(self.value)
def safe_values(self, value):
""" Parse non-string values that will not serialize """
# TODO: override-able?
string_val = ""
if isinstance(value, datetime.date):
try:
string_val = value.strftime('{0}{1}{2}'.format(
current_app.config['DATETIME']['DATE_FORMAT'],
current_app.config['DATETIME']['SEPARATOR'],
current_app.config['DATETIME']['TIME_FORMAT']))
except RuntimeError:
string_val = value.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(value, bytes):
string_val = value.decode('utf-8')
elif isinstance(value, decimal.Decimal):
string_val = float(value)
else:
string_val = value
return string_val
def camel_case(self, snake_case):
""" Convert snake case to camel case """
components = snake_case.split('_')
return components[0] + "".join(x.title() for x in components[1:])
def __find_object_children(self, obj) -> dict:
""" Convert object to flattened object """
if hasattr(obj, 'items') and \
isinstance(obj.items, types.BuiltinFunctionType):
return self.__construct_object(obj)
elif isinstance(obj, (list, tuple, set)):
return self.__construct_list(obj)
else:
exclude_list = []
if hasattr(obj, '_sa_instance_state'):
# load only deferred objects
if len(orm.attributes.instance_state(obj).unloaded) > 0:
mapper = inspect(obj)
for column in mapper.attrs:
column.key
column.value
if hasattr(obj, 'json_exclude_list'):
# do not serialize any values in this list
exclude_list = obj.json_exclude_list
return self.__construct_object(vars(obj), exclude_list)
return None
def __construct_list(self, list_value):
""" Loop list/set/tuple and parse values """
array = []
for value in list_value:
array.append(self.__iterate_value(value))
return array
def __construct_object(self, obj, exclude_list=[]):
""" Loop dict/class object and parse values """
new_obj = {}
for key, value in obj.items():
if str(key).startswith('_') or \
key is 'json_exclude_list' or key in exclude_list:
continue
new_obj[self.camel_case(key)] = self.__iterate_value(value)
return new_obj
def __iterate_value(self, value):
""" Return value for JSON serialization """
if hasattr(value, '__dict__') or isinstance(value, dict):
return self.__find_object_children(value) # go through dict/class
elif isinstance(value, (list, tuple, set)):
return self.__construct_list(value) # go through list
return self.safe_values(value)
|
class Json():
''' help break down and construct json objects '''
def __init__(self, value):
pass
@staticmethod
def string(value) -> str:
''' string dict/object/value to JSON '''
pass
@staticmethod
def parse(string, is_file=False, obj=False):
''' Convert a JSON string to dict/object '''
pass
@staticmethod
def from_file(file_path) -> dict:
''' Load JSON file '''
pass
@staticmethod
def save_file(file_path, data):
pass
def safe_object(self) -> dict:
''' Create an object ready for JSON serialization '''
pass
def safe_values(self, value):
''' Parse non-string values that will not serialize '''
pass
def camel_case(self, snake_case):
''' Convert snake case to camel case '''
pass
def __find_object_children(self, obj) -> dict:
''' Convert object to flattened object '''
pass
def __construct_list(self, list_value):
''' Loop list/set/tuple and parse values '''
pass
def __construct_object(self, obj, exclude_list=[]):
''' Loop dict/class object and parse values '''
pass
def __iterate_value(self, value):
''' Return value for JSON serialization '''
pass
| 17 | 11 | 9 | 0 | 8 | 1 | 3 | 0.17 | 0 | 12 | 0 | 0 | 8 | 1 | 12 | 12 | 129 | 13 | 102 | 32 | 85 | 17 | 76 | 24 | 63 | 7 | 0 | 4 | 33 |
7,565 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/security.py
|
evernode.classes.security.Security
|
class Security:
""" Static functions to help app security """
@staticmethod
def generate_uuid(multiplier=1):
uuid = ''
counter = 0
while counter < multiplier:
uuid = uuid + secrets.token_hex()
counter = counter + 1
return uuid
@staticmethod
def generate_key() -> str:
""" Generate a Fernet key"""
return Fernet.generate_key().decode("utf-8")
@staticmethod
def encrypt(clear_text) -> str:
""" Use config.json key to encrypt """
if not isinstance(clear_text, bytes):
clear_text = str.encode(clear_text)
cipher = Fernet(current_app.config['KEY'])
return cipher.encrypt(clear_text).decode("utf-8")
@staticmethod
def decrypt(crypt_text) -> str:
""" Use config.json key to decrypt """
cipher = Fernet(current_app.config['KEY'])
if not isinstance(crypt_text, bytes):
crypt_text = str.encode(crypt_text)
return cipher.decrypt(crypt_text).decode("utf-8")
@staticmethod
def random_string(length) -> str:
""" Create a random string for security purposes """
return ''.join(
random.SystemRandom().choice(
string.ascii_uppercase + string.digits)
for _ in range(length))
@staticmethod
def hash(clear_text) -> str:
""" Hash clear text """
return generate_password_hash(
clear_text,
method=current_app.config['AUTH']['PASSWORD_HASHING'])
@staticmethod
def verify_hash(clear_text, hashed_text) -> bool:
""" Check a hash """
return check_password_hash(hashed_text, clear_text)
|
class Security:
''' Static functions to help app security '''
@staticmethod
def generate_uuid(multiplier=1):
pass
@staticmethod
def generate_key() -> str:
''' Generate a Fernet key'''
pass
@staticmethod
def encrypt(clear_text) -> str:
''' Use config.json key to encrypt '''
pass
@staticmethod
def decrypt(crypt_text) -> str:
''' Use config.json key to decrypt '''
pass
@staticmethod
def random_string(length) -> str:
''' Create a random string for security purposes '''
pass
@staticmethod
def hash(clear_text) -> str:
''' Hash clear text '''
pass
@staticmethod
def verify_hash(clear_text, hashed_text) -> bool:
''' Check a hash '''
pass
| 15 | 7 | 5 | 0 | 4 | 1 | 1 | 0.18 | 0 | 5 | 0 | 0 | 0 | 0 | 7 | 7 | 52 | 7 | 38 | 20 | 23 | 7 | 26 | 12 | 18 | 2 | 0 | 1 | 10 |
7,566 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/render.py
|
evernode.classes.render.Render
|
class Render:
""" Compile templates from root_path resources or module resources """
jinja = None
template_path = None
templates = {}
""" dict that contains compiled templates """
def __init__(self, module_name=None):
self.templates = {}
if module_name is None:
path = os.path.join(sys.path[0], 'resources', 'templates')
if os.path.isdir(path):
self.template_path = path
else:
raise NotADirectoryError
else:
path = os.path.join(
sys.path[0],
'modules',
module_name,
'resources',
'templates')
if os.path.isdir(path):
self.template_path = path
else:
raise NotADirectoryError
self.__init_jinja()
def __init_jinja(self):
self.jinja = Environment(
loader=FileSystemLoader(self.template_path),
trim_blocks=True)
def compile(self, name, folder=None, data=None):
"""
renders template_name + self.extension file with data using jinja
"""
template_name = name.replace(os.sep, "")
if folder is None:
folder = ""
full_name = os.path.join(
folder.strip(os.sep), template_name)
if data is None:
data = {}
try:
self.templates[template_name] = \
self.jinja.get_template(full_name).render(data)
except TemplateNotFound as template_error:
if current_app.config['DEBUG']:
raise template_error
|
class Render:
''' Compile templates from root_path resources or module resources '''
def __init__(self, module_name=None):
pass
def __init_jinja(self):
pass
def compile(self, name, folder=None, data=None):
'''
renders template_name + self.extension file with data using jinja
'''
pass
| 4 | 2 | 14 | 0 | 13 | 1 | 3 | 0.12 | 0 | 2 | 0 | 0 | 3 | 0 | 3 | 3 | 51 | 4 | 42 | 11 | 38 | 5 | 30 | 10 | 26 | 5 | 0 | 2 | 10 |
7,567 |
AtomHash/evernode
|
AtomHash_evernode/app/app/modules/mock_module/models/hello_world_model.py
|
modules.mock_module.models.hello_world_model.HelloWorldModel
|
class HelloWorldModel:
""" Mock Module, Mock Model """
def __init__(self):
self.hello = 'world'
|
class HelloWorldModel:
''' Mock Module, Mock Model '''
def __init__(self):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 5 | 1 | 3 | 3 | 1 | 1 | 3 | 3 | 1 | 1 | 0 | 0 | 1 |
7,568 |
AtomHash/evernode
|
AtomHash_evernode/app/app/modules/core/controllers/core_ctrl.py
|
modules.core.controllers.core_ctrl.CoreController
|
class CoreController:
""" route controller """
@staticmethod
def no_database():
return JsonResponse(200, None, "No Database")
@staticmethod
def test():
""" evernode testing """
fail2ban = Fail2Ban(1, location="passwords", ban_for=60)
fail2ban.add_attempt(1)
return JsonResponse(200, None, fail2ban.is_banned())
@staticmethod
def fail2ban_login():
user_auth = UserAuth(
BaseUserModel,
username_error="Please enter a username",
password_error="Please Enter a password")
session = user_auth.session()
fail2ban = Fail2Ban(
location="login",
ban_for=60)
if session is None:
if user_auth.user is not None:
fail2ban.object_id(user_auth.user.id)
fail2ban.add_attempt()
if fail2ban.is_banned():
return JsonResponse(403)
return JsonResponse(401)
else:
fail2ban.object_id(user_auth.user.id)
if fail2ban.is_banned():
return JsonResponse(403)
fail2ban.clear(user_auth.user.id)
return JsonResponse(200, None, session)
@staticmethod
def test_paginate(page_number, limit):
""" evernode testing """
paginate = Paginate(TestModel, limit)
paginate.add_filter('name', 'LIKE', 'te%')
return JsonResponse(
200,
None,
paginate.json_paginate('/v1/tests/', page_number))
@staticmethod
def test_refresh_token():
""" evernode testing """
jwt = JWT()
jwt.verify_http_auth_refresh_token()
return JsonResponse(200, None, jwt.data)
@staticmethod
def test_test_model():
""" evernode testing """
return JsonResponse(200, None, TestModel.where_id(1))
@staticmethod
def test_jwt_token():
""" evernode testing """
jwt = JWT()
to = jwt.create_token("data")
return JsonResponse(200, None, {"result": jwt.verify_token(to), "jwterror": str(jwt.errors)})
@staticmethod
def test_validate_password_reset():
""" evernode testing """
formdata = FormData()
formdata.add_field(
'code', required=True, error='A code is required.')
formdata.add_field(
'password', required=True, error='A new password is required.')
formdata.parse()
result = BaseUserModel.validate_password_reset(
formdata.values['code'], formdata.values['password'])
return JsonResponse(200, None, result)
@staticmethod
def test_create_password_reset(email):
""" evernode testing """
token = BaseUserModel.create_password_reset(email, valid_for=3600)
return JsonResponse(200, None, token)
@staticmethod
def test_json():
""" evernode testing """
class JJ(JsonModel):
bob = None
def __init__(self):
self.bob = None
self.time = datetime.now()
self.time2 = {'ti_me': datetime.now(), 'set': set('test')}
self.list = [1, datetime.now(), [{'test': [{
'date': datetime.now()}]}]]
self.time3 = {
'ti_me': ['s', [datetime.now(), 1], datetime.now(), 1]}
self.time4 = {
'ti_me': ['s', 'f', {'another_test': {
'another_date': datetime.now()}}]}
return JsonResponse(200, None, JJ())
@staticmethod
def user_json():
user = BaseUserModel.where_id(1)
return JsonResponse(200, None, user)
@staticmethod
def test_email():
email = Email(send_as_one=True)
email.html('hello')
email.text('hello')
email.add_address('me@dylanharty.com')
email.add_cc('example@atomhash.org')
email.add_file('/srv/logs/uwsgi.log')
email.send()
return JsonResponse(200, None, "")
@staticmethod
def test_translator():
trans = Translator()
return JsonResponse(200, None,
trans.trans('welcome.home'))
@staticmethod
def test_render():
""" evernode testing """
render = Render()
render.compile('ev/ern/ode.html', folder="emails/user")
render.templates['evernode.html']
return JsonResponse(200, None,
render.templates['evernode.html'])
@staticmethod
def test_security():
security_functions = dict(
string="EverNode",
encrypted=Security.encrypt("EverNode"),
decrypt=Security.decrypt(Security.encrypt("EverNode")),
)
return JsonResponse(200, None, security_functions)
@staticmethod
@middleware
def user_check():
return JsonResponse(200, None, "is logged in")
@staticmethod
def test_form_upload():
""" evernode testing """
form = FormData()
form.add_file("image-file")
form.add_file("another-file")
form.parse()
form.file_save('image-file')
return JsonResponse(200, None, str(form.files))
@staticmethod
def generate_key():
""" evernode testing """
key = Security.generate_key()
return JsonResponse(200, None, key).create()
@staticmethod
def form_fail_callback():
print('callback called')
@staticmethod
def test_form():
""" evernode testing """
form = FormData()
form.add_field('name', error="you need a name", required=True)
form.parse(fail_callback=CoreController.form_fail_callback)
return JsonResponse(200, None, form.values['name'])
def make_user():
user = BaseUserModel()
user.firstname = 'Dylan'
user.lastname = 'Harty'
user.email = 'example@atomhash.org'
user.set_password('123321')
user.save()
return JsonResponse(200, None, user)
def user_token():
session = UserAuth(
BaseUserModel,
username_error="Please enter a username",
password_error="Please Enter a password").session()
if session is None:
return JsonResponse(401)
return JsonResponse(200, None, session)
|
class CoreController:
''' route controller '''
@staticmethod
def no_database():
pass
@staticmethod
def test():
''' evernode testing '''
pass
@staticmethod
def fail2ban_login():
pass
@staticmethod
def test_paginate(page_number, limit):
''' evernode testing '''
pass
@staticmethod
def test_refresh_token():
''' evernode testing '''
pass
@staticmethod
def test_test_model():
''' evernode testing '''
pass
@staticmethod
def test_jwt_token():
''' evernode testing '''
pass
@staticmethod
def test_validate_password_reset():
''' evernode testing '''
pass
@staticmethod
def test_create_password_reset(email):
''' evernode testing '''
pass
@staticmethod
def test_json():
''' evernode testing '''
pass
class JJ(JsonModel):
def __init__(self):
pass
@staticmethod
def user_json():
pass
@staticmethod
def test_email():
pass
@staticmethod
def test_translator():
pass
@staticmethod
def test_render():
''' evernode testing '''
pass
@staticmethod
def test_security():
pass
@staticmethod
@middleware
def user_check():
pass
@staticmethod
def test_form_upload():
''' evernode testing '''
pass
@staticmethod
def generate_key():
''' evernode testing '''
pass
@staticmethod
def form_fail_callback():
pass
@staticmethod
def test_form_upload():
''' evernode testing '''
pass
def make_user():
pass
def user_token():
pass
| 46 | 13 | 7 | 0 | 6 | 1 | 1 | 0.08 | 0 | 15 | 13 | 0 | 2 | 0 | 22 | 22 | 196 | 24 | 159 | 72 | 113 | 13 | 113 | 52 | 88 | 5 | 0 | 3 | 28 |
7,569 |
AtomHash/evernode
|
AtomHash_evernode/app/app/modules/core/controllers/test_ctrl.py
|
modules.core.controllers.test_ctrl.TestCtrl
|
class TestCtrl:
@staticmethod
def model_serialization_json():
test_model = TestModel()
test_model.name = "AtomHash"
test_model.save()
test_model.add('groups', {'1-h': 1})
test_model_2 = TestModel.where_id(1)
return JsonResponse(200, None, [test_model, test_model_2])
@staticmethod
def decimal_serialization_json():
money = Decimal(1.95).quantize(Decimal('0.01'), ROUND_HALF_UP)
return JsonResponse(200, None, {
'money': money})
|
class TestCtrl:
@staticmethod
def model_serialization_json():
pass
@staticmethod
def decimal_serialization_json():
pass
| 5 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 0 | 3 | 2 | 0 | 0 | 0 | 2 | 2 | 16 | 2 | 14 | 8 | 9 | 0 | 11 | 6 | 8 | 1 | 0 | 0 | 2 |
7,570 |
AtomHash/evernode
|
AtomHash_evernode/app/app/modules/core/models/test_model.py
|
modules.core.models.test_model.TestModel
|
class TestModel(BaseModel):
""" Test DB model """
__tablename__ = 'tests'
name = Column(String(20))
json_exclude_list = ['id']
|
class TestModel(BaseModel):
''' Test DB model '''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 3 | 0 | 0 |
7,571 |
AtomHash/evernode
|
AtomHash_evernode/app/app/modules/mock_module/controllers/mock_controller.py
|
modules.mock_module.controllers.mock_controller.MockController
|
class MockController:
""" Mock Module, Mock Controller """
@staticmethod
def hello_world():
""" Hello World Controller """
return JsonResponse(200, None, HelloWorldModel())
|
class MockController:
''' Mock Module, Mock Controller '''
@staticmethod
def hello_world():
''' Hello World Controller '''
pass
| 3 | 2 | 3 | 0 | 2 | 1 | 1 | 0.5 | 0 | 2 | 2 | 0 | 0 | 0 | 1 | 1 | 7 | 1 | 4 | 3 | 1 | 2 | 3 | 2 | 1 | 1 | 0 | 0 | 1 |
7,572 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/session.py
|
evernode.classes.session.Session
|
class Session:
""" Helper class for app state-less sessions """
@staticmethod
def create_session_id() -> str:
""" Create a session token """
return Security.generate_uuid(2)
@staticmethod
def set_current_session(session_id) -> bool:
""" Add session_id to flask globals for current request """
try:
g.session_id = session_id
return True
except (Exception, BaseException) as error:
# catch all on config update
if current_app.config['DEBUG']:
print(error)
return False
@staticmethod
def current_session() -> str:
""" Return session id in app globals, only current request """
session_id = getattr(g, 'session_id', None)
if session_id is not None:
return SessionModel.where_session_id(session_id)
return None
@classmethod
def create_session(cls, session_id, user_id):
"""
Save a new session to the database
Using the ['AUTH']['MAX_SESSIONS'] config setting
a session with be created within the MAX_SESSIONS
limit. Once this limit is hit, delete the earliest
session.
"""
count = SessionModel.count(user_id)
if count < current_app.config['AUTH']['MAX_SESSIONS']:
cls.__save_session(session_id, user_id)
return
elif count >= current_app.config['AUTH']['MAX_SESSIONS']:
earliest_session = SessionModel.where_earliest(user_id)
earliest_session.delete()
cls.__save_session(session_id, user_id)
return
@classmethod
def __save_session(cls, session_id, user_id):
session = SessionModel()
session.user_id = user_id
session.session_id = session_id
Session.set_current_session(session_id)
session.save()
|
class Session:
''' Helper class for app state-less sessions '''
@staticmethod
def create_session_id() -> str:
''' Create a session token '''
pass
@staticmethod
def set_current_session(session_id) -> bool:
''' Add session_id to flask globals for current request '''
pass
@staticmethod
def current_session() -> str:
''' Return session id in app globals, only current request '''
pass
@classmethod
def create_session_id() -> str:
'''
Save a new session to the database
Using the ['AUTH']['MAX_SESSIONS'] config setting
a session with be created within the MAX_SESSIONS
limit. Once this limit is hit, delete the earliest
session.
'''
pass
@classmethod
def __save_session(cls, session_id, user_id):
pass
| 11 | 5 | 8 | 0 | 6 | 2 | 2 | 0.32 | 0 | 6 | 2 | 0 | 0 | 0 | 5 | 5 | 54 | 5 | 37 | 16 | 26 | 12 | 31 | 10 | 25 | 3 | 0 | 2 | 10 |
7,573 |
AtomHash/evernode
|
AtomHash_evernode/tests/test_class.py
|
tests.test_class.TestClass
|
class TestClass(unittest.TestCase):
app_class = None
@classmethod
def setUpClass(cls):
script_path = os.path.dirname(__file__)
root_path_file = os.path.join(script_path, 'root_path.txt')
with open(root_path_file, 'r') as opened_file:
root_path = opened_file.read().replace('\n', '')
cls.app_class = App(__name__, root_path=(root_path))
@classmethod
def tearDownClass(cls):
cls.app_class = None
|
class TestClass(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
@classmethod
def tearDownClass(cls):
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 3 | 0 | 0 | 2 | 74 | 15 | 3 | 12 | 10 | 7 | 0 | 10 | 7 | 7 | 1 | 2 | 1 | 2 |
7,574 |
AtomHash/evernode
|
AtomHash_evernode/tests/test_classes_app.py
|
tests.test_classes_app.Test_Classes_App
|
class Test_Classes_App(TestClass):
def test_app_is_flask(self):
self.assertIsInstance(self.app_class.app, Flask)
|
class Test_Classes_App(TestClass):
def test_app_is_flask(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 75 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
7,575 |
AtomHash/evernode
|
AtomHash_evernode/tests/test_classes_json.py
|
tests.test_classes_json.Test_Classes_Json
|
class Test_Classes_Json(TestClass):
def test_json_read_not_found(self):
self.assertRaises(FileNotFoundError, Json.from_file, 'nofile')
def test_json_read_found(self):
self.assertIsInstance(
Json.from_file(self.app_class.app.config['CONFIG_PATH']), dict)
def test_json_string_parse(self):
self.assertIsInstance(
Json.parse('{"first": "hello"}'), dict)
def test_json_object_to_string(self):
self.assertIsInstance(
Json.string({"second": "message"}), str)
def test_parse_string_to_json_object_to_string(self):
string = '{"third": "hello"}'
dict = Json.parse(string)
string_two = Json.string(dict)
self.assertIsInstance(string_two, str)
def test_json_handle_date(self):
self.assertIsInstance(
Json.string({"datetime": datetime.datetime.now()}), str)
def test_json_read_error(self):
self.assertRaises(JSONDecodeError, Json.parse, '{{{{{}')
|
class Test_Classes_Json(TestClass):
def test_json_read_not_found(self):
pass
def test_json_read_found(self):
pass
def test_json_string_parse(self):
pass
def test_json_object_to_string(self):
pass
def test_parse_string_to_json_object_to_string(self):
pass
def test_json_handle_date(self):
pass
def test_json_read_error(self):
pass
| 8 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 5 | 0 | 0 | 7 | 0 | 7 | 81 | 29 | 7 | 22 | 11 | 14 | 0 | 18 | 11 | 10 | 1 | 3 | 0 | 7 |
7,576 |
AtomHash/evernode
|
AtomHash_evernode/tests/test_classes_security.py
|
tests.test_classes_security.Test_Classes_Security
|
class Test_Classes_Security(TestClass):
def test_generate_key(self):
self.assertIsInstance(Security.generate_key(), str)
def test_encrypt(self):
with self.app_class.app.app_context():
self.assertIsInstance(Security.encrypt('hello'), str)
def test_decrypt(self):
with self.app_class.app.app_context():
self.assertIsInstance(
Security.decrypt(Security.encrypt('hello')), str)
|
class Test_Classes_Security(TestClass):
def test_generate_key(self):
pass
def test_encrypt(self):
pass
def test_decrypt(self):
pass
| 4 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 3 | 0 | 3 | 77 | 13 | 3 | 10 | 4 | 6 | 0 | 9 | 4 | 5 | 1 | 3 | 1 | 3 |
7,577 |
AtomHash/evernode
|
AtomHash_evernode/evernode/models/response_model.py
|
evernode.models.response_model.ResponseModel
|
class ResponseModel:
""" Class for a response a centralized response structure """
status = 200
message = "Connection sucessful"
data = {}
def __init__(self, status, message, data=None):
if data is None:
data = {}
self.status = status
self.message = message
self.data = data
def __repr__(self):
return Json.string(self)
def __str__(self):
return self.__repr__()
|
class ResponseModel:
''' Class for a response a centralized response structure '''
def __init__(self, status, message, data=None):
pass
def __repr__(self):
pass
def __str__(self):
pass
| 4 | 1 | 3 | 0 | 3 | 0 | 1 | 0.07 | 0 | 1 | 1 | 0 | 3 | 0 | 3 | 3 | 18 | 3 | 14 | 7 | 10 | 1 | 14 | 7 | 10 | 2 | 0 | 1 | 4 |
7,578 |
AtomHash/evernode
|
AtomHash_evernode/evernode/scripts/sendemail.py
|
evernode.scripts.sendemail.SendEmail
|
class SendEmail:
""" send email from the command line with async abilities """
multipart = MIMEMultipart
smtp = smtplib.SMTP
config_path = None
config = None
subject = None
text = None
html = None
addresses = None
ccs = None
send_as_one = None
files = []
def __init__(self):
self.parse()
with open(self.config_path, 'r') as json_stream:
loaded_json = json.load(json_stream)
if 'EMAIL' not in loaded_json:
raise RuntimeError(
'EverNode sendemail.py requires SMTP login details.')
self.config = loaded_json['EMAIL']
self.smtp = smtplib.SMTP(self.config['HOST'], self.config['PORT'])
self.smtp.starttls()
self.smtp.set_debuglevel(0)
self.multipart = MIMEMultipart('alternative')
self.create_email()
def parse(self):
""" parses args json """
data = json.loads(sys.argv[1])
self.config_path = self.decode(data['config_path'])
self.subject = self.decode(data['subject'])
self.text = self.decode(data['text'])
self.html = self.decode(data['html'])
self.send_as_one = data['send_as_one']
if 'files' in data:
self.parse_files(data['files'])
self.ccs = data['ccs']
self.addresses = data['addresses']
if not self.addresses:
raise ValueError(
'Atleast one email address is required to send an email')
def parse_files(self, files):
if files is None or not files:
return
for file in files:
part = None
with open(file, "rb") as file_opened:
part = MIMEApplication(
file_opened.read(),
Name=basename(file)
)
part['Content-Disposition'] = \
'attachment; filename="%s"' % basename(file)
self.files.append(part)
def decode(self, value):
""" decode args """
return base64.b64decode(value).decode()
def construct_message(self, email=None):
""" construct the email message """
# add subject, from and to
self.multipart['Subject'] = self.subject
self.multipart['From'] = self.config['EMAIL']
self.multipart['Date'] = formatdate(localtime=True)
if email is None and self.send_as_one:
self.multipart['To'] = ", ".join(self.addresses)
elif email is not None and self.send_as_one is False:
self.multipart['To'] = email
# add ccs
if self.ccs is not None and self.ccs:
self.multipart['Cc'] = ", ".join(self.ccs)
# add html and text body
html = MIMEText(self.html, 'html')
alt_text = MIMEText(self.text, 'plain')
self.multipart.attach(html)
self.multipart.attach(alt_text)
for file in self.files:
self.multipart.attach(file)
def connect(self):
self.smtp.ehlo()
self.smtp.login(self.config['USERNAME'], self.config['PASSWORD'])
def disconnect(self):
self.smtp.quit()
def send(self, email=None):
""" send email message """
if email is None and self.send_as_one:
self.smtp.send_message(
self.multipart, self.config['EMAIL'], self.addresses)
elif email is not None and self.send_as_one is False:
self.smtp.send_message(
self.multipart, self.config['EMAIL'], email)
self.multipart = MIMEMultipart('alternative')
def create_email(self):
""" main function to construct and send email """
self.connect()
if self.send_as_one:
self.construct_message()
self.send()
elif self.send_as_one is False:
for email in self.addresses:
self.construct_message(email)
self.send(email)
self.disconnect()
|
class SendEmail:
''' send email from the command line with async abilities '''
def __init__(self):
pass
def parse(self):
''' parses args json '''
pass
def parse_files(self, files):
pass
def decode(self, value):
''' decode args '''
pass
def construct_message(self, email=None):
''' construct the email message '''
pass
def connect(self):
pass
def disconnect(self):
pass
def send(self, email=None):
''' send email message '''
pass
def create_email(self):
''' main function to construct and send email '''
pass
| 10 | 6 | 10 | 0 | 9 | 1 | 3 | 0.1 | 0 | 6 | 0 | 0 | 9 | 0 | 9 | 9 | 111 | 9 | 93 | 31 | 83 | 9 | 82 | 29 | 72 | 5 | 0 | 2 | 23 |
7,579 |
AtomHash/evernode
|
AtomHash_evernode/evernode/models/session_model.py
|
evernode.models.session_model.SessionModel
|
class SessionModel(BaseModel):
""" class to handle db model for session """
__tablename__ = 'user_sessions'
session_id = Column(String(255), unique=True)
user_id = Column(Integer, ForeignKey('users.id'))
@classmethod
def where_session_id(cls, session_id):
""" Easy way to query by session id """
try:
session = cls.query.filter_by(session_id=session_id).one()
return session
except (NoResultFound, MultipleResultsFound):
return None
@classmethod
def where_user_id(cls, user_id):
""" Easy way to query by user id """
return cls.query.filter_by(user_id=user_id).first()
@classmethod
def where_lastest(cls, user_id):
""" Get lastest session by created_at timestamp """
return cls.query.filter_by(user_id=user_id)\
.order_by(cls.created_at.desc()).first()
@classmethod
def where_earliest(cls, user_id):
""" Get earilest session by created_at timestamp """
return cls.query.filter_by(user_id=user_id)\
.order_by(cls.created_at.asc()).first()
@classmethod
def count(cls, user_id):
""" Count sessions with user_id """
return cls.query.with_entities(
cls.user_id).filter_by(user_id=user_id).count()
|
class SessionModel(BaseModel):
''' class to handle db model for session '''
@classmethod
def where_session_id(cls, session_id):
''' Easy way to query by session id '''
pass
@classmethod
def where_user_id(cls, user_id):
''' Easy way to query by user id '''
pass
@classmethod
def where_lastest(cls, user_id):
''' Get lastest session by created_at timestamp '''
pass
@classmethod
def where_earliest(cls, user_id):
''' Get earilest session by created_at timestamp '''
pass
@classmethod
def count(cls, user_id):
''' Count sessions with user_id '''
pass
| 11 | 6 | 4 | 0 | 3 | 1 | 1 | 0.23 | 1 | 0 | 0 | 0 | 0 | 0 | 5 | 14 | 37 | 5 | 26 | 15 | 15 | 6 | 18 | 10 | 12 | 2 | 3 | 1 | 6 |
7,580 |
AtomHash/evernode
|
AtomHash_evernode/evernode/models/json_model.py
|
evernode.models.json_model.JsonModel
|
class JsonModel:
""" easy class to JSON conversion """
__exclude_list = []
""" add names in here to exclude attributes in serialization """
def add(self, name, value):
""" Add attribute """
setattr(self, name, value)
def remove(self, name):
""" Remove attribute """
del self.__dict__[name]
def __json(self):
"""
Using the exclude lists, convert fields to a string.
"""
if self.exclude_list is None:
self.exclude_list = []
fields = {}
for key, item in vars(self).items():
if hasattr(self, '_sa_instance_state'):
# load only deferred objects
if len(orm.attributes.instance_state(self).unloaded) > 0:
mapper = inspect(self)
for column in mapper.attrs:
column.key
column.value
if str(key).startswith('_') or key in self.exclude_list:
continue
fields[key] = item
obj = Json.safe_object(fields)
return str(obj)
|
class JsonModel:
''' easy class to JSON conversion '''
def add(self, name, value):
''' Add attribute '''
pass
def remove(self, name):
''' Remove attribute '''
pass
def __json(self):
'''
Using the exclude lists, convert fields to a string.
'''
pass
| 4 | 4 | 9 | 0 | 7 | 2 | 3 | 0.36 | 0 | 2 | 1 | 2 | 3 | 1 | 3 | 3 | 34 | 4 | 22 | 11 | 18 | 8 | 22 | 11 | 18 | 7 | 0 | 4 | 9 |
7,581 |
AtomHash/evernode
|
AtomHash_evernode/evernode/models/fail2ban_model.py
|
evernode.models.fail2ban_model.Fail2BanModel
|
class Fail2BanModel(BaseModel):
""" User db model """
__tablename__ = 'evernode_fail2ban'
location = Column(String(100))
ip = Column(String(128)) # support IPv6
attempts = Column(Integer, nullable=False, default=0)
banned_token = Column(String(300))
object_id = Column(Integer)
json_exclude_list = []
@classmethod
def where_ip(cls, ip):
""" Get db model by username """
return cls.query.filter_by(ip=ip).first()
@classmethod
def where_unique(cls, ip, object_id, location):
""" Get db model by username """
return cls.query.filter_by(
ip=ip,
object_id=object_id,
location=location).first()
@classmethod
def where_object_id(cls, object_id):
""" Get db model by object id """
return cls.query.filter_by(object_id=object_id).first()
@classmethod
def delete_where_unique(cls, ip, object_id, location):
""" delete by ip and object id """
result = cls.where_unique(ip, object_id, location)
if result is None:
return None
result.delete()
return True
def generate_banned_token(self, valid_for):
self.banned_token = JWT().create_token({}, valid_for)
self.save()
def is_banned(self) -> bool:
if self.banned_token is None:
return False
banned_status = JWT().verify_token(self.banned_token)
if banned_status:
return True
else:
self.delete()
return False
def add_attempt_or_ban(self, number=1, max_attempts=3, valid_for=1800):
if self.attempts >= max_attempts:
if self.banned_token is not None:
return
self.generate_banned_token(valid_for=valid_for)
else:
self.attempts = self.attempts + number
self.save()
return
|
class Fail2BanModel(BaseModel):
''' User db model '''
@classmethod
def where_ip(cls, ip):
''' Get db model by username '''
pass
@classmethod
def where_unique(cls, ip, object_id, location):
''' Get db model by username '''
pass
@classmethod
def where_object_id(cls, object_id):
''' Get db model by object id '''
pass
@classmethod
def delete_where_unique(cls, ip, object_id, location):
''' delete by ip and object id '''
pass
def generate_banned_token(self, valid_for):
pass
def is_banned(self) -> bool:
pass
def add_attempt_or_ban(self, number=1, max_attempts=3, valid_for=1800):
pass
| 12 | 5 | 6 | 0 | 5 | 1 | 2 | 0.13 | 1 | 2 | 1 | 0 | 3 | 0 | 7 | 16 | 61 | 8 | 48 | 21 | 36 | 6 | 39 | 17 | 31 | 3 | 3 | 2 | 12 |
7,582 |
AtomHash/evernode
|
AtomHash_evernode/evernode/evernode.py
|
evernode.evernode.Evernode
|
class Evernode:
parser = None
args = None
def __init__(self):
self.parser = argparse.ArgumentParser(
description='EverNode helper.',
usage="""evernode <command> [<args>]
EverNode commands are:
init Create a fresh evernode app structure
module Create a module structure
""")
self.parser.add_argument('command', help='run evernode commands')
self.args = self.parser.parse_args(sys.argv[1:2])
getattr(self, self.args.command.lower(), 'help')()
def init(self):
parser = argparse.ArgumentParser(
description='make evernode_<name>')
parser.add_argument('name')
args = parser.parse_args(sys.argv[2:])
Create(args.name)
def module(self):
parser = argparse.ArgumentParser(
description='module commands')
parser.add_argument('command', help='run module commands')
args = parser.parse_args(sys.argv[2:3])
if hasattr(args, 'command'):
command = args.command.lower()
if command == 'init':
parser = argparse.ArgumentParser(
description='module commands')
parser.add_argument('name', help='name of module')
args = parser.parse_args(sys.argv[3:4])
Module(args.name, 'init')
else:
self.help()
def help(self):
print('Need some help?')
self.parser.print_help()
exit(1)
|
class Evernode:
def __init__(self):
pass
def init(self):
pass
def module(self):
pass
def help(self):
pass
| 5 | 0 | 9 | 0 | 9 | 0 | 2 | 0 | 0 | 1 | 0 | 0 | 4 | 0 | 4 | 4 | 45 | 6 | 39 | 12 | 34 | 0 | 29 | 12 | 24 | 3 | 0 | 2 | 6 |
7,583 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/user_auth.py
|
evernode.classes.user_auth.UserAuth
|
class UserAuth:
""" Helper class for creating user based authentication """
algo = None
user = None
user_model = None
username = None
password = None
__username_error = None
__password_error = None
__username_field = None
__password_field = None
def __init__(self, user_model, username_error=None, password_error=None):
self.__username_field = current_app.config['AUTH']['USERNAME_FIELD']
self.__password_field = current_app.config['AUTH']['PASSWORD_FIELD']
self.__username_error = username_error
self.__password_error = password_error
self.user_model = user_model
self.__collect_fields()
def __collect_fields(self):
""" Use field values from config.json and collect from request """
form = FormData()
form.add_field(self.__username_field, required=True,
error=self.__username_error)
form.add_field(self.__password_field, required=True,
error=self.__password_error)
form.parse()
self.username = form.values[self.__username_field]
self.password = form.values[self.__password_field]
return
def session(self) -> str:
""" Generate a session(authorization Bearer) JWT token """
session_jwt = None
self.user = self.user_model.where_username(self.username)
if self.user is None:
return None
self.user.updated() # update timestamp on user access
if self.verify_password(self.user.password):
session_id = Session.create_session_id()
data = {
'session_id': session_id,
'user_id': self.user.id,
'user_email': self.user.email,
}
token_valid_for = \
current_app.config['AUTH']['JWT']['TOKENS']['VALID_FOR'] if \
'VALID_FOR' in \
current_app.config['AUTH']['JWT']['TOKENS'] else 180
if current_app.config['AUTH']['JWT']['REFRESH_TOKENS']['ENABLED']:
refresh_token_valid_for = \
current_app \
.config['AUTH']['JWT']['REFRESH_TOKENS']['VALID_FOR'] if \
'VALID_FOR' in \
current_app.config['AUTH']['JWT']['REFRESH_TOKENS'] else \
86400
session_jwt = JWT().create_token_with_refresh_token(
data,
token_valid_for,
refresh_token_valid_for)
else:
session_jwt = JWT().create_token(data, token_valid_for)
Session.create_session(session_id, self.user.id)
return session_jwt
return None
def verify_password(self, hashed_password) -> bool:
""" Check a password hash """
return Security.verify_hash(self.password, hashed_password)
|
class UserAuth:
''' Helper class for creating user based authentication '''
def __init__(self, user_model, username_error=None, password_error=None):
pass
def __collect_fields(self):
''' Use field values from config.json and collect from request '''
pass
def session(self) -> str:
''' Generate a session(authorization Bearer) JWT token '''
pass
def verify_password(self, hashed_password) -> bool:
''' Check a password hash '''
pass
| 5 | 4 | 14 | 0 | 13 | 1 | 2 | 0.08 | 0 | 6 | 4 | 0 | 4 | 0 | 4 | 4 | 71 | 5 | 62 | 20 | 57 | 5 | 44 | 20 | 39 | 6 | 0 | 2 | 9 |
7,584 |
AtomHash/evernode
|
AtomHash_evernode/evernode/classes/translator.py
|
evernode.classes.translator.Translator
|
class Translator:
""" Uses dot-key syntax to translate phrases to words """
app_language = None
module_name = None
def __init__(self, module_name=None, environ=None):
try:
self.app_language = request.headers.get('Content-Language')
except (Exception, BaseException) as error:
if environ is not None:
if 'HTTP_CONTENT_LANGUAGE' in environ:
self.app_language = environ['HTTP_CONTENT_LANGUAGE']
if environ is None and current_app.config['DEBUG']:
raise RuntimeError('When running out of request context, '
'please specify environ')
if self.app_language is None:
if 'DEFAULT_LANGUAGE' in current_app.config:
self.app_language = current_app.config['DEFAULT_LANGUAGE']
elif 'DEFAULT_LANGUAGE' not in current_app.config:
if current_app.config['DEBUG']:
raise Exception(
'Please set "DEFAULT_LANGUAGE" in evernode config')
else:
# just strip encase of an absolute path in content-language
self.app_language = secure_filename(self.app_language)
self.module_name = module_name
if self.module_name is None:
self.module_name = 'root'
def trans(self, key) -> str:
"""
Root Example:
Translator()
Translator.trans('messages.hello')
resources/lang/en/messages.lang will be opened
and parsed for { 'hello': 'Some english text' }
If language is fr,
resources/lang/fr/messages.lang will be opened
and parsed for { 'hello': 'Some french text' }
Module Example:
Translator('[module-name]')
Translator.trans('messages.hello')
"""
key_list = self.__list_key(key)
try:
current_selection = \
current_app.config['LANGUAGE_PACKS'][
self.module_name][self.app_language]
except KeyError as error:
if current_app.config['DEBUG']:
raise error
return None
for parsed_dot_key in key_list:
try:
current_selection = current_selection[parsed_dot_key]
except (Exception, BaseException) as error:
if current_app.config['DEBUG']:
raise error
return None
return current_selection
def __load_file(self, key_list) -> str:
""" Load a translator file """
file = str(key_list[0]) + self.extension
key_list.pop(0)
file_path = os.path.join(self.path, file)
if os.path.exists(file_path):
return Json.from_file(file_path)
else:
raise FileNotFoundError(file_path)
def __list_key(self, key) -> list:
""" List a trans command by splitting dot-key syntax """
return key.split(".")
|
class Translator:
''' Uses dot-key syntax to translate phrases to words '''
def __init__(self, module_name=None, environ=None):
pass
def trans(self, key) -> str:
'''
Root Example:
Translator()
Translator.trans('messages.hello')
resources/lang/en/messages.lang will be opened
and parsed for { 'hello': 'Some english text' }
If language is fr,
resources/lang/fr/messages.lang will be opened
and parsed for { 'hello': 'Some french text' }
Module Example:
Translator('[module-name]')
Translator.trans('messages.hello')
'''
pass
def __load_file(self, key_list) -> str:
''' Load a translator file '''
pass
def __list_key(self, key) -> list:
''' List a trans command by splitting dot-key syntax '''
pass
| 5 | 4 | 17 | 0 | 13 | 4 | 5 | 0.32 | 0 | 8 | 1 | 0 | 4 | 0 | 4 | 4 | 76 | 6 | 53 | 14 | 48 | 17 | 46 | 12 | 41 | 10 | 0 | 3 | 19 |
7,585 |
AtomHash/evernode
|
AtomHash_evernode/evernode/models/base_user_model.py
|
evernode.models.base_user_model.BaseUserModel
|
class BaseUserModel(BaseModel):
""" User db model """
__tablename__ = 'users'
__table_args__ = {'extend_existing': True}
fullname = Column(String(255))
email = Column(String(255), unique=True)
password = Column(String(1000))
json_exclude_list = ['password', 'updated_at', 'created_at', 'id']
@classmethod
def where_email(cls, email):
""" Get db model by email """
return cls.query.filter_by(email=email).first()
def set_password(self, password):
""" Set user password with hash """
self.password = Security.hash(password)
self.save()
@classmethod
def create_password_reset(cls, email, valid_for=3600) -> str:
"""
Create a password reset request in the user_password_resets
database table. Hashed code gets stored in the database.
Returns unhashed reset code
"""
user = cls.where_email(email)
if user is None:
return None
PasswordResetModel.delete_where_user_id(user.id)
token = JWT().create_token({
'code': Security.random_string(5), # make unique
'user_id': user.id},
token_valid_for=valid_for)
code = Security.generate_uuid(1) + "-" + Security.random_string(5)
password_reset_model = PasswordResetModel()
password_reset_model.token = token
password_reset_model.code = code
password_reset_model.user_id = user.id
password_reset_model.save()
return code
@classmethod
def validate_password_reset(cls, code, new_password):
"""
Validates an unhashed code against a hashed code.
Once the code has been validated and confirmed
new_password will replace the old users password
"""
password_reset_model = \
PasswordResetModel.where_code(code)
if password_reset_model is None:
return None
jwt = JWT()
if jwt.verify_token(password_reset_model.token):
user = cls.where_id(jwt.data['data']['user_id'])
if user is not None:
user.set_password(new_password)
PasswordResetModel.delete_where_user_id(user.id)
return user
password_reset_model.delete() # delete expired/invalid token
return None
@classmethod
def by_current_session(cls):
""" Returns current user session """
session = Session.current_session()
if session is None:
return None
return cls.where_id(session.user_id)
|
class BaseUserModel(BaseModel):
''' User db model '''
@classmethod
def where_email(cls, email):
''' Get db model by email '''
pass
def set_password(self, password):
''' Set user password with hash '''
pass
@classmethod
def create_password_reset(cls, email, valid_for=3600) -> str:
'''
Create a password reset request in the user_password_resets
database table. Hashed code gets stored in the database.
Returns unhashed reset code
'''
pass
@classmethod
def validate_password_reset(cls, code, new_password):
'''
Validates an unhashed code against a hashed code.
Once the code has been validated and confirmed
new_password will replace the old users password
'''
pass
@classmethod
def by_current_session(cls):
''' Returns current user session '''
pass
| 10 | 6 | 11 | 0 | 8 | 3 | 2 | 0.31 | 1 | 5 | 4 | 0 | 1 | 0 | 5 | 14 | 71 | 6 | 51 | 24 | 41 | 16 | 43 | 20 | 37 | 4 | 3 | 2 | 10 |
7,586 |
AtomHash/evernode
|
AtomHash_evernode/evernode/models/base_model.py
|
evernode.models.base_model.BaseModel
|
class BaseModel(DatabaseModel, JsonModel):
""" Adds usefull custom attributes for applciation use """
__abstract__ = True
id = Column(Integer, primary_key=True)
created_at = Column(DateTime, server_default=text('CURRENT_TIMESTAMP'))
updated_at = Column(
DateTime,
server_default=text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'))
def __init__(self):
DatabaseModel.__init__(self)
@classmethod
def where_id(cls, id):
""" Get db model by id """
return cls.query.filter_by(id=id).first()
def exists(self):
""" Checks if item already exists in database """
self_object = self.query.filter_by(id=self.id).first()
if self_object is None:
return False
return True
def updated(self):
""" Update updated_at timestamp """
self.updated_at = datetime.utcnow()
self.save()
def delete(self):
""" Easy delete for db models """
try:
if self.exists() is False:
return None
self.db.session.delete(self)
self.db.session.commit()
except (Exception, BaseException) as error:
# fail silently
return None
def save(self):
""" Easy save(insert or update) for db models """
try:
if self.exists() is False:
self.db.session.add(self)
# self.db.session.merge(self)
self.db.session.commit()
except (Exception, BaseException) as error:
if current_app.config['DEBUG']:
raise error
return None
|
class BaseModel(DatabaseModel, JsonModel):
''' Adds usefull custom attributes for applciation use '''
def __init__(self):
pass
@classmethod
def where_id(cls, id):
''' Get db model by id '''
pass
def exists(self):
''' Checks if item already exists in database '''
pass
def updated(self):
''' Update updated_at timestamp '''
pass
def delete(self):
''' Easy delete for db models '''
pass
def save(self):
''' Easy save(insert or update) for db models '''
pass
| 8 | 6 | 6 | 0 | 5 | 1 | 2 | 0.22 | 2 | 3 | 0 | 5 | 5 | 0 | 6 | 9 | 52 | 7 | 37 | 14 | 29 | 8 | 34 | 11 | 27 | 4 | 2 | 2 | 12 |
7,587 |
AtomHash/evernode
|
AtomHash_evernode/evernode/middleware/session_middleware.py
|
evernode.middleware.session_middleware.SessionMiddleware
|
class SessionMiddleware(Middleware):
""" Middleware to handle sessions with JWT """
def condition(self) -> bool:
""" check JWT, then check session for validity """
jwt = JWT()
if jwt.verify_http_auth_token():
if not current_app.config['AUTH']['FAST_SESSIONS']:
session = SessionModel.where_session_id(
jwt.data['session_id'])
if session is None:
return False
Session.set_current_session(jwt.data['session_id'])
return True
return False
def create_response(self):
""" return 401 on invalid tokens """
self.response = JsonResponse(401)
|
class SessionMiddleware(Middleware):
''' Middleware to handle sessions with JWT '''
def condition(self) -> bool:
''' check JWT, then check session for validity '''
pass
def create_response(self):
''' return 401 on invalid tokens '''
pass
| 3 | 3 | 8 | 0 | 7 | 1 | 3 | 0.21 | 1 | 5 | 4 | 0 | 2 | 1 | 2 | 5 | 19 | 2 | 14 | 6 | 11 | 3 | 13 | 6 | 10 | 4 | 1 | 3 | 5 |
7,588 |
AtomHash/evernode
|
AtomHash_evernode/evernode/models/password_reset_model.py
|
evernode.models.password_reset_model.PasswordResetModel
|
class PasswordResetModel(BaseModel):
""" Password Reset db Model """
__tablename__ = 'user_password_resets'
token = Column(String(1000))
code = Column(String(70))
user_id = Column(Integer, ForeignKey('users.id'))
@classmethod
def where_token(cls, token):
""" get by token """
return cls.query.filter_by(token=token).first()
@classmethod
def where_code(cls, code):
""" get by code """
return cls.query.filter_by(code=code).first()
@classmethod
def where_user_id(cls, user_id):
""" get by user_id """
return cls.query.filter_by(user_id=user_id).first()
@classmethod
def delete_where_user_id(cls, user_id):
""" delete by email """
result = cls.where_user_id(user_id)
if result is None:
return None
result.delete()
return True
|
class PasswordResetModel(BaseModel):
''' Password Reset db Model '''
@classmethod
def where_token(cls, token):
''' get by token '''
pass
@classmethod
def where_code(cls, code):
''' get by code '''
pass
@classmethod
def where_user_id(cls, user_id):
''' get by user_id '''
pass
@classmethod
def delete_where_user_id(cls, user_id):
''' delete by email '''
pass
| 9 | 5 | 4 | 0 | 3 | 1 | 1 | 0.24 | 1 | 0 | 0 | 0 | 0 | 0 | 4 | 13 | 31 | 5 | 21 | 14 | 12 | 5 | 17 | 10 | 12 | 2 | 3 | 1 | 5 |
7,589 |
Atomistica/atomistica
|
Atomistica_atomistica/examples/ASE/liquid_tools.py
|
liquid_tools.PairAndAngleDistribution
|
class PairAndAngleDistribution:
def __init__(self, calc, paircutoff, anglecutoff, npairbins=100,
nanglebins=100, avgn=1000):
self.calc = calc
# Instantiate an MDCORE neighbor list object, *avgn* is the
# average number of neighbors per atom.
self.nl = native.Neighbors(avgn)
# Ask the neighbor list to compute neighbors at least up to
# cutoff *cutoff*. Neighbor list may contain farther atoms.
self.nl.request_interaction_range(max(paircutoff, anglecutoff))
self.paircutoff = paircutoff
self.anglecutoff = anglecutoff
self.npairbins = npairbins
self.nanglebins = nanglebins
self.pair_hist = None
self.pair_hist_var = None
self.angle_hist = None
self.angle_hist_var = None
self.navg = 0
def __call__(self):
# Construct neighbor list and return neighbors. Return are a
# list of integers *i* and *j* that denote the neighbor pair.
# List *r* contains the distance. If you want to loop over all
# neighbors and get the distance use
# for ii, jj, rr in zip(i,j,r):
i, j, dr, abs_dr = self.nl.get_neighbors(self.calc.particles, vec=True)
pavg, pvar = native.pair_distribution(i, abs_dr, self.npairbins,
self.paircutoff)
aavg, avar = native.angle_distribution(i, j, dr, self.nanglebins,
self.anglecutoff)
if self.pair_hist is None:
self.pair_hist = pavg
self.pair_hist_var = pvar
self.angle_hist = aavg
self.angle_hist_var = avar
self.navg = 1
else:
self.pair_hist += pavg
self.pair_hist_var += pvar
self.angle_hist += aavg
self.angle_hist_var += avar
self.navg += 1
def get_pair_hist(self):
return self.pair_hist/self.navg
def get_angle_hist(self):
return self.angle_hist/self.navg
def get_pair_variance(self):
return self.pair_hist_var/self.navg
def get_angle_variance(self):
return self.angle_hist_var/self.navg
|
class PairAndAngleDistribution:
def __init__(self, calc, paircutoff, anglecutoff, npairbins=100,
nanglebins=100, avgn=1000):
pass
def __call__(self):
pass
def get_pair_hist(self):
pass
def get_angle_hist(self):
pass
def get_pair_variance(self):
pass
def get_angle_variance(self):
pass
| 7 | 0 | 9 | 1 | 7 | 2 | 1 | 0.22 | 0 | 0 | 0 | 0 | 6 | 11 | 6 | 6 | 58 | 8 | 41 | 22 | 33 | 9 | 37 | 21 | 30 | 2 | 0 | 1 | 7 |
7,590 |
Atomistica/atomistica
|
Atomistica_atomistica/tests/test_bulk_properties.py
|
test_bulk_properties.TestElasticConstants
|
class TestElasticConstants(unittest.TestCase):
def test_elastic_constants(self):
for pot, par, mats in tests:
cubic_elastic_constants(mats, pot, par, sx, dev_thres,
test=self)
|
class TestElasticConstants(unittest.TestCase):
def test_elastic_constants(self):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 6 | 1 | 5 | 3 | 3 | 0 | 4 | 3 | 2 | 2 | 2 | 1 | 2 |
7,591 |
Atomistica/atomistica
|
Atomistica_atomistica/examples/ASE/liquid_tools.py
|
liquid_tools.CoordinationCount
|
class CoordinationCount:
def __init__(self, dyn, calc, cutoff, maxc=10, logfile=None):
self.dyn = dyn
self.calc = calc
self.cutoff = cutoff
self.maxc = maxc
self.hist = np.zeros(maxc, dtype=int)
self.navg = 0
self.logfile = logfile
if isinstance(logfile, str):
self.logfile = open(logfile, 'w')
self.fmt = '{0:.2f}'
for i in range(maxc+1):
self.fmt += ' {{{0}}}'.format(i+1)
self.fmt += '\n'
def __call__(self):
c = self.calc.nl.get_coordination_numbers(self.calc.particles,
self.cutoff)
hist = np.bincount(c)
if len(hist) < self.maxc:
hist = np.append(hist, np.zeros(self.maxc-len(hist), dtype=int))
self.hist += hist
self.navg += 1
if self.logfile is not None:
self.hist /= self.navg
self.hist = np.append(self.hist, np.sum(self.hist))
self.logfile.write(self.fmt.format(self.dyn.get_time()/(1000*fs),
*self.hist))
self.hist = np.zeros(self.maxc, dtype=int)
self.navg = 0
def get_hist(self):
return self.hist/self.navg
|
class CoordinationCount:
def __init__(self, dyn, calc, cutoff, maxc=10, logfile=None):
pass
def __call__(self):
pass
def get_hist(self):
pass
| 4 | 0 | 12 | 2 | 10 | 0 | 2 | 0 | 0 | 3 | 0 | 0 | 3 | 8 | 3 | 3 | 41 | 9 | 32 | 15 | 28 | 0 | 30 | 15 | 26 | 3 | 0 | 1 | 7 |
7,592 |
Atomistica/atomistica
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Atomistica_atomistica/versioneer.py
|
versioneer.get_cmdclass.cmd_build_exe
|
class cmd_build_exe(_build_exe):
def run(self):
root = get_root()
cfg = get_config_from_root(root)
versions = get_versions()
target_versionfile = cfg.versionfile_source
print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile, versions)
_build_exe.run(self)
os.unlink(target_versionfile)
with open(cfg.versionfile_source, "w") as f:
LONG = LONG_VERSION_PY[cfg.VCS]
f.write(LONG %
{"DOLLAR": "$",
"STYLE": cfg.style,
"TAG_PREFIX": cfg.tag_prefix,
"PARENTDIR_PREFIX": cfg.parentdir_prefix,
"VERSIONFILE_SOURCE": cfg.versionfile_source,
})
|
class cmd_build_exe(_build_exe):
def run(self):
pass
| 2 | 0 | 19 | 1 | 18 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 20 | 1 | 19 | 8 | 17 | 0 | 13 | 7 | 11 | 1 | 1 | 1 | 1 |
7,593 |
Atomistica/atomistica
|
Atomistica_atomistica/src/python/atomistica/hardware.py
|
atomistica.hardware.ComputeCluster
|
class ComputeCluster:
def __init__(self, architecture=None):
if architecture:
self.arch = architecture
try:
self.data = _hardware_info[architecture]
return
except KeyError:
raise KeyError(
'Architecture {0} unknown, known are\n'.format(
architecture) + self.list_architectures())
def get_hostname():
if os.path.isfile('/etc/FZJ/systemname'):
with open('/etc/FZJ/systemname', "r") as f:
return f.read().strip()
if 'HOSTNAME' in list(os.environ.keys()):
return os.environ['HOSTNAME']
try:
import socket
return socket.gethostname().split('-')[0]
except:
dummy, hostname = os.popen4('hostname -s')
return hostname.readline().split()
def has_key_regexp(dictionary, expression):
for key in dictionary:
if re.match(key, expression):
return True
return False
hostname = get_hostname()
for host in _hardware_info:
d = _hardware_info[host]
if has_key_regexp(d['loginnodes'], hostname):
self.arch = host
self.data = d
return
raise KeyError('Host {0} unknown, try -a option.\n'.format(hostname) +
self.list_architectures())
def list_architectures(self):
string = ''
for arch in _hardware_info:
string += ' {0}\n'.format(arch)
return string
def write(self, filename=None, **set):
if filename is None:
filename = 'run.' + self.arch
f = open(filename, 'w')
env = os.environ
d = self.data['scheduler']
c = d['cmdstr']
print('#!/bin/bash -x', file=f)
print(c + d['name'] + set['name'].replace('+', ''), file=f)
cores = set['cores']
cores_per_node = self.data['cores_per_node']
if set['smt']:
cores_per_node *= 2
nodes = int((cores + (cores_per_node - 1)) / cores_per_node)
ppn = int((cores + nodes - 1) / nodes)
if cores != nodes * ppn:
print('Note:', nodes * ppn, 'cores reserved but only', cores,
'cores used.')
print(' Consider to use multiples of', cores_per_node, end=' ')
print('processors for best performance.')
print(c + d['nodes'] + str(nodes), file=f, end='')
if 'ppn' in d:
print(d['ppn'] + str(ppn), file=f)
else:
print(file=f)
print(c + '--ntasks-per-node=' + str(ppn), file=f)
print(c + d['walltime'] + hms_string(set['time']), file=f)
if set['mail'] is not None:
print(c + '--mail-user=' + set['mail'], file=f)
print(c + d['mailtype'], file=f)
print('cd', set['wd'], file=f)
# atomistica uses OMP for parallelization
print('export OMP_NUM_THREADS=$PBS_NP', file=f)
# copy current module environment
print('export MODULEPATH=' + env['MODULEPATH'], file=f)
for module in env['LOADEDMODULES'].split(':'):
print('module load', module, file=f)
print('python', set['script'], end=' ', file=f)
if 'parameters' in set:
print(set['parameters'], end=' ', file=f)
print('>', set['out'] + '_' + d['jobid'], end=' ', file=f)
print('2>', set['err'] + '_' + d['jobid'], file=f)
f.close()
return filename
|
class ComputeCluster:
def __init__(self, architecture=None):
pass
def get_hostname():
pass
def has_key_regexp(dictionary, expression):
pass
def list_architectures(self):
pass
def write(self, filename=None, **set):
pass
| 6 | 0 | 23 | 3 | 20 | 1 | 4 | 0.04 | 0 | 4 | 0 | 0 | 3 | 2 | 3 | 3 | 100 | 14 | 84 | 26 | 77 | 3 | 79 | 25 | 72 | 8 | 0 | 2 | 22 |
7,594 |
Atomistica/atomistica
|
Atomistica_atomistica/src/python/atomistica/deformation.py
|
atomistica.deformation.RemoveSimpleShearDeformation
|
class RemoveSimpleShearDeformation:
"""
Remove a homogeneous cell deformation given an (iterable) trajectory
object. This will take proper care of cells that are instantaneously
flipped from +0.5 strain to -0.5 strain during simple shear, as e.g.
generated by LAMMPS.
"""
def __init__(self, traj):
self.traj = traj
self.last_d = [ ]
self.sheared_cells = [ ]
self.unsheared_cells = [ ]
def _fill_cell_info_upto(self, i):
# Iterate up to frame i the full trajectory first and generate a list
# of cell vectors.
if i < len(self.last_d):
return
# Iterate up to frame i the full trajectory first and generate a list
# of cell vectors.
if len(self.last_d) == 0:
i0 = 0
last_dx, last_dy = get_shear_distance(self.traj[0])
dx = last_dx
dy = last_dy
else:
i0 = len(self.last_d)
last_dx, last_dy = self.last_d[i0-1]
dx, dy, dummy = self.sheared_cells[i0-1][2]
for a in self.traj[i0:i+1]:
sx, sy, sz = a.cell.diagonal()
cur_dx, cur_dy = get_shear_distance(a)
while cur_dx-last_dx < -sx/2:
cur_dx += sx
dx += cur_dx-last_dx
while cur_dy-last_dy < -sy/2:
cur_dy += sy
dy += cur_dy-last_dy
# Store last shear distance
last_dx = cur_dx
last_dy = cur_dy
# Store cells and shear distance
self.last_d += [ ( last_dx, last_dy ) ]
self.sheared_cells += [ np.array([[sx,0,0],[0,sy,0],[dx,dy,sz]]) ]
self.unsheared_cells += [ np.array([sx,sy,sz]) ]
def __getitem__(self, i=-1):
if i < 0:
i = len(self) + i
if i < 0 or i >= len(self):
raise IndexError('Trajectory index out of range.')
self._fill_cell_info_upto(i)
a = self.traj[i]
# Set true cell shape
a.set_cell(self.sheared_cells[i], scale_atoms=False)
# Unshear
a.set_cell(self.unsheared_cells[i], scale_atoms=True)
# Wrap to cell
a.set_scaled_positions(a.get_scaled_positions()%1.0)
a.info['true_cell'] = self.sheared_cells[i]
return a
def __len__(self):
return len(self.traj)
|
class RemoveSimpleShearDeformation:
'''
Remove a homogeneous cell deformation given an (iterable) trajectory
object. This will take proper care of cells that are instantaneously
flipped from +0.5 strain to -0.5 strain during simple shear, as e.g.
generated by LAMMPS.
'''
def __init__(self, traj):
pass
def _fill_cell_info_upto(self, i):
pass
def __getitem__(self, i=-1):
pass
def __len__(self):
pass
| 5 | 1 | 17 | 3 | 11 | 2 | 3 | 0.33 | 0 | 1 | 0 | 0 | 4 | 4 | 4 | 4 | 81 | 20 | 46 | 18 | 41 | 15 | 45 | 18 | 40 | 6 | 0 | 2 | 11 |
7,595 |
Atomistica/atomistica
|
Atomistica_atomistica/src/python/atomistica/aseinterface.py
|
atomistica.aseinterface.Atomistica
|
class Atomistica(Calculator):
"""
Atomistica ASE calculator.
"""
implemented_properties = ['energy', 'free_energy', 'stress', 'forces', 'charges']
default_parameters = {}
CELL_TOL = 1e-16
POSITIONS_TOL = 1e-16
name = 'Atomistica'
potential_class = None
avgn = 100
def __init__(self, potentials=None, avgn=None, **kwargs):
"""
Initialize a potential. *potential* is the a native Atomistica
potential class, in which case the arguments are given by the
keywords of this function. Alternatively, it can be a list of tuples
[ ( pot1, args1 ), ... ] in which case *pot1* is the name of the
first potential and *args1* a dictionary containing its arguments.
"""
Calculator.__init__(self)
# List of potential objects
self.pots = [ ]
# List of Coulomb solvers
self.couls = [ ]
# Loop over all potentials and check whether it is a potntial or a
# Coulomb solver. Create two separate lists.
if potentials is not None:
for pot in potentials:
if isinstance(pot, Atomistica):
raise TypeError('Potential passed to Atomistica class is '
'already an Atomistica object. This does '
'not work. You need to pass native '
'potential from atomistica.native or '
'_atomistica.')
if hasattr(pot, 'potential'):
self.couls += [ pot ]
else:
self.pots += [ pot ]
else:
pot = self.potential_class(**convpar(kwargs))
if hasattr(pot, 'potential'):
self.couls += [ pot ]
else:
self.pots += [ pot ]
if avgn:
self.avgn = avgn
self.particles = None
self.nl = None
self.charges = None
self.initial_charges = None
self.mask = None
self.properties_changed = []
self.kwargs = kwargs
self.compute_epot_per_bond = False
self.compute_f_per_bond = False
self.compute_wpot_per_at = False
self.compute_wpot_per_bond = False
self.epot_per_bond = None
self.f_per_bond = None
self.wpot_per_bond = None
def todict(self):
return self.kwargs
def check_state(self, atoms):
return super().check_state(atoms) + self.properties_changed
def initialize(self, atoms):
if self.mask is not None:
if len(self.mask) != len(atoms):
raise RuntimeError('Length of mask array (= {0}) does not '
'equal number of atoms (= {1}).'
.format(len(self.mask), len(atoms)))
pbc = atoms.get_pbc()
self.particles = _atomistica.Particles()
for pot in self.pots:
pot.register_data(self.particles)
self.particles.allocate(len(atoms))
self.particles.set_cell(atoms.get_cell(), pbc)
Z = self.particles.Z
for i, at in enumerate(atoms):
Z[i] = atomic_numbers[at.symbol]
self.particles.coordinates[:, :] = \
atoms.positions - atoms.get_celldisp().ravel()
# Notify the Particles object of a change
self.particles.I_changed_positions()
self.particles.update_elements()
# Initialize and set neighbor list
self.nl = _atomistica.Neighbors(self.avgn)
# Tell the potential about the new Particles and Neighbors object
for pot in self.pots:
pot.bind_to(self.particles, self.nl)
if len(self.couls) > 0:
if atoms.has('initial_charges'):
if self.charges is None or len(self.charges) != len(atoms) or \
(self.initial_charges is not None and \
np.any(atoms.get_array('initial_charges') != self.initial_charges)\
):
self.charges = atoms.get_array('initial_charges')
self.initial_charges = self.charges.copy()
if self.charges is None or len(self.charges) != len(atoms):
self.charges = np.zeros(len(atoms))
self.E = np.zeros([3, len(atoms)])
# Coulomb callback should be directed to this wrapper object
for pot in self.pots:
pot.set_Coulomb(self)
for coul in self.couls:
coul.bind_to(self.particles, self.nl)
# Force re-computation of energies/forces the next time these are
# requested
self.properties_changed = all_changes
def set_mask(self, mask):
if np.any(self.mask != mask):
self.mask = mask
self.properties_changed += ['mask']
def set_per_bond(self, epot=None, f=None, wpot=None):
if epot is not None:
self.compute_epot_per_bond = epot
if f is not None:
self.compute_f_per_bond = f
if wpot is not None:
self.compute_wpot_per_bond = wpot
self.properties_changed += ['per_bond']
def update(self, atoms):
if atoms is None:
return
# Number of particles changed? -> Reinitialize potential
if self.particles is None or len(self.particles.Z) != len(atoms) or \
(self.charges is not None and len(self.charges) != len(atoms)):
self.initialize(atoms)
# Type of particles changed? -> Reinitialize potential
elif np.any(self.particles.Z != atoms.get_atomic_numbers()):
self.initialize(atoms)
# Cell or pbc changed?
cell = self.particles.cell
pbc = self.particles.pbc
#if np.any(np.abs(cell - atoms.get_cell()) > self.CELL_TOL):
if np.any(cell != atoms.get_cell()) or np.any(pbc != atoms.get_pbc()):
self.particles.set_cell(atoms.get_cell(), atoms.get_pbc())
# Positions changed?
positions = self.particles.coordinates
if np.any(positions != atoms.positions - atoms.get_celldisp().ravel()):
positions[:, :] = atoms.positions - atoms.get_celldisp().ravel()
# Notify the Particles object of a change
self.particles.I_changed_positions()
if atoms.has('initial_charges') and self.initial_charges is not None and \
np.any(atoms.get_array('initial_charges') != self.initial_charges):
self.charges = atoms.get_array('initial_charges')
self.initial_charges = self.charges.copy()
def get_potential_energies(self, atoms):
self.calculate(atoms, ['energies'], [])
return self.results['energies']
def get_stresses(self, atoms):
self.calculate(atoms, ['stresses'], [])
return self.results['stresses']
def get_electrostatic_potential(self, atoms=None):
self.phi = np.zeros(len(self.particles))
self.potential(self.particles, self.nl, self.charges, self.phi)
return self.phi
def get_per_bond_property(self, name):
for pot in self.pots:
if hasattr(pot, 'get_per_bond_property'):
return pot.get_per_bond_property(self.particles, self.nl, name)
def calculate(self, atoms, properties, system_changes):
Calculator.calculate(self, atoms, properties, system_changes)
self.update(atoms)
epot = 0.0
forces = np.zeros([len(self.particles),3])
wpot = np.zeros([3,3])
self.results = {}
compute_epot_per_at = 'energies' in properties
compute_wpot_per_at = 'stresses' in properties
kwargs = dict(epot_per_at = compute_epot_per_at,
epot_per_bond = self.compute_epot_per_bond,
f_per_bond = self.compute_f_per_bond,
wpot_per_at = compute_wpot_per_at,
wpot_per_bond = self.compute_wpot_per_bond)
if self.mask is not None:
kwargs['mask'] = self.mask
if self.charges is None:
# No charges? Just call the potentials...
for pot in self.pots:
_epot, _forces, _wpot, epot_per_at, self.epot_per_bond, \
self.f_per_bond, wpot_per_at, self.wpot_per_bond = \
pot.energy_and_forces(self.particles, self.nl,
forces = forces,
**kwargs)
epot += _epot
wpot += _wpot
else:
# Charges? Pass charge array to potentials and ...
for pot in self.pots:
_epot, _forces, _wpot, epot_per_at, self.epot_per_bond, \
self.f_per_bond, wpot_per_at, self.wpot_per_bond = \
pot.energy_and_forces(self.particles, self.nl,
forces = forces,
charges = self.charges,
**kwargs)
epot += _epot
wpot += _wpot
# ... call Coulomb solvers to get potential and fields
epot_coul = 0.0
forces_coul = np.zeros([len(self.particles),3])
wpot_coul = np.zeros([3,3])
for coul in self.couls:
_epot, _forces, _wpot = \
coul.energy_and_forces(self.particles, self.nl,
self.charges, forces_coul)
epot_coul += _epot
wpot_coul += _wpot
# Convert units
epot_coul *= Hartree * Bohr
forces_coul *= Hartree * Bohr
wpot_coul *= Hartree * Bohr
epot += epot_coul
wpot += wpot_coul
# Sum forces
forces += forces_coul
self.results['charges'] = self.charges
self.results['energy'] = epot
self.results['free_energy'] = epot
# Convert to Voigt
volume = self.atoms.get_volume()
self.results['stress'] = np.array([wpot[0,0], wpot[1,1], wpot[2,2],
(wpot[1,2]+wpot[2,1])/2,
(wpot[0,2]+wpot[2,0])/2,
(wpot[0,1]+wpot[1,0])/2])/volume
self.results['forces'] = forces
if compute_epot_per_at:
self.results['energies'] = epot_per_at
if compute_wpot_per_at:
# Convert to Voigt
self.results['stresses'] = \
np.transpose([wpot_per_at[:,0,0],
wpot_per_at[:,1,1],
wpot_per_at[:,2,2],
(wpot_per_at[:,1,2]+wpot_per_at[:,2,1])/2,
(wpot_per_at[:,0,2]+wpot_per_at[:,2,0])/2,
(wpot_per_at[:,0,1]+wpot_per_at[:,1,0])/2])
self.properties_changed = []
def get_atomic_stress(self):
r = np.zeros( [ 3, 3, len(self.particles) ] )
for i, a in enumerate(self.particles):
r[:, :, i] = a.w
return r
def get_neighbors(self):
return self.nl.get_neighbors(self.particles)
def __str__(self):
s = 'Atomistica(['
for pot in self.pots:
s += pot.__str__()+','
for coul in self.couls:
s += coul.__str__()+','
return s[:-1]+'])'
### Coulomb solver callback
def set_Hubbard_U(self, p, U):
assert p is self.particles
for coul in self.couls:
coul.set_Hubbard_U(p, U)
def potential(self, p, nl, q, phi):
assert p is self.particles
assert nl is self.nl
_phi = np.zeros_like(phi)
for coul in self.couls:
coul.potential(p, nl, q, _phi)
phi += _phi * Hartree * Bohr
|
class Atomistica(Calculator):
'''
Atomistica ASE calculator.
'''
def __init__(self, potentials=None, avgn=None, **kwargs):
'''
Initialize a potential. *potential* is the a native Atomistica
potential class, in which case the arguments are given by the
keywords of this function. Alternatively, it can be a list of tuples
[ ( pot1, args1 ), ... ] in which case *pot1* is the name of the
first potential and *args1* a dictionary containing its arguments.
'''
pass
def todict(self):
pass
def check_state(self, atoms):
pass
def initialize(self, atoms):
pass
def set_mask(self, mask):
pass
def set_per_bond(self, epot=None, f=None, wpot=None):
pass
def update(self, atoms):
pass
def get_potential_energies(self, atoms):
pass
def get_stresses(self, atoms):
pass
def get_electrostatic_potential(self, atoms=None):
pass
def get_per_bond_property(self, name):
pass
def calculate(self, atoms, properties, system_changes):
pass
def get_atomic_stress(self):
pass
def get_neighbors(self):
pass
def __str__(self):
pass
def set_Hubbard_U(self, p, U):
pass
def potential(self, p, nl, q, phi):
pass
| 18 | 2 | 17 | 3 | 13 | 2 | 3 | 0.15 | 1 | 5 | 0 | 1 | 17 | 19 | 17 | 17 | 343 | 80 | 229 | 76 | 211 | 34 | 188 | 75 | 170 | 12 | 1 | 3 | 58 |
7,596 |
Atomistica/atomistica
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Atomistica_atomistica/src/python/atomistica/aseinterface.py
|
atomistica.aseinterface.TightBinding
|
class TightBinding(Atomistica):
"""Non-orthogonal tight-binding.
"""
potential_class = _atomistica.TightBinding
def __init__(self, width=0.1, database_folder=None):
# Translate from a human friendly format
d = {
"SolverLAPACK": {
"electronic_T": width
}
}
if database_folder is not None:
d["database_folder"] = database_folder
d['avgn'] = 1000
Atomistica.__init__(self, **d)
|
class TightBinding(Atomistica):
'''Non-orthogonal tight-binding.
'''
def __init__(self, width=0.1, database_folder=None):
pass
| 2 | 1 | 15 | 4 | 10 | 1 | 2 | 0.25 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 18 | 21 | 6 | 12 | 4 | 10 | 3 | 8 | 4 | 6 | 2 | 2 | 1 | 2 |
7,597 |
Atomistica/atomistica
|
Atomistica_atomistica/tests/test_coulomb.py
|
test_coulomb.CoulombTest
|
class CoulombTest(unittest.TestCase):
def test_direct_coulomb(self):
a = ase.Atoms('NaCl', positions=[[-1.0, 0, 0], [1.0, 0, 0]], pbc=False)
a.center(vacuum=10.0)
a.set_initial_charges(np.zeros(len(a)))
c = DirectCoulomb()
a.calc = c
assert a.get_potential_energy() == 0
assert (np.abs(c.get_electrostatic_potential()) < 1e-9).all()
a.set_initial_charges([-1,1])
c = DirectCoulomb()
a.calc = c
assert abs(a.get_potential_energy()+Hartree*Bohr/2) < 1e-9
assert (np.abs(c.get_electrostatic_potential()-Hartree*Bohr/2*np.array([1,-1])) < 1e-9).all()
|
class CoulombTest(unittest.TestCase):
def test_direct_coulomb(self):
pass
| 2 | 0 | 19 | 6 | 13 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 21 | 7 | 14 | 4 | 12 | 0 | 14 | 4 | 12 | 1 | 2 | 0 | 1 |
7,598 |
Atomistica/atomistica
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Atomistica_atomistica/versioneer.py
|
versioneer.get_cmdclass.cmd_version
|
class cmd_version(Command):
description = "report generated version string"
user_options = []
boolean_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
vers = get_versions(verbose=True)
print("Version: %s" % vers["version"])
print(" full-revisionid: %s" % vers.get("full-revisionid"))
print(" dirty: %s" % vers.get("dirty"))
print(" date: %s" % vers.get("date"))
if vers["error"]:
print(" error: %s" % vers["error"])
|
class cmd_version(Command):
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
pass
| 4 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 19 | 3 | 16 | 8 | 12 | 0 | 16 | 8 | 12 | 2 | 1 | 1 | 4 |
7,599 |
Atomistica/atomistica
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Atomistica_atomistica/versioneer.py
|
versioneer.get_cmdclass.cmd_sdist
|
class cmd_sdist(_sdist):
def run(self):
versions = get_versions()
self._versioneer_generated_versions = versions
# unless we update this, the command will keep using the old
# version
self.distribution.metadata.version = versions["version"]
return _sdist.run(self)
def make_release_tree(self, base_dir, files):
root = get_root()
cfg = get_config_from_root(root)
_sdist.make_release_tree(self, base_dir, files)
# now locate _version.py in the new base_dir directory
# (remembering that it may be a hardlink) and replace it with an
# updated value
target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile,
self._versioneer_generated_versions)
|
class cmd_sdist(_sdist):
def run(self):
pass
def make_release_tree(self, base_dir, files):
pass
| 3 | 0 | 9 | 0 | 7 | 3 | 1 | 0.36 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 20 | 1 | 14 | 8 | 11 | 5 | 13 | 8 | 10 | 1 | 1 | 0 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.