本文整理汇总了Python中tower_cli.api.client.post函数的典型用法代码示例。如果您正苦于以下问题:Python post函数的具体用法?Python post怎么用?Python post使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了post函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: login
def login(username, password, scope, client_id, client_secret, verbose):
"""
Retrieves and stores an OAuth2 personal auth token.
"""
if not supports_oauth():
raise exc.TowerCLIError(
'This version of Tower does not support OAuth2.0. Set credentials using tower-cli config.'
)
# Explicitly set a basic auth header for PAT acquisition (so that we don't
# try to auth w/ an existing user+pass or oauth2 token in a config file)
req = collections.namedtuple('req', 'headers')({})
if client_id and client_secret:
HTTPBasicAuth(client_id, client_secret)(req)
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
r = client.post(
'/o/token/',
data={
"grant_type": "password",
"username": username,
"password": password,
"scope": scope
},
headers=req.headers
)
elif client_id:
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
r = client.post(
'/o/token/',
data={
"grant_type": "password",
"username": username,
"password": password,
"client_id": client_id,
"scope": scope
},
headers=req.headers
)
else:
HTTPBasicAuth(username, password)(req)
r = client.post(
'/users/{}/personal_tokens/'.format(username),
data={"description": "Tower CLI", "application": None, "scope": scope},
headers=req.headers
)
if r.ok:
result = r.json()
result.pop('summary_fields', None)
result.pop('related', None)
if client_id:
token = result.pop('access_token', None)
else:
token = result.pop('token', None)
if settings.verbose:
# only print the actual token if -v
result['token'] = token
secho(json.dumps(result, indent=1), fg='blue', bold=True)
config.main(['oauth_token', token, '--scope=user'])
示例2: role_write
def role_write(self, fail_on_found=False, disassociate=False, **kwargs):
"""Re-implementation of the parent `write` method specific to roles.
Adds a grantee (user or team) to the resource's role."""
# Get the role, using only the resource data
data, self.endpoint = self.data_endpoint(kwargs, ignore=['obj'])
debug.log('Checking if role exists.', header='details')
response = self.read(pk=None, fail_on_no_results=True,
fail_on_multiple_results=True, **data)
role_data = response['results'][0]
role_id = role_data['id']
# Role exists, change display settings to output something
self.configure_display(role_data, kwargs, write=True)
# Check if user/team has this role
# Implictly, force_on_exists is false for roles
obj, obj_type, res, res_type = self.obj_res(kwargs)
debug.log('Checking if %s already has role.' % obj_type,
header='details')
data, self.endpoint = self.data_endpoint(kwargs)
data['content_type__model'] = res_type.replace('_', '')
response = self.read(pk=None, fail_on_no_results=False,
fail_on_multiple_results=False, **data)
msg = ''
if response['count'] > 0 and not disassociate:
msg = 'This %s is already a member of the role.' % obj_type
elif response['count'] == 0 and disassociate:
msg = 'This %s is already a non-member of the role.' % obj_type
if msg:
role_data['changed'] = False
if fail_on_found:
raise exc.NotFound(msg)
else:
debug.log(msg, header='DECISION')
return role_data
# Add or remove the user/team to the role
debug.log('Attempting to %s the %s in this role.' % (
'remove' if disassociate else 'add', obj_type), header='details')
post_data = {'id': role_id}
if disassociate:
post_data['disassociate'] = True
client.post('%s/%s/roles/' % (grammar.pluralize(obj_type), obj),
data=post_data)
role_data['changed'] = True
return role_data
示例3: callback
def callback(self, pk=None, host_config_key='', extra_vars=None):
"""Contact Tower and request a configuration update using this job template.
=====API DOCS=====
Contact Tower and request a provisioning callback using this job template.
:param pk: Primary key of the job template to run provisioning callback against.
:type pk: int
:param host_config_key: Key string used to authenticate the callback host.
:type host_config_key: str
:param extra_vars: Extra variables that are passed to provisioning callback.
:type extra_vars: array of str
:returns: A dictionary of a single key "changed", which indicates whether the provisioning callback
is successful.
:rtype: dict
=====API DOCS=====
"""
url = self.endpoint + '%s/callback/' % pk
if not host_config_key:
host_config_key = client.get(url).json()['host_config_key']
post_data = {'host_config_key': host_config_key}
if extra_vars:
post_data['extra_vars'] = parser.process_extra_vars(list(extra_vars), force_json=True)
r = client.post(url, data=post_data, auth=None)
if r.status_code == 201:
return {'changed': True}
示例4: update
def update(self, inventory_source, monitor=False, timeout=None, **kwargs):
"""Update the given inventory source."""
# Establish that we are able to update this inventory source
# at all.
debug.log('Asking whether the inventory source can be updated.',
header='details')
r = client.get('%s%d/update/' % (self.endpoint, inventory_source))
if not r.json()['can_update']:
raise exc.BadRequest('Tower says it cannot run an update against '
'this inventory source.')
# Run the update.
debug.log('Updating the inventory source.', header='details')
r = client.post('%s%d/update/' % (self.endpoint, inventory_source))
# If we were told to monitor the project update's status, do so.
if monitor:
result = self.monitor(inventory_source, timeout=timeout)
inventory = client.get('/inventory_sources/%d/' %
result['inventory_source'])\
.json()['inventory']
result['inventory'] = int(inventory)
return result
# Done.
return {'status': 'ok'}
示例5: cancel
def cancel(self, pk, fail_if_not_running=False):
"""Cancel a currently running job.
Fails with a non-zero exit status if the job cannot be canceled.
"""
# Attempt to cancel the job.
try:
client.post('/jobs/%d/cancel/' % pk)
changed = True
except exc.MethodNotAllowed:
changed = False
if fail_if_not_running:
raise exc.TowerCLIError('Job not running.')
# Return a success.
return adict({'status': 'canceled', 'changed': changed})
示例6: update
def update(self, pk=None, create_on_missing=False, monitor=False,
timeout=None, name=None, organization=None):
"""Trigger a project update job within Ansible Tower.
Only meaningful on non-manual projects.
"""
# First, get the appropriate project.
# This should be uniquely identified at this point, and if not, then
# we just want the error that `get` will throw to bubble up.
project = self.get(pk, name=name, organization=organization)
pk = project['id']
# Determine whether this project is able to be updated.
debug.log('Asking whether the project can be updated.',
header='details')
result = client.get('/projects/%d/update/' % pk)
if not result.json()['can_update']:
raise exc.CannotStartJob('Cannot update project.')
# Okay, this project can be updated, according to Tower.
# Commence the update.
debug.log('Updating the project.', header='details')
result = client.post('/projects/%d/update/' % pk)
# If we were told to monitor the project update's status, do so.
if monitor:
return self.monitor(pk, timeout=timeout)
# Return the project update ID.
return {
'changed': True,
}
示例7: launch
def launch(self, monitor=False, wait=False, timeout=None, **kwargs):
"""Launch a new ad-hoc command.
Runs a user-defined command from Ansible Tower, immediately starts it,
and returns back an ID in order for its status to be monitored.
=====API DOCS=====
Launch a new ad-hoc command.
:param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched command rather
than exiting with a success.
:type monitor: bool
:param wait: Flag that if set, monitor the status of the job, but do not print while job is in progress.
:type wait: bool
:param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number
of seconds.
:type timeout: int
:param `**kwargs`: Fields needed to create and launch an ad hoc command.
:returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``
call if ``wait`` flag is on; dictionary of "id" and "changed" if none of the two flags are on.
:rtype: dict
:raises tower_cli.exceptions.TowerCLIError: When ad hoc commands are not available in Tower backend.
=====API DOCS=====
"""
# This feature only exists for versions 2.2 and up
r = client.get('/')
if 'ad_hoc_commands' not in r.json():
raise exc.TowerCLIError('Your host is running an outdated version'
'of Ansible Tower that can not run '
'ad-hoc commands (2.2 or earlier)')
# Pop the None arguments because we have no .write() method in
# inheritance chain for this type of resource. This is needed
self._pop_none(kwargs)
# Actually start the command.
debug.log('Launching the ad-hoc command.', header='details')
result = client.post(self.endpoint, data=kwargs)
command = result.json()
command_id = command['id']
# If we were told to monitor the command once it started, then call
# monitor from here.
if monitor:
return self.monitor(command_id, timeout=timeout)
elif wait:
return self.wait(command_id, timeout=timeout)
# Return the command ID and other response data
answer = OrderedDict((
('changed', True),
('id', command_id),
))
answer.update(result.json())
return answer
示例8: update
def update(self, inventory_source, monitor=False, wait=False,
timeout=None, **kwargs):
"""Update the given inventory source.
=====API DOCS=====
Update the given inventory source.
:param inventory_source: Primary key or name of the inventory source to be updated.
:type inventory_source: str
:param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched inventory update
rather than exiting with a success.
:type monitor: bool
:param wait: Flag that if set, monitor the status of the inventory update, but do not print while it is
in progress.
:type wait: bool
:param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number
of seconds.
:type timeout: int
:param `**kwargs`: Fields used to override underlyingl inventory source fields when creating and launching
an inventory update.
:returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``
call if ``wait`` flag is on; dictionary of "status" if none of the two flags are on.
:rtype: dict
:raises tower_cli.exceptions.BadRequest: When the inventory source cannot be updated.
=====API DOCS=====
"""
# Establish that we are able to update this inventory source
# at all.
debug.log('Asking whether the inventory source can be updated.', header='details')
r = client.get('%s%d/update/' % (self.endpoint, inventory_source))
if not r.json()['can_update']:
raise exc.BadRequest('Tower says it cannot run an update against this inventory source.')
# Run the update.
debug.log('Updating the inventory source.', header='details')
r = client.post('%s%d/update/' % (self.endpoint, inventory_source), data={})
inventory_update_id = r.json()['inventory_update']
# If we were told to monitor the project update's status, do so.
if monitor or wait:
if monitor:
result = self.monitor(inventory_update_id, parent_pk=inventory_source, timeout=timeout)
elif wait:
result = self.wait(inventory_update_id, parent_pk=inventory_source, timeout=timeout)
inventory = client.get('/inventory_sources/%d/' % result['inventory_source']).json()['inventory']
result['inventory'] = int(inventory)
return result
# Done.
return {
'id': inventory_update_id,
'status': 'ok'
}
示例9: sync
def sync(self, inventory_source, **kwargs):
"""Update the given inventory source."""
# Establish that we are able to update this inventory source
# at all.
r = client.get('%s%d/update/' % (self.endpoint, inventory_source))
if not r.json()['can_update']:
raise exc.BadRequest('Tower says it cannot run an update against '
'this inventory source.')
# Run the update.
r = client.post('%s%d/update/' % (self.endpoint, inventory_source))
return {'status': 'ok'}
示例10: cancel
def cancel(self, pk=None, fail_if_not_running=False, **kwargs):
"""Cancel a currently running job.
Fails with a non-zero exit status if the job cannot be canceled.
You must provide either a pk or parameters in the job's identity.
"""
# Search for the record if pk not given
if not pk:
existing_data = self.get(**kwargs)
pk = existing_data['id']
cancel_endpoint = '%s%d/cancel/' % (self.endpoint, pk)
# Attempt to cancel the job.
try:
client.post(cancel_endpoint)
changed = True
except exc.MethodNotAllowed:
changed = False
if fail_if_not_running:
raise exc.TowerCLIError('Job not running.')
# Return a success.
return adict({'status': 'canceled', 'changed': changed})
示例11: test_request_post
def test_request_post(self):
"""Establish that on a POST request, we encode the provided data
to JSON automatically.
"""
with client.test_mode as t:
t.register_json('/ping/', {'status': 'ok'}, method='POST')
r = client.post('/ping/', {'payload': 'this is my payload.'})
# Establish that our request has the expected payload, and
# is sent using an application/json content type.
headers = r.request.headers
self.assertEqual(headers['Content-Type'], 'application/json')
self.assertEqual(r.request.body,
'{"payload": "this is my payload."}')
示例12: _disassoc
def _disassoc(self, url_fragment, me, other):
"""Disassociate the `other` record from the `me` record."""
# Get the endpoint for foreign records within this object.
url = self.endpoint + '%d/%s/' % (me, url_fragment)
# Attempt to determine whether the other record already is absent, for
# the "changed" moniker.
r = client.get(url, params={'id': other}).json()
if r['count'] == 0:
return {'changed': False}
# Send a request removing the foreign record from this one.
r = client.post(url, data={'disassociate': True, 'id': other})
return {'changed': True}
示例13: _assoc
def _assoc(self, url_fragment, me, other):
"""Associate the `other` record with the `me` record."""
# Get the endpoint for foreign records within this object.
url = self.endpoint + '%d/%s/' % (me, url_fragment)
# Attempt to determine whether the other record already exists here,
# for the "changed" moniker.
r = client.get(url, params={'id': other}).json()
if r['count'] > 0:
return {'changed': False}
# Send a request adding the other record to this one.
r = client.post(url, data={'associate': True, 'id': other})
return {'changed': True}
示例14: _get_or_create_child
def _get_or_create_child(self, parent, relationship, **kwargs):
ujt_pk = kwargs.get('unified_job_template', None)
if ujt_pk is None:
raise exceptions.BadRequest(
'A child node must be specified by one of the options '
'unified-job-template, job-template, project, or '
'inventory-source')
kwargs.update(self._parent_filter(parent, relationship, **kwargs))
response = self.read(
fail_on_no_results=False, fail_on_multiple_results=False, **kwargs)
if len(response['results']) == 0:
debug.log('Creating new workflow node.', header='details')
return client.post(self.endpoint, data=kwargs).json()
else:
return response['results'][0]
示例15: launch
def launch(self, workflow_job_template=None, monitor=False, wait=False,
timeout=None, extra_vars=None, **kwargs):
"""Launch a new workflow job based on a workflow job template.
Creates a new workflow job in Ansible Tower, starts it, and
returns back an ID in order for its status to be monitored.
=====API DOCS=====
Launch a new workflow job based on a workflow job template.
:param workflow_job_template: Primary key or name of the workflow job template to launch new job.
:type workflow_job_template: str
:param monitor: Flag that if set, immediately calls ``monitor`` on the newly launched workflow job rather
than exiting with a success.
:type monitor: bool
:param wait: Flag that if set, monitor the status of the workflow job, but do not print while job is
in progress.
:type wait: bool
:param timeout: If provided with ``monitor`` flag set, this attempt will time out after the given number
of seconds.
:type timeout: int
:param extra_vars: yaml formatted texts that contains extra variables to pass on.
:type extra_vars: array of strings
:param `**kwargs`: Fields needed to create and launch a workflow job.
:returns: Result of subsequent ``monitor`` call if ``monitor`` flag is on; Result of subsequent ``wait``
call if ``wait`` flag is on; loaded JSON output of the job launch if none of the two flags are on.
:rtype: dict
=====API DOCS=====
"""
if extra_vars is not None and len(extra_vars) > 0:
kwargs['extra_vars'] = parser.process_extra_vars(extra_vars)
debug.log('Launching the workflow job.', header='details')
self._pop_none(kwargs)
post_response = client.post('workflow_job_templates/{0}/launch/'.format(
workflow_job_template), data=kwargs).json()
workflow_job_id = post_response['id']
post_response['changed'] = True
if monitor:
return self.monitor(workflow_job_id, timeout=timeout)
elif wait:
return self.wait(workflow_job_id, timeout=timeout)
return post_response