blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
721
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 5
91
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 321
values | visit_date
timestamp[ns]date 2016-08-12 09:31:09
2023-09-06 10:45:07
| revision_date
timestamp[ns]date 2010-09-28 14:01:40
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 2010-09-28 14:01:40
2023-09-06 06:22:19
| github_id
int64 426
681M
| star_events_count
int64 101
243k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[ns]date 2012-06-28 18:51:49
2023-09-14 21:59:16
⌀ | gha_created_at
timestamp[ns]date 2008-02-11 22:55:26
2023-08-10 11:14:58
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 26
values | language
stringclasses 2
values | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 6
10.2M
| extension
stringclasses 115
values | filename
stringlengths 3
113
| content
stringlengths 6
10.2M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
38c75cfc45d548f77ad8feb7d242ef26154cd05b
|
3982e6daf88e453c726f6b39a081fc37ce15a08a
|
/discovery-provider/src/models/users/user_bank.py
|
84768fd85526d74e506bab7c1d31eebf203324ad
|
[
"Apache-2.0"
] |
permissive
|
AudiusProject/audius-protocol
|
45808e11082608ad5b76a425d287cb6d94a6dab0
|
7cf1d8e378520460d24a7cc8c29e9927c0944cb3
|
refs/heads/main
| 2023-08-09T10:34:28.850436
| 2023-08-09T04:28:17
| 2023-08-09T04:28:17
| 201,821,771
| 531
| 108
|
NOASSERTION
| 2023-09-14T21:27:52
| 2019-08-11T22:31:43
|
TypeScript
|
UTF-8
|
Python
| false
| false
| 1,007
|
py
|
user_bank.py
|
from sqlalchemy import Column, DateTime, Integer, String
from src.models.base import Base
from src.models.model_utils import RepresentableMixin
class UserBankTx(Base, RepresentableMixin):
__tablename__ = "user_bank_txs"
signature = Column(String, primary_key=True)
slot = Column(Integer, nullable=False, index=True)
created_at = Column(DateTime, nullable=False)
class UserBankAccount(Base, RepresentableMixin):
__tablename__ = "user_bank_accounts"
signature = Column(String, primary_key=True)
ethereum_address = Column(String, nullable=False, index=True)
created_at = Column(DateTime, nullable=False)
bank_account = Column(String, nullable=False)
class USDCUserBankAccount(Base, RepresentableMixin):
__tablename__ = "usdc_user_bank_accounts"
signature = Column(String, primary_key=True)
ethereum_address = Column(String, nullable=False, index=True)
created_at = Column(DateTime, nullable=False)
bank_account = Column(String, nullable=False)
|
475de514323b7862dcc88043b6017fcf252971b1
|
5dfa8f66e7d200117fec49a0b273bf97f1babd3d
|
/pyradio/config_window.py
|
7d8b040132d31d0089f25f42626047844957725d
|
[
"MIT"
] |
permissive
|
coderholic/pyradio
|
08db8fb7fd105d0f137006d601fd8355e2101bbd
|
67e81c5dade03b20d65ebcca0c019f4d1493d7dc
|
refs/heads/master
| 2023-08-18T08:02:07.589209
| 2023-07-15T11:37:07
| 2023-07-15T11:37:07
| 55,984
| 828
| 135
|
MIT
| 2023-05-18T15:52:00
| 2008-09-24T11:51:13
|
Python
|
UTF-8
|
Python
| false
| false
| 116,415
|
py
|
config_window.py
|
# -*- coding: utf-8 -*-
import curses
from copy import deepcopy
from textwrap import wrap
import glob
import csv
from os import path, sep, remove
from sys import platform, version_info
from .common import *
from .window_stack import Window_Stack_Constants
from .cjkwrap import cjklen
from .config import SUPPORTED_PLAYERS
from .encodings import *
from .themes import *
from .simple_curses_widgets import SimpleCursesLineEdit, SimpleCursesHorizontalPushButtons
import logging
import locale
locale.setlocale(locale.LC_ALL, '') # set your locale
logger = logging.getLogger(__name__)
def set_global_functions(global_functions):
ret = {}
if global_functions is not None:
ret = dict(global_functions)
if ord('t') in ret.keys():
del ret[ord('t')]
return ret
class PyRadioConfigWindow(object):
n_u = Window_Stack_Constants
parent = None
_win = None
_title = 'PyRadio Configuration'
selection = __selection = 1
''' Keep a copy of saved values for theme and transparency
Work-around for 'T' auto save (trasnsparency), and
's'/Space them saving
'''
_old_use_transparency = False
_old_theme = ''
_headers = []
_num_of_help_lines = 0
_help_text = []
_help_text.append(None)
_help_text.append(['Specify the player to use with PyRadio, or the player detection order.', '|',
'This is the eqivelant to the -u , --use-player command line option.', '|',
'Example:', ' player = vlc', 'or', ' player = vlc,mpv, mplayer', '|',
'Default value: mpv,mplayer,vlc'])
_help_text.append(['If this option is enabled, the last local playlist loaded before terminating, will be automatically opened the next time PyRadio is executed. Furthermore, playback will resume, if it was on when PyRadio exited. Otherwise, station selection will be restored.', '|', 'This option will take precedence over the "Def. playlist" configuration option and the "-s" command line option.', '|', 'It can also be toggled on the fly by perssing \\l while on Main mode.', '|', 'Default value: False'])
_help_text.append(['This is the playlist to open at start up, if none is specified and "Open last playlist" is not set.', '|',
'This is the equivalent to the -s, --stations command line option.', '|',
'Default value: stations'])
_help_text.append(['The station number within the default playlist to play.', '|',
'This is the equivalent to the -p, --play command line option.', '|',
'Value is 1..number of stations, "False" means no auto play, "Random" means play a random station.', '|', 'Default value: False'])
_help_text.append(['This is the encoding used by default when reading data provided by a station such as song title, etc. If reading said data ends up in an error, "utf-8" will be used instead.', '|',
'If changed, playback must be restarted so that changes take effect.',
'|', 'Default value: utf-8'])
_help_text.append(['If this options is enabled, the mouse can be used to scroll the playlist, start, stop and mute the player, adjust its volume etc.', '|', 'Mouse support is highly terminal dependent, that\'s why it is disabled by default.', '|', 'Default value: False'])
_help_text.append(['If this options is enabled, a Desktop Notification will be displayed using the notification daemon / service.', '|', 'If enabled but no notification is displayed, please refer to', 'https://github.com/coderholic/pyradio/desktop-notification.md', '|', 'Valid values are:', ' -1: disabled ', ' 0: enabled (no repetition) ', ' x: repeat every x seconds ', '|', 'Default value: -1'])
_help_text.append(['Notice: Not applicable on Windows!', '|', 'Online Radio Directory Services (like Radio Browser) will usually provide an icon for the stations they advertise.', '|', 'PyRadio can use this icon (provided that one exists and is of JPG or PNG format) while displaying Desktop Notifications.', '|', 'Setting this option to True, will enable the behavior above.', '|', 'If this option is False, the default icon will be used.', '|', 'Default value: True'])
_help_text.append(None)
_help_text.append(['PyRadio will wait for this number of seconds to get a station/server message indicating that playback has actually started.', '|',
'If this does not happen within this number of seconds after the connection is initiated, PyRadio will consider the station unreachable, and display the "Failed to connect to: station" message.', '|', 'Press "h"/Left or "l"/Right to change value.',
'|', 'Valid values: 5 - 60, 0 disables check', 'Default value: 10'])
_help_text.append(['Most radio stations use plain old http protocol to broadcast, but some of them use https.', '|', 'If this parameter is enabled, all connections will use http; results depend on the combination of station/player.', '|', 'This value is read at program startup, use "z" to change its effect while mid-session.',
'|', 'Default value: False'])
_help_text.append(None)
_help_text.append(['The theme to be used by default.', '|',
'This is the equivalent to the -t , --theme command line option.', '|',
'If a theme uses more colors than those supported by the terminal in use, the "dark" theme will be used instead (but the "light" theme will be used, if the "light_16colors" theme was requested but not supported).',
'|', 'Default value = dark'])
_help_text.append(['This option will work when a theme\'s transparency value is set to 2 (Obey config setting), the default. Otherwise, it\'s up to the theme to handle transparency.', '|', 'If False, theme colors will be used.', '|',
"If True and a compositor is running, the stations' window background will be transparent.", '|', "If True and a compositor is not running, the terminal's background color will be used.", '|', 'Default value: False'])
_help_text.append(['Pyradio can calculate and use an alternative color for secondary windows.', '|', 'This option will determine if this color will be used (value > 0) or not (value = 0), provided that the theme used does not already provide it.', '|', 'The value of this option is actually the factor to darken or lighten the main (stations) background color.', '|', 'You can get more info on this at https://github.com/coderholic/pyradio#secondary-windows-background', '|', 'Valid Values: 0-0.2', 'Default value: 0'])
_help_text.append(None)
_help_text.append(['Specify whether you will be asked to confirm every station deletion action.',
'|', 'Default value: True'])
_help_text.append(['Specify whether you will be asked to confirm playlist reloading, when the playlist has not been modified within PyRadio.',
'|', 'Default value: True'])
_help_text.append(['Specify whether you will be asked to save a modified playlist whenever it needs saving.', '|', 'Default value: False'])
_help_text.append(None)
_help_text.append(['This is the IP for the Remote Control Server.', '|', 'Available options:', '- localhost', ' PyRadio will be accessible from within the current system only.', '- LAN', ' PyRadio will be accessible from any computer in the local network.', '|', 'One can see the active IP using the "\s" command from the program\'s Main Window.', '|', 'Use "Space", "Enter", "l/Right" to change the value.','|', 'Default value: localhost'])
_help_text.append(
['This is the port used by the Remote Control Server (the port the server is listening to).', '|', 'Please make sure that a "free" port is specified here, to avoid any conflicts with existing services and daemons.', '|', 'If an invalid port number is inserted, the cursor will not move to another field.', '|', 'Valid values: 1025-65535', 'Default value: 9998'])
_help_text.append(['If set to True, the Server wiil be automatically started when PyRadio starts.', 'If set to False, one can start the Server using the "\s" command from the Main program window.', '|', 'Default value: False'])
_help_text.append(None)
_help_text.append(['This options will open the configuration window for the RadioBrowser Online Stations Directory.', '|', "In order to use RadioBrowser, python's requests module must be installed."])
_config_options = None
def __init__(self, parent, config,
toggle_transparency_function,
show_theme_selector_function,
save_parameters_function,
reset_parameters_function,
show_port_number_invalid,
global_functions=None
):
self._local_functions = {
ord('j'): self._go_down,
curses.KEY_DOWN: self._go_down,
ord('k'): self._go_up,
curses.KEY_UP: self._go_up,
curses.KEY_PPAGE: self._go_pgup,
curses.KEY_NPAGE: self._go_pgdown,
ord('g'): self._go_home,
curses.KEY_HOME: self._go_home,
ord('G'): self._go_end,
curses.KEY_END: self._go_end,
ord('d'): self._go_default,
ord('r'): self._go_saved,
curses.KEY_EXIT: self._go_exit,
27: self._go_exit,
ord('q'): self._go_exit,
ord('h'): self._go_exit,
curses.KEY_LEFT: self._go_exit,
ord('s'): self._go_save,
}
self._global_functions = set_global_functions(global_functions)
self._port_line_editor = SimpleCursesLineEdit(
parent=self._win,
width=6,
begin_y=6,
begin_x=16,
boxed=False,
has_history=False,
caption='',
box_color=curses.color_pair(6),
edit_color=curses.color_pair(6),
cursor_color=curses.color_pair(8),
unfocused_color=curses.color_pair(4),
key_up_function_handler=self._go_up,
key_down_function_handler=self._go_down,
key_pgup_function_handler=self._go_pgup,
key_pgdown_function_handler=self._go_pgdown,
)
self._port_line_editor.visible = False
self._port_line_editor.bracket = False
self._port_line_editor._use_paste_mode = False
self._port_line_editor.set_global_functions(self._global_functions)
self._port_line_editor._paste_mode = False
self._port_line_editor.chars_to_accept = [ str(x) for x in range(0, 10)]
self._port_line_editor.set_local_functions(self._fix_local_functions_for_editor())
self._start = 0
self.parent = parent
self._cnf = config
self._show_port_number_invalid = show_port_number_invalid
self._toggle_transparency_function = toggle_transparency_function
self._show_theme_selector_function = show_theme_selector_function
self._save_parameters_function = save_parameters_function
self._reset_parameters_function = reset_parameters_function
self._saved_config_options = deepcopy(config.opts)
self._config_options = deepcopy(config.opts)
self._old_theme = self._config_options['theme'][1]
if logger.isEnabledFor(logging.INFO):
if self._saved_config_options == self._config_options:
logger.info('Saved options loaded')
else:
logger.info('Altered options loaded')
self.number_of_items = len(self._config_options) - 3
for i, n in enumerate(list(self._config_options.values())):
if n[1] == '':
self._headers.append(i)
# logger.error('{}'.format(self._config_options))
# logger.error('self._headers = {}'.format(self._headers))
self._port_line_editor.string = self._config_options['remote_control_server_port'][1]
self.init_config_win()
self.refresh_config_win()
self._old_use_transparency = self._config_options['use_transparency'][1]
self._cnf.get_player_params_from_backup()
''' Config window parameters check '''
# logger.error('DE \n\ncheck params\n{0}\n{1}'.format(self._cnf.saved_params, self._cnf.params))
for a_key in self._cnf.saved_params.keys():
if self._cnf.saved_params[a_key] != self._cnf.params[a_key]:
self._cnf.dirty_config = True
def __del__(self):
self._toggle_transparency_function = None
def _fix_local_functions_for_editor(self):
chk = (
curses.KEY_HOME,
curses.KEY_END,
curses.KEY_LEFT,
curses.KEY_RIGHT,
)
local_f = {}
for n in self._local_functions.keys():
local_f[n] = self._local_functions[n]
for n in chk:
if n in local_f.keys():
local_f.pop(n)
return local_f
@property
def parent(self):
return self.__parent
@parent.setter
def parent(self, val):
self.__parent = val
self.init_config_win()
@property
def selection(self):
return self.__selection
@selection.setter
def selection(self, val):
if val < 1:
val = len(self._headers) - 1
elif val >= self.number_of_items:
val = 1
if val in self._headers:
self.__selection = val + 1
else:
self.__selection = val
#self.refresh_config_win()
def init_config_win(self):
self._win = None
self.maxY, self.maxX = self.__parent.getmaxyx()
# logger.error('\n\nmaxY = {}\n\n'.format(self.maxY))
self._second_column = int(self.maxX / 2)
self._win = curses.newwin(self.maxY, self.maxX, 1, 0)
self._populate_help_lines()
if self._config_options:
self._max_start = len(self._config_options) - 1 - self.maxY
# logger.error('max_start = {}'.format(self._max_start))
if self._max_start < 0:
self._start = 0
else:
self._put_cursor(0)
def refresh_config_win(self):
self._win.bkgdset(' ', curses.color_pair(12))
self._win.erase()
self._win.box()
self._print_title()
#self._win.addstr(0,
# int((self.maxX - len(self._title)) / 2),
# self._title,
# curses.color_pair(4))
min_lines = len(self._config_options)
if min_lines < self._max_number_of_help_lines:
min_lines = self._max_number_of_help_lines
# if self.maxX < 80 or self.maxY < min_lines + 3:
if self.maxX < 80 or self.maxY < 22:
self.too_small = True
else:
self.too_small = False
if self.too_small:
self._port_line_editor.visible = False
# self._port_line_editor.visible = False
msg = 'Window too small to display content!'
if self.maxX < len(msg) + 2:
msg = 'Window too small!'
try:
self._win.addstr(
int(self.maxY / 2),
int((self.maxX - len(msg)) / 2),
msg, curses.color_pair(5))
except:
pass
else:
self._win.addstr(1, self._second_column, 'Option Help', curses.color_pair(4))
''' print distro name '''
''' TODO: make sure it does not overwrite an option name '''
self.refresh_selection()
def _print_title(self):
if self._config_options == self._saved_config_options and \
self._old_theme == self._saved_config_options['theme'][1] and \
self._old_use_transparency == self._saved_config_options['use_transparency'][1] and not self._cnf.params_changed:
dirty_title = '─ '
self._cnf.dirty_config = False
col = 12
else:
dirty_title = ' *'
# logger.error('config_options = {}'.format(self._config_options))
# logger.error('saved_config_options = {}'.format(self._saved_config_options))
# logger.error('old_theme = "{0}", theme = "{1}"'.format(self._old_theme, self._saved_config_options['theme'][1]))
# logger.error('old transparency = {0}, transparency = {1}'.format(self._old_use_transparency, self._saved_config_options['use_transparency'][1]))
# logger.error('params_changed = {}'.format(self._cnf.params_changed))
# logger.error('>>>')
self._cnf.dirty_config = True
col = 12
X = int((self.maxX - len(self._title) - 1) / 2)
try:
self._win.addstr(0, X, dirty_title, curses.color_pair(col))
except:
self._win.addstr(0, X, dirty_title.encode('utf-8'), curses.color_pair(col))
self._win.addstr(self._title + ' ', curses.color_pair(4))
if self._cnf.distro != 'None':
try:
X = int((self.maxX - 20 - len(self._cnf.distro) - 1) / 2)
self._win.addstr(self.maxY - 1, X, ' Package provided by ', curses.color_pair(5))
# self._win.addstr(min_lines + 2, 3 + int(abs(8 - len(self._cnf.distro)) / 2), self._cnf.distro, curses.color_pair(4))
self._win.addstr(self._cnf.distro + ' ', curses.color_pair(4))
except:
pass
def refresh_selection(self):
self._print_title()
if not self.too_small:
# logger.error('\n\n================\nself._start = {}'.format(self._start))
# logger.error(self._config_options)
it_list = list(self._config_options.values())
for i in range(len(it_list)-1, 0, -1):
if it_list[i][0] == '':
it_list.pop()
# logger.error(it_list)
# if self.__selection < self.maxY -2:
# self._start = 0
# else:
# self._start += 1
# logger.error('self._start = {}'.format(self._start))
# for i in range(self._start, len(it_list)):
self._port_line_editor.visible = False
for i in range(self._start, self._start + self.maxY - 2):
try:
it = it_list[i]
except IndexError:
break
# logger.error('selection = {0}, i = {1}, max = {2}'.format(self.selection, i, self.maxY))
if i == self.__selection:
col = hcol = curses.color_pair(6)
self._print_options_help()
else:
col = curses.color_pair(5)
hcol = curses.color_pair(4)
hline_width = self._second_column - 2
try:
self._win.hline(i+1-self._start, 1, ' ', hline_width, col)
except:
logger.error('===== ERROR: {}'.format(i+1))
if it[0] == 'Server Port: ':
logger.error('\n\ni = {0}, y = {1}, it[0] = "{2}"'.format(i, i+1-self._start, it[0]))
if i in self._headers:
self._win.addstr(i+1-self._start, 1, it[0], curses.color_pair(4))
else:
on_editor = i+1-self._start if it[0] == 'Server Port: ' else -1
self._win.addstr(i+1-self._start, 1, ' ' + it[0], col)
if on_editor > -1:
''' move port editor to line '''
self._port_line_editor.visible = True
self._port_line_editor.move(self._win, on_editor + 1, 16, update=False)
logger.error('{0}: moving to: {1},{2}'.format(on_editor+1, on_editor, 16))
if i == self.__selection:
self._port_line_editor.focused = True
logger.error('line editor focused = True')
else:
self._port_line_editor.focused = False
logger.error('line editor focused = False')
logger.error('line editor string = "{}"'.format(self._port_line_editor.string))
elif isinstance(it[1], bool):
self._win.addstr('{}'.format(it[1]), hcol)
else:
if it[1] is None:
''' random station '''
self._win.addstr('{}'.format('Random'), hcol)
else:
if it[1] != '-':
self._win.addstr('{}'.format(it[1][:self._second_column - len(it[0]) - 6]), hcol)
self._win.refresh()
if self._port_line_editor.visible:
self._port_line_editor.keep_restore_data()
self._port_line_editor.show(self._win)
def _get_col_line(self, ind):
if ind < self._headers:
self._column = 3
self._line = ind + 2
else:
self._column = self._second_column + 2
self._line = ind - self._headers + 2
def _put_cursor(self, jump):
if self.__selection == self.number_of_items - 1 and jump > 0:
self.__selection = 1
self._start = 0
return
visible_items = self.maxY - 3
last_item = self._start + visible_items
old_selection = self.__selection
old_start = self._start
self.__selection += jump
if jump >= 0:
if self.__selection in self._headers:
self.__selection += 1
if self.__selection >= self.number_of_items:
self.__selection = self.number_of_items -1
if self.number_of_items > visible_items:
self._start = self.number_of_items - visible_items - 1
else:
if self.__selection <= 1:
self._start = 0
elif self.__selection > last_item:
self._start += 1
if self._start + visible_items in self._headers:
self._start += 1
if self.__selection - self._start > visible_items:
self._start = self.__selection - self._start - visible_items + 1
else:
if self.__selection in self._headers:
self.__selection -= 1
if self.__selection < 1:
self.__selection = self.number_of_items - 1
if self.number_of_items > visible_items:
self._start = self.__selection - visible_items
else:
if self.__selection < self._start:
self._start = self.__selection
def _populate_help_lines(self):
self._help_lines = []
self._max_number_of_help_lines = 0
for z in self._help_text:
if z is None:
self._help_lines.append(None)
else:
all_lines = []
for k in z:
lines = []
lines = wrap(k, self.maxX - self._second_column - 2)
all_lines.extend(lines)
self._help_lines.append(all_lines)
if len(all_lines) > self._max_number_of_help_lines:
self._max_number_of_help_lines = len(all_lines)
def _print_options_help(self):
for i, x in enumerate(self._help_lines[self.selection]):
if i + 2 == self.maxY:
break
self._win.addstr(i+2, self._second_column, ' ' * (self._second_column - 1), curses.color_pair(5))
self._win.addstr(i+2, self._second_column, x.replace('|',''), curses.color_pair(5))
if len(self._help_lines[self.selection]) < self._num_of_help_lines:
for i in range(len(self._help_lines[self.selection]), self._num_of_help_lines):
try:
self._win.addstr(i+2, self._second_column, ' ' * (self._second_column - 1), curses.color_pair(5))
except:
pass
self._num_of_help_lines = len(self._help_lines[self.selection])
'''
Uncomment if trouble with help lines
'''
#if logger.isEnabledFor(logging.DEBUG):
# logger.debug('self._num_of_help_lines = {}'.format(self._num_of_help_lines))
def _load_default_values(self):
self._config_options['general_title'][1] = ''
self._config_options['player'][1] = 'mpv,mplayer,vlc'
self._config_options['open_last_playlist'][1] = 'False'
self._config_options['default_playlist'][1] = 'stations'
self._config_options['default_station'][1] = 'False'
self._config_options['default_encoding'][1] = 'utf-8'
self._config_options['enable_mouse'][1] = 'False'
self._config_options['enable_notifications'][1] = '-1'
self._config_options['use_station_icon'][1] = 'True'
self._config_options['connection_timeout'][1] = '10'
self._config_options['theme_title'][1] = ''
''' Transparency '''
#self._old_use_transparency = self._config_options['use_transparency'][1]
self._config_options['use_transparency'][1] = False
self._config_options['calculated_color_factor'][1] = '0'
self._config_options['force_http'][1] = False
self._toggle_transparency_function(changed_from_config_window=True, force_value=False)
self._config_options['playlist_manngement_title'][1] = ''
self._config_options['confirm_station_deletion'][1] = True
self._config_options['confirm_playlist_reload'][1] = True
self._config_options['auto_save_playlist'][1] = False
self._config_options['requested_player'][1] = ''
self._config_options['remote_control_server_ip'][1] = 'localhost'
self._config_options['remote_control_server_port'][1] = '9998'
self._port_line_editor.string = '9998'
self._config_options['remote_control_server_auto_start'][1] = False
''' Theme
Put this AFTER applying transparency, so that _do_init_pairs in
_toggle_transparency does not overwrite pairs with applied theme values
'''
self._config_options['theme'][1] = 'dark'
self._apply_a_theme('dark', False)
self._check_if_config_is_dirty()
def _check_if_config_is_dirty(self):
if self._config_options == self._saved_config_options:
self._config_options['dirty_config'] = ['', False]
else:
self._config_options['dirty_config'] = ['', True]
def _apply_a_theme(self, a_theme, use_transparency=None):
theme = PyRadioTheme(self._cnf)
theme.readAndApplyTheme(a_theme, use_transparency=use_transparency)
self._cnf.use_calculated_colors = False if self._cnf.opts['calculated_color_factor'][1] == '0' else True
self._cnf.update_calculated_colors()
theme = None
curses.doupdate()
def _is_port_invalid(self):
if 1025 <= int(self._port_line_editor.string) <= 65535:
self._config_options['remote_control_server_port'][1] = self._port_line_editor.string
return False
self._show_port_number_invalid()
return True
def _go_up(self):
if self._is_port_invalid():
return
self._put_cursor(-1)
self.refresh_selection()
def _go_down(self):
if self._is_port_invalid():
return
self._put_cursor(1)
self.refresh_selection()
def _go_pgup(self):
if self._is_port_invalid():
return
self._put_cursor(-5)
self.refresh_selection()
def _go_pgdown(self):
if self._is_port_invalid():
return
self._put_cursor(5)
self.refresh_selection()
def _go_home(self):
if self._is_port_invalid():
return
self._start = 0
self.__selection = 1
self.refresh_selection()
def _go_end(self):
if self._is_port_invalid():
return
self.__selection = self.number_of_items - 1
self._start = self.__selection - self.maxY + 2
self._put_cursor(0)
self.refresh_selection()
def _go_default(self):
self._load_default_values()
self.refresh_selection()
if logger.isEnabledFor(logging.INFO):
logger.info('Default options loaded')
def _go_saved(self):
if self._cnf.use_themes:
old_theme = self._config_options['theme'][1]
old_transparency = self._config_options['use_transparency'][1]
self._config_options = deepcopy(self._saved_config_options)
self._port_line_editor.string = self._config_options['remote_control_server_port'][1]
''' Transparency '''
self._config_options['use_transparency'][1] = self._old_use_transparency
self._toggle_transparency_function(
changed_from_config_window=True,
force_value=self._old_use_transparency)
''' Theme
Put it after applying transparency, so that saved color_pairs
do not get loaded instead of active ones
'''
self._config_options['theme'][1] = self._old_theme
self._saved_config_options['theme'][1] = self._old_theme
self._apply_a_theme(self._config_options['theme'][1], self._old_use_transparency)
self._reset_parameters_function()
self.refresh_selection()
if logger.isEnabledFor(logging.INFO):
logger.info('Saved options loaded')
def _go_exit(self):
self._win.nodelay(True)
char = self._win.getch()
self._win.nodelay(False)
if char == -1:
''' ESCAPE '''
logger.error('dirty config is {}, and ESC pressed'.format(self._cnf.dirty_config))
self._saved_config_options['theme'][1] = self._old_theme
self._cnf.opts['theme'][1] = self._old_theme
self._cnf.theme = self._old_theme
def _go_save(self):
if self._is_port_invalid():
return
''' save and exit '''
self._old_theme = self._config_options['theme'][1]
if self._saved_config_options['enable_mouse'][1] == self._config_options['enable_mouse'][1]:
self.mouse_support_option_changed = False
else:
self.mouse_support_option_changed = True
if self._saved_config_options['calculated_color_factor'][1] == self._config_options['calculated_color_factor'][1]:
self.need_to_update_theme = False
else:
self.need_to_update_theme = True
self._saved_config_options = deepcopy(self._config_options)
if self._cnf.opts != self._saved_config_options:
''' check if player has changed '''
if self._cnf.opts['player'][1] != self._saved_config_options['player'][1]:
self._cnf.player_changed = True
self._cnf.player_values = [self._cnf.opts['player'][1], self._saved_config_options['player'][1]]
self._cnf.opts = deepcopy(self._saved_config_options)
self._old_theme == self._saved_config_options['theme'][1]
self._config_options = deepcopy(self._cnf.opts)
self._cnf.dirty_config = True
else:
self._cnf.dirty_config = False
self._save_parameters_function()
return True
def keypress(self, char):
''' Config Window key press
Returns:
-1 continue
0 save config
1 cancel saving config
2 cancel a dirty config (not active currently)
3 open online browser config
'''
if self.too_small:
return 1, []
# logger.error('max = {0}, len = {1}'.format(self.maxY, len(self._config_options)))
self._max_start = len(self._config_options) -1 - self.maxY
# logger.error('mas_start = {}'.format(self._max_start))
val = list(self._config_options.items())[self.selection]
logger.error('val = {}'.format(val))
Y = self.selection - self._start + 1
if char in self._local_functions.keys():
if not (val[0] in (
'remote_control_server_port',
'enable_notifications',
'connection_timeout',
'calculated_color_factor',
) and char in (
curses.KEY_LEFT,
curses.KEY_RIGHT,
ord('h'), ord('l'),
)):
ret = self._local_functions[char]()
if self._local_functions[char] == self._go_exit:
return 1, []
elif self._local_functions[char] == self._go_save and ret:
return 0, []
return -1, []
if char in self._global_functions.keys():
self._global_functions[char]()
elif val[0] == 'radiobrowser':
if char in (curses.KEY_RIGHT, ord('l'),
ord(' '), curses.KEY_ENTER, ord('\n')):
return 3, []
elif val[0] == 'remote_control_server_port':
ret = self._port_line_editor.keypress(self._win, char)
if ret == 1:
return -1, []
elif val[0] == 'enable_notifications':
if char in (curses.KEY_RIGHT, ord('l')):
t = int(val[1][1])
if t == -1:
t = 0
elif t == 0:
t = 30
else:
t += 30
if t > 300:
t =300
val[1][1] = str(t)
self._win.addstr(
Y, 3 + len(val[1][0]),
val[1][1] + ' ', curses.color_pair(6))
self._print_title()
self._win.refresh()
return -1, []
elif char in (curses.KEY_LEFT, ord('h')):
t = int(val[1][1])
if t == -1:
t = -1
elif t == 0:
t = -1
else:
t -= 30
val[1][1] = str(t)
self._win.addstr(
Y, 3 + len(val[1][0]),
val[1][1] + ' ', curses.color_pair(6))
self._print_title()
self._win.refresh()
return -1, []
elif val[0] == 'calculated_color_factor':
if char in (curses.KEY_RIGHT, ord('l')):
if self._cnf.use_themes:
t = float(val[1][1])
if t < .2:
t = round(t + .01, 2)
logger.error('t = {}'.format(t))
s_t = str(t)[:4]
if s_t == '0.0':
s_t = '0'
logger.error('s_t = ' + s_t)
self._config_options[val[0]][1] = s_t
self._win.addstr(
Y, 3 + len(val[1][0]),
s_t + ' ', curses.color_pair(6))
self._print_title()
self._win.refresh()
# att = PyRadioThemeReadWrite(self._cnf)
# att._calculate_fifteenth_color()
else:
self._cnf._show_colors_cannot_change()
return -1, []
elif char in (curses.KEY_LEFT, ord('h')):
if self._cnf.use_themes:
t = float(val[1][1])
if t > 0:
t = round(t - .01, 2)
logger.error('t = {}'.format(t))
s_t = str(t)[:4]
if s_t == '0.0':
s_t = '0'
logger.error('s_t = ' + s_t)
self._config_options[val[0]][1] = s_t
self._win.addstr(
Y, 3 + len(val[1][0]),
s_t + ' ', curses.color_pair(6))
self._print_title()
self._win.refresh()
# att = PyRadioThemeReadWrite(self._cnf)
# att._calculate_fifteenth_color()
else:
self._cnf._show_colors_cannot_change()
return -1, []
elif val[0] == 'remote_control_server_ip':
if char in (curses.KEY_RIGHT, ord('l'), ord(' '), ord('\n'), curses.KEY_ENTER):
if self._config_options[val[0]][1] == 'localhost':
self._config_options[val[0]][1] = 'LAN'
disp = 'LAN '
else:
self._config_options[val[0]][1] = 'localhost'
disp = 'localhost'
self._win.addstr(
Y, 3 + len(val[1][0]),
disp, curses.color_pair(6)
)
self._print_title()
self._win.refresh()
return -1, []
elif char in (curses.KEY_LEFT, ord('h')):
if self._config_options[val[0]][1] == 'localhost':
self._config_options[val[0]][1] = 'LAN'
disp = 'LAN '
else:
self._config_options[val[0]][1] = 'localhost'
disp = 'localhost'
self._win.addstr(
Y, 3 + len(val[1][0]),
disp, curses.color_pair(6)
)
self._print_title()
self._win.refresh()
return -1, []
elif val[0] == 'connection_timeout':
if char in (curses.KEY_RIGHT, ord('l')):
t = int(val[1][1])
if t == 0:
t = 4
if t < 60:
t += 1
self._config_options[val[0]][1] = str(t)
self._win.addstr(
Y, 3 + len(val[1][0]),
str(t) + ' ', curses.color_pair(6))
self._print_title()
self._win.refresh()
return -1, []
elif char in (curses.KEY_LEFT, ord('h')):
t = int(val[1][1])
if t > 5:
t -= 1
else:
t = 0
self._config_options[val[0]][1] = str(t)
self._win.addstr(
Y, 3 + len(val[1][0]),
str(t) + ' ', curses.color_pair(6))
self._print_title()
self._win.refresh()
return -1, []
if char in (
curses.KEY_ENTER, ord('\n'),
ord('\r'), ord(' '), ord('l'), curses.KEY_RIGHT):
''' alter option value '''
vals = list(self._config_options.items())
sel = vals[self.selection][0]
if sel == 'player':
return self.n_u.SELECT_PLAYER_MODE, []
elif sel == 'default_encoding':
return self.n_u.SELECT_ENCODING_MODE, []
elif sel == 'theme':
if self._cnf.use_themes:
self._cnf.theme = self._old_theme
if logger.isEnabledFor(logging.ERROR):
logger.error('DE\n\nshowing theme self._cnf.theme = {}\n\n'.format(self._cnf.theme))
self._show_theme_selector_function()
elif sel == 'default_playlist':
return self.n_u.SELECT_PLAYLIST_MODE, []
elif sel == 'default_station':
return self.n_u.SELECT_STATION_MODE, []
elif sel == 'confirm_station_deletion' or \
sel == 'open_last_playlist' or \
sel == 'confirm_playlist_reload' or \
sel == 'enable_mouse' or \
sel == 'auto_save_playlist' or \
sel == 'force_http' or \
sel == 'remote_control_server_auto_start' or \
sel == 'use_station_icon':
self._config_options[sel][1] = not self._config_options[sel][1]
# # if sel == 'open_last_playlist':
# # if self._config_options[sel][1]:
# # ''' became True, save last playlist '''
# # self._cnf.save_last_playlist()
self.refresh_selection()
elif sel == 'use_transparency':
#self._old_use_transparency = not self._config_options[ 'use_transparency' ][1]
self._toggle_transparency_function(
changed_from_config_window=True,
force_value=not self._config_options['use_transparency'][1]
)
self.refresh_selection()
return -1, []
class PyRadioExtraParams(object):
''' Class to display extra player parameters on
main window. No editing allowed!
'''
def __init__(self,
config,
parent,
global_functions=None):
''' setting editing to 0 so that help functions work '''
self.editing = 0
self._max_lines = 16
self._note_text = ' Note '
self._note_line1 = 'Changes made here wil not be'
self._note_line2 = 'saved in the configuration file'
self._extra = None
self._cnf = config
self._parent = parent
self._win = None
self._title = ' Player Extra Parameters '
self._too_small_str = 'Window too small'
self._cnf.get_player_params_from_backup(param_type=1)
self._global_functions = global_functions
self._redisplay()
@property
def params(self):
return self._extra._working_params
@params.setter
def params(self, val):
raise ValueError('property is read only')
def set_parrent(self, window):
self._parent = window
self._redisplay()
def _redisplay(self):
pY, pX = self._parent.getmaxyx()
logger.error('pY = {0}, pX = {1}'.format(pY, pX))
if pY < self._max_lines + 2 or pX < 30:
self._too_small = True
self._win = curses.newwin(
3, len(self._too_small_str) + 4,
int((pY - 3) / 2) + 2,
int((pX - len(self._too_small_str)) / 2)
)
self.show()
else:
self._too_small = False
self.maxX = pX - 2 if pX < 40 else 40
logger.error('maxX = {}'.format(self.maxX))
logger.error('max_lines = {}'.format(self._max_lines))
self._win = curses.newwin(
self._max_lines, self.maxX,
int((pY - self._max_lines) / 2) + 2,
int((pX - self.maxX) / 2)
)
if self._extra:
self._extra.set_window(self._win)
self.show()
else:
self._extra = ExtraParameters(
self._cnf,
self._cnf.PLAYER_NAME,
self._win,
lambda: True,
from_config=False,
global_functions=self._global_functions
)
def show(self):
self._win.bkgdset(' ', curses.color_pair(3))
self._win.erase()
self._win.box()
if self._too_small:
self._win.addstr(1, 1, self._too_small_str,
curses.color_pair(10))
self._win.refresh()
else:
self._win.addstr(
0, int((self.maxX - len(self._title)) / 2),
self._title,
curses.color_pair(11))
''' show note '''
try:
self._win.addstr(12, 2, '─' * (self.maxX - 4), curses.color_pair(3))
except:
self._win.addstr(12, 2, '─'.encode('utf-8') * (self.maxX - 6), curses.color_pair(3))
self._win.addstr(12, int((self.maxX - len(self._note_text))/2), self._note_text, curses.color_pair(3))
self._win.addstr(13, int((self.maxX - len(self._note_line1)) / 2), self._note_line1, curses.color_pair(10))
self._win.addstr(14, int((self.maxX - len(self._note_line2)) / 2), self._note_line2, curses.color_pair(10))
self._extra.refresh_win()
def keypress(self, char):
return self._extra.keypress(char)
class ExtraParametersEditor(object):
''' Class to edit or add parameters
'''
def __init__(self,
parent,
config,
string='',
global_functions=None):
self._parent = parent
self._cnf = config
self.edit_string = string
self._caption = ' Parameter value '
self._string = self._orig_string = string
self._global_functions = set_global_functions(global_functions)
self.Y, self.X = self._parent.getbegyx()
self.Y += 1
self.X += 1
self.maxY, self.maxX = self._parent.getmaxyx()
self.maxY -= 2
self.maxX -= 2
self._win = curses.newwin(
self.maxY, self.maxX,
self.Y, self.X)
self._win.bkgdset(' ', curses.color_pair(3))
self._win.erase()
self._focus = 0
self._widgets = [None, None, None]
self._too_small = False
''' add line editor '''
self._widgets[0] = SimpleCursesLineEdit(
parent=self._win,
width=self.maxX - 2,
begin_y=self.Y + 1,
begin_x=self.X + 1,
boxed=False,
has_history=False,
caption='',
box_color=curses.color_pair(9),
caption_color=curses.color_pair(11),
edit_color=curses.color_pair(9),
cursor_color=curses.color_pair(8),
unfocused_color=curses.color_pair(10),
string_changed_handler=self._string_changed
)
self._widgets[0].string = string
self._widgets[0].bracket = False
self._widgets[0]._use_paste_mode = True
self._widgets[0]._mode_changed = self._show_alternative_modes
self._widgets[0].set_global_functions(self._global_functions)
''' enables direct insersion of ? and \ '''
self._widgets[0]._paste_mode = False
self._line_editor = self._widgets[0]
''' add horizontal push buttons '''
self._h_buttons = SimpleCursesHorizontalPushButtons(
Y=3, captions=('OK', 'Cancel'),
color_focused=curses.color_pair(9),
color=curses.color_pair(11),
bracket_color=curses.color_pair(10),
parent=self._win)
self._h_buttons.calculate_buttons_position()
self._widgets[1], self._widgets[2] = self._h_buttons.buttons
self._widgets[1]._focused = self._widgets[2].focused = False
if not self._orig_string:
self._widgets[1].enabled = False
def _show_alternative_modes(self):
if self._line_editor._paste_mode:
""" print paste mode is on on editor """
self._win.addstr(0, 18, '[', curses.color_pair(10))
self._win.addstr('Paste mode', curses.color_pair(11))
self._win.addstr('] ', curses.color_pair(10))
else:
if self._line_editor.backslash_pressed:
""" print editor's flag """
# fix for python 2
#self._win.addstr(*lin[i], '[', curses.color_pair(10))
self._win.addstr(0, 18, '[', curses.color_pair(10))
self._win.addstr('Extra mode', curses.color_pair(11))
self._win.addstr(']', curses.color_pair(10))
else:
""" print cleared editor's flag """
# fix for python 2
#self._win.addstr(*lin[i], 15 * ' ', curses.color_pair(10))
self._win.addstr(0, 18, 15 * ' ', curses.color_pair(10))
self._win.refresh()
def _string_changed(self):
pass
def resize(self, parent):
self._parent = parent
self.Y, self.X = self._parent.getbegyx()
self.Y += 1
self.X += 1
self._win.mvwin(self.Y, self.X)
self._h_buttons.calculate_buttons_position(parent=self._win)
self._win.refresh()
self.refresh_win()
def show(self):
self._win.addstr(0, 0, self._caption, curses.color_pair(10))
try:
self._win.addstr(5, 3, '─' * (self.maxX - 6), curses.color_pair(3))
except:
self._win.addstr(5, 3, '─'.encode('utf-8') * (self.maxX - 6), curses.color_pair(3))
self._win.addstr(5, int((self.maxX - 6) / 2), ' Help ', curses.color_pair(11))
self._win.addstr(6, 5, 'TAB', curses.color_pair(11))
self._win.addstr(', ', curses.color_pair(10))
self._win.addstr('Down', curses.color_pair(11))
self._win.addstr(' / ', curses.color_pair(10))
self._win.addstr('Up', curses.color_pair(11))
self._win.addstr(' Go to next / previous field.', curses.color_pair(10))
self._win.addstr(7, 5, 'ENTER', curses.color_pair(11))
self._win.addstr(' When in Line Editor, go to next field.', curses.color_pair(10))
step = 0
if self._orig_string:
self._win.addstr(8, 5, 'r', curses.color_pair(11))
self._win.addstr(', ', curses.color_pair(10))
self._win.addstr('^R', curses.color_pair(11))
self._win.addstr(8, 23, 'Revert to saved values (', curses.color_pair(10))
self._win.addstr('^R', curses.color_pair(11))
self._win.addstr(' in Line Editor).', curses.color_pair(10))
step = 1
self._win.addstr(8 + step, 5, 'Esc', curses.color_pair(11))
self._win.addstr(8 + step, 23, 'Cancel operation.', curses.color_pair(10))
self._win.addstr(9 + step, 5, 's', curses.color_pair(11))
self._win.addstr(' / ', curses.color_pair(10))
self._win.addstr('q', curses.color_pair(11))
self._win.addstr(9 + step , 23, 'Save / Cancel (not in Line Editor).', curses.color_pair(10))
self._win.addstr(10 + step, 5, '?', curses.color_pair(11))
self._win.addstr(10 + step, 23, 'Line editor help (in Line Editor).', curses.color_pair(10))
self._show_alternative_modes()
self._win.refresh()
self.refresh_win()
def refresh_win(self):
if not self._too_small:
self._line_editor.show(
self._win, opening=False,
new_y=self.Y + 1,
new_x=self.X + 1)
self._widgets[1].show()
self._widgets[2].show()
def _update_focus(self):
''' use _focused here to avoid triggering
widgets' refresh
'''
for i, x in enumerate(self._widgets):
if x:
if self._focus == i:
x._focused = True
else:
x._focused = False
def _focus_next(self):
if self._focus == len(self._widgets) - 1:
self._focus = 0
else:
focus = self._focus + 1
while not self._widgets[focus].enabled:
focus += 1
self._focus = focus
def _focus_previous(self):
if self._focus == 0:
self._focus = len(self._widgets) - 1
else:
focus = self._focus - 1
while not self._widgets[focus].enabled:
focus -= 1
self._focus = focus
def keypress(self, char):
''' Extra parameter editor keypress
Returns:
0: Response ready (in edit_string)
1: Continue
2: Display line editor help
'''
ret = 1
if char == ord('?') and self._focus > 0:
return 2
elif char in (curses.KEY_EXIT, 27, ord('q')) and \
self._focus > 0:
self.edit_string = ''
ret = 0
elif char in (ord('\t'), 9, curses.KEY_DOWN):
self._focus_next()
elif char == curses.KEY_UP:
self._focus_previous()
elif char in (curses.KEY_ENTER, ord('\n'), ord('\r')):
if self._focus == 0:
''' go to next field '''
self._focus_next()
elif self._focus == 1:
''' save string '''
self.edit_string = self._line_editor.string.strip()
ret = 0
else:
''' cancel '''
self.edit_string = ''
ret = 0
elif char == ord('s') and self._focus > 0:
''' s, execute '''
if self._widgets[1].enabled:
self.edit_string = self._line_editor.string.strip()
ret = 0
elif self._focus == 0:
'''
Returns:
2: display help
1: get next char
0: exit edit mode, string isvalid
-1: cancel
'''
ret = self._line_editor.keypress(self._win, char)
if ret == 2:
self._win.touchwin()
elif ret == 1:
''' get next char '''
if self._line_editor.string.strip():
self._widgets[1].enabled = True
else:
self._widgets[1].enabled = False
ret = 1
elif ret == 0:
''' exit, string is valid '''
self.edit_string = self._line_editor.string.strip()
ret = 0
elif ret == -1:
''' cancel '''
self.edit_string = ''
ret = 0
elif char in self._global_functions.keys():
self._global_functions[char]()
return 1
if ret == 1:
self._update_focus()
self.refresh_win()
''' Continue '''
return ret
try:
self._count += 1
except:
self._count = 1
if self._count > 2:
return 0
else:
return 1
def _update_focus(self):
''' use _focused here to avoid triggering
widgets' refresh
'''
for i, x in enumerate(self._widgets):
if x:
if self._focus == i:
x._focused = True
else:
x._focused = False
class ExtraParameters(object):
''' display player's extra parameters
in a foreign curses window ('Z')
'''
def __init__(self,
config,
player,
win,
focus,
startY=1,
startX=1,
max_lines=11,
from_config=True,
global_functions=None):
self._cnf = config
self._orig_params = deepcopy(self._cnf.saved_params)
self._global_functions = set_global_functions(global_functions)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('original parameters = {}'.format(self._orig_params))
self._orig_player = player
# logger.error('DE orig player = {}'.format(self._orig_player))
self._win = win
self._focus = focus
self.from_config = from_config
''' start Y, X '''
self.startY = startY
self.startX = startX
''' maximum number of lines to display '''
self.max_lines = max_lines
self.reset(saved=False)
''' set cursor to active item '''
for a_key in self._selections.keys():
self._selections[a_key][0] = self._selections[a_key][2]
self._get_width()
def check_parameters(self):
''' Exrta Parameters check '''
for a_key in self._orig_params.keys():
if self._orig_params[a_key] != self._working_params[a_key]:
self._cnf.dirty_config = self._cnf.params_changed = True
return True
return False
def reset(self, saved=True):
''' reset Player Selection Options
Parameter
========
saved:
False - load params from config (default)
True - load saved params from config
'''
self._player = self._orig_player
if saved:
self._working_params = deepcopy(self._cnf.saved_params)
else:
self._working_params = deepcopy(self._cnf.params)
self._selections = {
'mpv': [0, 0, 0],
'mplayer': [0, 0, 0],
'vlc': [0, 0, 0]
}
self._items_dict = {
'mpv': [],
'mplayer': [],
'vlc': []
}
self._dict_to_list()
self._items = self._items_dict[self._player]
self._original_active = self.active
@property
def player(self):
return self._player
@player.setter
def player(self, a_player):
if a_player in SUPPORTED_PLAYERS:
self._player = a_player
self._items = self._items_dict[a_player]
self.refresh_win()
@property
def selection(self):
return(self._selections[self._player][0])
@selection.setter
def selection(self, val):
self._selections[self._player][0] = val
@property
def startPos(self):
return(self._selections[self._player][1])
@startPos.setter
def startPos(self, val):
self._selections[self._player][1] = val
@property
def original_active(self):
if self._player == self._cnf.PLAYER_NAME:
return self._original_active
else:
return self.selection
@original_active.setter
def original_active(self, val):
raise ValueError('property is read only')
@property
def active(self):
''' this is the parameter to be used by the player '''
return(self._selections[self._player][2])
@active.setter
def active(self, val):
self._selections[self._player][2] = val
@property
def params(self):
''' Returns the parameters as changed by the user '''
return self._orig_params
@params.setter
def params(self, val):
raise ValueError('parameter is read only')
def _dict_to_list(self):
''' convert self._working_params dict
to self._items dict, and set self.active
'''
# logger.error('DE\n')
# logger.error('DE working params = {}'.format(self._working_params))
for a_param_set in self._working_params.keys():
for i, a_param in enumerate(self._working_params[a_param_set]):
if i == 0:
# logger.error('DE a_param = {}'.format(a_param))
self._selections[a_param_set][2] = int(a_param) - 1
else:
self._items_dict[a_param_set].append(a_param)
def _list_to_dict(self):
''' convert self._items_dict to self._working_params '''
for a_params_set in self._items_dict.keys():
the_list = [self._selections[a_params_set][2] + 1]
the_list.extend(self._items_dict[a_params_set])
self._working_params[a_params_set] = the_list[:]
def _get_width(self):
Y, X = self._win.getmaxyx()
self._width = X - self.startX - 2
def refresh_win(self):
for a_line in range(0, self.max_lines):
i = a_line + 1
d_str = ' ' + str(i) + '.' if i < 10 else str(i) + '.'
self._win.addstr(
self.startY + a_line,
self.startX,
d_str,
curses.color_pair(11)
)
for a_line in range(0, len(self._items)):
if a_line == len(self._items):
break
else:
col = self._get_color(a_line)
item_str = self._items[a_line]
cjk_len = cjklen(item_str) + 3
if cjk_len > self._width - 1:
d_str = ' ' + item_str[:self._width - 4] + ' '
else:
d_str = ' ' + item_str + ' ' * (self._width - cjk_len)
self._win.addstr(
self.startY + a_line,
self.startX + 3,
d_str,
col
)
self._win.refresh()
def _get_color(self, a_line):
col = curses.color_pair(10)
if self._focus():
if a_line == self.active:
if a_line == self.selection:
col = curses.color_pair(9)
else:
col = curses.color_pair(11)
elif a_line == self.selection:
col = curses.color_pair(6)
else:
if a_line == self.active:
col = curses.color_pair(11)
return col
def set_player(self, a_player):
if a_player in SUPPORTED_PLAYERS:
self._orig_player = self._player
self._player = a_player
self._items = self._items_dict[a_player]
if len(self._items) < self.max_lines:
''' "erase" window '''
empty_str = ' ' * self._width
for a_line in range(len(self._items), self.max_lines):
self._win.addstr(self.startY + a_line,
self.startX,
empty_str,
curses.color_pair(10))
self.refresh_win()
def resize(self, window, startY=None, startX=None):
self._win = window
if startY is not None:
self.startY = startY
if startX is not None:
self.startX = startX
self._get_width()
''' erase params window
done by containing window
'''
if self.from_config:
self.refresh_win()
def set_window(self, window):
self.resize(window=window)
def _go_up(self, how_much=1):
old_selection = self.selection
self.selection -= how_much
if old_selection == 0:
self.selection = len(self._items) - 1
else:
if self.selection < 0:
if how_much == 1:
self.selection = len(self._items) - 1
else:
self.selection = 0
self.refresh_win()
def _go_down(self, how_much=1):
old_selection = self.selection
self.selection += how_much
if old_selection == len(self._items) - 1:
self.selection = 0
else:
if self.selection >= self.max_lines or \
self.selection >= len(self._items):
if how_much == 1:
self.selection = 0
else:
self.selection = len(self._items) - 1
self.refresh_win()
def save_results(self):
''' pass working parameters to original parameters
effectively saving any changes.
'''
# logger.error('DE save_results')
# logger.error('DE 1 working_params = {}'.format(self._working_params))
self._list_to_dict()
# logger.error('DE 2 working_params = {}'.format(self._working_params))
self.check_parameters()
# logger.error('DE 3 working_params = {}'.format(self._working_params))
self._orig_params = deepcopy(self._working_params)
if logger.isEnabledFor(logging.DEBUG):
logger.debug('new parameters (not saved) = {}'.format(self._orig_params))
def keypress(self, char):
''' Extra parameters keypress
Returns:
-2 - cancel
-1 - continue
0 - activate selection
1 - display help
2 - error, number of max lines reached
3 - error, cannot edit or delete first item
4 - edit parameter
5 - add parameter
6 - line editor help
'''
if char in self._global_functions.keys():
self._global_functions[char]()
return -1
elif char in (
curses.KEY_ENTER, ord('\n'),
ord('\r'), ord(' '), ord('l'),
curses.KEY_RIGHT, ord('s')):
''' activate selection '''
# logger.error('DE active ={}, selection={}'.format(self.active, self.selection))
self.active = self.selection
# logger.error('DE active ={}, selection={}'.format(self.active, self.selection))
''' reset profile '''
if self._cnf.PLAYER_NAME == self._orig_player:
if not self._items[self.active].startswith('profile:'):
self._cnf._profile_name = 'pyradio'
if self.from_config:
self.refresh_win()
else:
self.save_results()
return 0
elif char in (
curses.KEY_EXIT, 27,
ord('q'), curses.KEY_LEFT,
ord('h')
):
self._win.nodelay(True)
char = self._win.getch()
self._win.nodelay(False)
if char == -1:
''' ESCAPE '''
self.reset()
return -2
elif char == ord('?'):
''' display help '''
return 1
elif char in (curses.KEY_UP, ord('k')):
self._go_up()
elif char in (curses.KEY_DOWN, ord('j')):
self._go_down()
elif char in (curses.KEY_NPAGE, ):
self._go_down(5)
elif char in (curses.KEY_PPAGE, ):
self._go_up(5)
elif char == ord('g'):
self.selection = 0
self.refresh_win()
elif char == ord('G'):
self.selection = len(self._items) - 1
self.refresh_win()
elif char in (ord('x'), curses.KEY_DC):
if self.from_config:
if self.selection == 0:
''' error: cannot delete first item '''
return 3
else:
self._win.addstr(
self.startY + len(self._items) - 1,
self.startX,
' ' * (self._width + 1),
curses.color_pair(10)
)
if self.active == self.selection or self.selection > len(self._items):
self.active = 0
elif self.active > self.selection:
self.active -= 1
self._items.pop(self.selection)
while self.selection > len(self._items) - 1:
self.selection -= 1
self.refresh_win()
elif char == ord('e'):
if self.from_config:
if self.selection == 0:
''' error: cannot edit first item '''
return 3
''' edit parameter '''
return 4
elif char == ord('a'):
if self.from_config:
if len(self._items) == self.max_lines:
''' error: cannot add more items '''
return 2
''' add parameter '''
return 5
return -1
class PyRadioSelectPlayer(object):
maxY = 14
maxX = 72
selection = 0
_title = ' Player Selection '
_win = None
_extra = None
_working_players = [[], []]
''' mlength is the length of the longest item in the
players list, which is '[ ] mplayer ' = 14
'''
mlength = 13
def __init__(self, config, parent, player,
global_functions=None):
if logger.isEnabledFor(logging.DEBUG):
logger.debug('current players = {}'.format(player))
self._cnf = config
self._parent = parent
self._parent_maxY, self._parent_maxX = parent.getmaxyx()
self.player = player
self._orig_player = player
self._global_functions = set_global_functions(global_functions)
self.focus = True
''' Is editor active?
0 - Not active
1 - Adding a parameter
2 - Editing a parameter
'''
self.editing = 0
''' result of parameter editing'''
self.edit_string = None
''' parameter editor window '''
self._parameter_editor = None
''' players contain supported players
it is a list of lists
each list contains three items
0 - player name
1 - True if enabled for detection
2 - True if usable on platform
'''
self._players = []
self._populate_players()
self.init_window()
self.refresh_win(do_params=True)
@property
def from_config(self):
if self._extra:
return self._extra.from_config
else:
return True
@from_config.setter
def from_config(self, val):
raise ValueError('property is read only')
@property
def is_dirty(self):
if self._extra is not None:
return self._extra.is_dirty
return False
@is_dirty.setter
def is_dirty(self, val):
raise ValueError('property is read only')
def init_window(self):
self._win = None
Y = int((self._parent_maxY - self.maxY) / 2)
if Y % 2 == 1:
Y += 1
self._win = curses.newwin(
self.maxY, self.maxX,
Y,
int((self._parent_maxX - self.maxX) / 2)
)
if self._extra is None:
self._extra = ExtraParameters(
self._cnf,
self.selected_player_name(),
self._win,
lambda: not self.focus,
startY=2,
startX=self.mlength + 11,
)
else:
self._extra.set_window(self._win)
def selected_player_name(self):
return self._players[self.selection][0]
def _populate_players(self):
self._players.clear()
parts = self.player.replace(' ', '').split(',')
for ap in parts:
self._players.append([ap, True, True])
if len(parts) < len(SUPPORTED_PLAYERS):
''' add missing player '''
for ap in SUPPORTED_PLAYERS:
if ap not in parts:
self._players.append([ap, False, True])
if logger.isEnabledFor(logging.DEBUG):
logger.debug('all players parameters = {}'.format(self._players))
def refresh_win(self, do_params=False):
self._win.bkgdset(' ', curses.color_pair(3))
self._win.erase()
self._win.box()
if self.editing == 0:
self._win.addstr(
0, int((self.maxX - len(self._title)) / 2),
self._title,
curses.color_pair(11))
self._win.addstr(1, 2, 'Supported Players', curses.color_pair(11))
self._win.addstr(1, self.mlength + 11, 'Extra Player Parameters', curses.color_pair(11))
#self._win.addstr(1, int(self.maxX / 2 + 2), 'Active' , curses.color_pair(11))
self.refresh_selection()
if do_params:
self._extra.set_player(self.selected_player_name())
else:
if self.editing == 1:
title = ' Add player paremeter '
else:
title = ' Edit player paremeter '
self._win.addstr(
0, int((self.maxX - len(title)) / 2),
title, curses.color_pair(11))
self._win.refresh()
self._parameter_editor.show()
def refresh_selection(self):
for i in range(0, len(self._players)):
token = ' [✔] ' if self._players[i][1] else ' [ ] '
first_char = last_char = ' '
if self.focus:
if self.selection == i:
col = curses.color_pair(6)
else:
col = curses.color_pair(10)
else:
col = curses.color_pair(10)
if self.selection == i:
col = curses.color_pair(11)
'''
first_char = '>'
last_char = '<'
'''
pad = self.mlength - (len(token) + len(self._players[i][0])) + 3
self._win.addstr(
i+2, 1,
first_char + token + self._players[i][0] +
pad * ' ' + last_char,
col
)
# self._win.hline(i+2, 1, ' ', self.maxX - 2, curses.color_pair(10))
self._win.refresh()
return
if self._working_players[0]:
if self.selection[0] >= len(self._working_players[0]):
self.selection[0] = 0
def refresh_and_resize(self, maxY, maxX):
self._parent_maxY = maxY
self._parent_maxX = maxX
self.init_window()
self._extra.set_window(self._win)
if self._parameter_editor:
self._parameter_editor.resize(self._win)
self.refresh_win(True)
def reset(self):
self._extra.reset()
self._populate_players()
self.refresh_win(do_params=True)
self._cnf.params_changed = False
def keypress(self, char):
''' Player selection keypress
Returns:
-2 - error, number of max lines reached
-3 - error, cannot edit or delete first item
-1 - Continue
0 - Accept changes
1 - Cancel
2 - Display editor help
3 - Editor is visible
4 - Editor exited
'''
if self.editing == 0:
''' focus on players '''
if char in self._global_functions.keys():
self._global_functions[char]()
elif char in (9, ):
if self._players[self.selection][1]:
self._switch_column()
self.refresh_selection()
elif char in (
curses.KEY_EXIT, 27,
ord('q'), curses.KEY_LEFT,
ord('h')
):
self._win.nodelay(True)
char = self._win.getch()
self._win.nodelay(False)
if char == -1:
''' ESCAPE '''
return 1
elif char == ord('r'):
self.reset()
elif char == ord('s'):
working_players = []
for a_player in self._players:
if a_player[1]:
working_players.append(a_player[0])
if working_players:
self.player = ','.join(working_players)
else:
self.player = ','.join(SUPPORTED_PLAYERS)
self._extra.save_results()
return 0
if self.focus:
if char in (
curses.KEY_ENTER, ord('\n'), ord('\r'),
ord(' '), ord('l'), curses.KEY_RIGHT
):
self._players[self.selection][1] = not self._players[self.selection][1]
self.refresh_selection()
elif char in (curses.ascii.NAK, 21):
''' ^U, move player Up '''
x = self._players.pop(self.selection)
if self.selection == 0:
self._players.append(x)
self.selection = len(self._players) - 1
else:
self.selection -= 1
self._players.insert(self.selection, x)
self.refresh_selection()
elif char in (curses.ascii.EOT, 4):
''' ^D, move player Down '''
if self.selection == len(self._players) - 1:
x = self._players.pop(self.selection)
self._players.insert(0, x)
self.selection = 0
else:
x = self._players.pop(self.selection)
self.selection += 1
self._players.insert(self.selection, x)
self.refresh_selection()
elif char in (curses.KEY_UP, ord('k')):
self.selection -= 1
if self.selection < 0:
self.selection = len(self._players) - 1
self.refresh_selection()
self._extra.set_player(self.selected_player_name())
elif char in (curses.KEY_DOWN, ord('j')):
self.selection += 1
if self.selection == len(self._players):
self.selection = 0
self.refresh_selection()
self._extra.set_player(self.selected_player_name())
else:
''' focus on parameters '''
ret = self._extra.keypress(char)
if ret == 2:
''' error, number of max lines reached '''
return -2
elif ret == 3:
''' error, cannot edit or delete first item '''
return -3
elif ret == 4:
''' edit parameter '''
self.editing = 2
self._parameter_editor = ExtraParametersEditor(
self._win,
self._cnf,
string=self._extra._items[self._extra.selection],
global_functions=self._global_functions
)
self.refresh_win()
return 3
elif ret == 5:
''' add parameter '''
self._parameter_editor = ExtraParametersEditor(
self._win,
self._cnf,
global_functions=self._global_functions
)
self.editing = 1
self.refresh_win()
return 3
else:
''' return from parameter editor
adding or editing a parameter
'''
ret = self._parameter_editor.keypress(char)
if ret == 0:
''' accept parameter or cancel '''
if self._parameter_editor.edit_string:
if self.editing == 1:
''' add parameter '''
self._extra._items.append(self._parameter_editor.edit_string)
self._extra.selection = len(self._extra._items) - 1
if logger.isEnabledFor(logging.DEBUG):
logger.debug('New parameter: ' + self._extra._items[-1])
else:
''' change parameter '''
self._extra._items[self._extra.selection] = self._parameter_editor.edit_string
if logger.isEnabledFor(logging.DEBUG):
logger.debug('New parameter value: ' + self._parameter_editor.edit_string)
self.editing = 0
self.refresh_win(True)
self._parameter_editor = None
return 4
elif ret == 2:
''' show editor help '''
return ret
return -1
def _switch_column(self):
self.focus = not self.focus
self.refresh_selection()
self._extra.refresh_win()
def setPlayers(self, these_players):
self.player = these_players
self._players = []
self._populate_players()
class PyRadioSelectEncodings(object):
max_enc_len = 15
_win = None
_title = ' Encoding Selection '
_num_of_columns = 4
maxY = maxX = 10
_column = _row = 0
_encodings = []
list_maxY = 0
startPos = 0
selection = 0
_invalid = []
def __init__(self, maxY, maxX, encoding, config_encoding,
global_functions=None):
self._parent_maxY = maxY
self._parent_maxX = maxX
self.encoding = encoding
self._orig_encoding = encoding
self._config_encoding = config_encoding
self._orig_encoding = encoding
self._encodings = get_encodings()
self._num_of_rows = int(len(self._encodings) / self._num_of_columns)
self.init_window()
def set_global_functions(self, global_functions):
self._global_functions = global_functions
def set_reduced_global_functions(self, global_functions):
self._global_functions = set_global_functions(global_functions)
def init_window(self, set_encoding=True):
self._win = None
self._win = curses.newwin(
self.maxY, self.maxX,
int((self._parent_maxY - self.maxY) / 2) + 1,
int((self._parent_maxX - self.maxX) / 2))
if set_encoding:
self.setEncoding(self.encoding, init=True)
def _fix_geometry(self):
self._num_of_columns = int((self._parent_maxX - 2) / (self.max_enc_len + 2))
if self._num_of_columns > 8:
self._num_of_columns = 8
elif self._num_of_columns > 4:
self._num_of_columns = 4
self.maxY = int(len(self._encodings) / self._num_of_columns) + 5
if len(self._encodings) % self._num_of_columns > 0:
self.maxY += 1
if self._num_of_columns == 8:
maxY = int(len(self._encodings) / 6) + 5
if len(self._encodings) % 6 > 0:
maxY += 1
if maxY < self._parent_maxY:
self.maxY = maxY
self._num_of_columns = 6
while self.maxY > self._parent_maxY - 2:
self.maxY -= 1
self.list_maxY = self.maxY - 5
self.maxX = self._num_of_columns * (self.max_enc_len + 2) + 2
''' Enable this to see geometry '''
#if logger.isEnabledFor(logging.DEBUG):
# logger.debug('maxY,maxX = {0},{1}'.format(self.maxY, self.maxX))
# logger.debug('Number of columns = {}'.format(self._num_of_columns))
# logger.debug('Number of rows = {}'.format(self._num_of_rows))
# logger.debug('Number of visible rows = {}'.format(self.list_maxY))
def refresh_win(self, set_encoding=True):
''' set_encoding is False when resizing '''
self._fix_geometry()
self.init_window(set_encoding)
self._win.bkgdset(' ', curses.color_pair(3))
self._win.erase()
self._win.box()
self._win.addstr(
0, int((self.maxX - len(self._title)) / 2),
self._title,
curses.color_pair(11))
for i in range(1, self.maxX - 1):
try:
self._win.addch(self.maxY - 4, i, '─', curses.color_pair(3))
except:
self._win.addstr(self.maxY - 4, i, u'─'.encode('utf-8'), curses.color_pair(3))
try:
self._win.addch(self.maxY - 4, 0, '├', curses.color_pair(3))
self._win.addch(self.maxY - 4, self.maxX - 1, '┤', curses.color_pair(3))
except:
self._win.addstr(self.maxY - 4, 0, u'├'.encode('utf-8'), curses.color_pair(3))
self._win.addstr(self.maxY - 4, self.maxX - 1, u'┤'.encode('utf-8'), curses.color_pair(3))
self._num_of_rows = int(len(self._encodings) / self._num_of_columns)
self._get_invalids()
self.refresh_selection()
def refresh_selection(self):
if self._parent_maxX < 4 * (self.max_enc_len + 2) + 2 or self.maxY < 10:
self._too_small = True
else:
self._too_small = False
if self._too_small:
msg = 'Window too small to display content!'
if self.maxX - 2 < len(msg):
msg = 'Window too small!'
self._win.hline(self.maxY - 4, 1, ' ', self.maxX - 2, curses.color_pair(10))
try:
self._win.addch(self.maxY - 4, 0, '│', curses.color_pair(3))
self._win.addch(self.maxY - 4, self.maxX - 1, '│', curses.color_pair(3))
except:
self._win.addstr(self.maxY - 4, 0, u'│'.encode('utf-8'), curses.color_pair(3))
self._win.addstr(self.maxY - 4, self.maxX - 1, u'│'.encode('utf-8'), curses.color_pair(3))
self._win.addstr(
int(self.maxY / 2),
int((self.maxX - len(msg)) / 2),
msg, curses.color_pair(10))
else:
self._win.hline(self.maxY - 3, 1, ' ', self.maxX - 2, curses.color_pair(10))
self._win.hline(self.maxY - 2, 1, ' ', self.maxX - 2, curses.color_pair(10))
self._set_startPos()
for i in range(0, self._num_of_columns):
for y in range(0, self.list_maxY):
xx = i * self.max_enc_len + 2 + i * 2
yy = y + 1
pos = self.startPos + i * self._num_of_rows + y
if i > 0:
pos += i
if pos == self.selection:
if self._encodings[self.selection][0] == self._orig_encoding:
col = curses.color_pair(9)
else:
col = curses.color_pair(6)
self._win.addstr(self.maxY - 3, 1, ' ' * (self.maxX - 2), curses.color_pair(11))
self._win.addstr(self.maxY - 3, 2, ' Alias: ', curses.color_pair(11))
self._win.addstr(self._encodings[pos][1][:self.maxX - 14], curses.color_pair(10))
self._win.addstr(self.maxY - 2, 1, ' ' * (self.maxX - 2), curses.color_pair(11))
self._win.addstr(self.maxY - 2, 2, 'Language: ', curses.color_pair(11))
self._win.addstr(self._encodings[pos][2][:self.maxX - 14], curses.color_pair(10))
else:
col = curses.color_pair(10)
if pos < len(self._encodings):
if self._encodings[pos][0] == self._orig_encoding:
col = curses.color_pair(11)
self._win.addstr(yy, xx - 1,
' ' * (self.max_enc_len + 2),
col)
if pos < len(self._encodings):
self._win.addstr(yy, xx, self._encodings[pos][0], col)
self._win.refresh()
def refresh_and_resize(self, maxY, maxX):
self._parent_maxY = maxY
self._parent_maxX = maxX
self.refresh_win(set_encoding=False)
self._resize()
def _get_invalids(self):
self._invalid = []
col = self._num_of_columns - 1
row = self._num_of_rows
b = self._col_row_to_selection(col, row)
while b >= len(self._encodings):
self._invalid.append((col, row))
row -= 1
b = self._col_row_to_selection(col, row)
def _set_startPos(self):
try:
if self.list_maxY == self._num_of_rows + 1:
self.startPos = 0
except:
pass
if self.startPos < 0:
self.startPos = 0
def _resize(self, init=False):
col, row = self._selection_to_col_row(self.selection)
if not (self.startPos <= row <= self.startPos + self.list_maxY - 1):
while row > self.startPos:
self.startPos += 1
while row < self.startPos + self.list_maxY - 1:
self.startPos -= 1
''' if the selection at the end of the list,
try to scroll down '''
if init and row > self.list_maxY:
new_startPos = self._num_of_rows - self.list_maxY + 1
if row > new_startPos:
if logger.isEnabledFor(logging.DEBUG):
logger.debug('setting startPos at {}'.format(new_startPos))
self.startPos = new_startPos
self.refresh_selection()
def setEncoding(self, this_encoding, init=False):
ret = self._is_encoding(this_encoding)
if ret == -1:
if logger.isEnabledFor(logging.ERROR):
logger.error('encoding "{}" not found, reverting to "utf-8"'.format(this_encoding))
self.encoding = 'utf-8'
self.selection = self._is_encoding(self.encoding)
else:
self.selection = ret
self.encoding = this_encoding
self._resize(init)
def _is_encoding(self, a_string):
def in_alias(a_list, a_string):
splited = a_list.split(',')
for n in splited:
if n.strip() == a_string:
return True
return False
for i, an_encoding in enumerate(self._encodings):
if a_string == an_encoding[0] or in_alias(an_encoding[1], a_string):
return i
return -1
def _fix_startPos(self, direction=1):
col, row = self._selection_to_col_row(self.selection)
startRow = self.startPos
endRow = self.startPos + self.list_maxY - 1
if not (startRow <= row <= endRow):
self.startPos = self.startPos + direction
if direction > 0:
#if self.startPos >= self.list_maxY or row == 0:
if row == 0:
self.startPos = 0
else:
self._resize()
elif direction < 0:
if row == self._num_of_rows - 2 or row == self._num_of_rows:
self.startPos = self._num_of_rows - self.list_maxY + 1
elif self.startPos < 0:
self._resize(init=True)
if self.startPos < 0:
self.startPos = 0
def _selection_to_col_row(self, sel):
x = int(sel / (self._num_of_rows+1))
y = sel % (self._num_of_rows + 1)
return x, y
def _col_row_to_selection(self, a_column, a_row):
return (self._num_of_rows + 1) * a_column + a_row
def keypress(self, char):
''' Encoding key press
'''
if char in self._global_functions.keys():
self._global_functions[char]()
elif char in (ord('c'), ):
self.encoding = self._config_encoding
self.setEncoding(self.encoding, init=True)
elif char in (ord('r'), ):
self.encoding = self._orig_encoding
self.setEncoding(self.encoding, init=True)
elif char in (curses.KEY_UP, ord('k')):
self.selection -= 1
if self.selection < 0:
self.selection = len(self._encodings) - 1
self._fix_startPos(-1)
self.refresh_selection()
elif char in (curses.KEY_DOWN, ord('j')):
self.selection += 1
if self.selection == len(self._encodings):
self.selection = 0
self._fix_startPos(1)
self.refresh_selection()
elif char in (curses.KEY_RIGHT, ord('l')):
self._column, self._row = self._selection_to_col_row(self.selection)
self._column += 1
if self._column == self._num_of_columns:
self._column = 0
self._row += 1
if self._row == self._num_of_rows:
self._row = 0
if (self._column, self._row) in self._invalid:
self._column = 0
self._row += 1
if self._row > self._num_of_rows:
self._row = 0
self.selection = self._col_row_to_selection(self._column, self._row)
self._fix_startPos(1)
self.refresh_selection()
elif char in (curses.KEY_LEFT, ord('h')):
self._column, self._row = self._selection_to_col_row(self.selection)
self._column -= 1
if self._column == -1:
self._column = self._num_of_columns - 1
self._row -= 1
if (self._column, self._row) in self._invalid:
self._column -= 1
self.selection = self._col_row_to_selection(self._column, self._row)
self._fix_startPos(-1)
self.refresh_selection()
elif char in (curses.KEY_NPAGE, ):
if self.selection == len(self._encodings) - 1:
self.selection = 0
else:
self.selection += 5
if self.selection > len(self._encodings) - 1:
self.selection = len(self._encodings) - 1
self._fix_startPos(5)
self.refresh_selection()
elif char in (curses.KEY_PPAGE, ):
if self.selection == 0:
self.selection = len(self._encodings) - 1
else:
self.selection -= 5
if self.selection < 0:
self.selection = 0
self._fix_startPos(-5)
self.refresh_selection()
elif char in (curses.KEY_HOME, ord('g')):
self.selection = 0
self.startPos = 0
self.refresh_selection()
elif char in (curses.KEY_END, ord('G')):
self.selection = len(self._encodings) - 1
self.startPos = self._num_of_rows - self.list_maxY + 1
self.refresh_selection()
elif char in (curses.KEY_EXIT, 27,
ord('q'), curses.KEY_LEFT,
ord('h')):
self._win.nodelay(True)
char = self._win.getch()
self._win.nodelay(False)
if char == -1:
''' ESCAPE '''
return 1, ''
elif char in (curses.KEY_ENTER, ord('\n'),
ord('\r'), ord(' '), ord('s')):
return 0, self._encodings[self.selection][0]
return -1, ''
class PyRadioSelectPlaylist(object):
_win = None
_title = ' Playlist Selection '
maxY = maxX = _parent_maxY = _parent_maxX = 0
_items = []
_registers_path = None
startPos = 0
selection = 0
_selected_playlist_id = 0
_select_playlist_error = -2
pageChange = 5
jumpnr = ''
''' offset to current item for padding calculation '''
pad_adjustment = 0
def __init__(self,
parent,
config_path,
default_playlist,
include_registers=False,
global_functions=None):
''' Select a playlist from a list
include_registers changes its behavior
If it is False (default), it is used by config window
and permit playlist only selection.
Returns: state, playlist title
if it is True, it is used in \p (paste) function and
permits playlist and register selection.
default_playlist is removed from the list.
Returns: state, playlist/register path
'''
self._parent_maxY, self._parent_maxX = parent.getmaxyx()
try:
self._parent_Y, _ = parent.getbegyx()
except:
''' revert to old behavior '''
self._parent_Y = 1
self._config_path = config_path
self.playlist = default_playlist
self._orig_playlist = default_playlist
self._selected_playlist = default_playlist
self._include_registers = include_registers
#self._include_registers = True
if self._include_registers:
self._title = ' Paste: Select target '
self._playlist_in_editor = self._selected_playlist
self._global_functions = set_global_functions(global_functions)
self.init_window()
def __del__(self):
self._error_win = None
self._items = None
def init_window(self):
self._read_items()
self.maxY = self._num_of_items + 2
if self.maxY > self._parent_maxY - 2:
self.maxY = self._parent_maxY - 2
self._calculate_width()
self._win = None
Y = int((self._parent_maxY - self.maxY) / 2) + self._parent_Y
X = int((self._parent_maxX - self.maxX) / 2)
self._win = curses.newwin(self.maxY, self.maxX, Y, X)
def refresh_and_resize(self, parent_maxYX):
self._parent_maxY = parent_maxYX[0]
self._parent_maxX = parent_maxYX[1]
self.init_window()
self.refresh_win(resizing=True)
def _calculate_width(self):
self.maxX = self._max_len + 5 + len(str(self._num_of_items))
max_title = len(self._title) + 8
if self.maxX < max_title:
self.maxX = max_title
if self.maxX > self._parent_maxX - 4:
self.maxX = self._parent_maxX - 4
def refresh_win(self, resizing=False):
self._win.bkgdset(' ', curses.color_pair(3))
self._win.erase()
self._win.box()
self._win.addstr(
0, int((self.maxX - len(self._title)) / 2),
self._title,
curses.color_pair(11)
)
if resizing:
self._resize()
self.refresh_selection(resizing)
def refresh_selection(self, resizing=False):
pad = len(str(self.startPos + self.maxY - 2 - self.pad_adjustment))
# logger.error('DE \n\npos = {0}, pad = {1}\n\n'.format(self.startPos + self.maxY - 2 - self.pad_adjustment, pad))
for i in range(0, self.maxY - 2):
# logger.error('DE i = {0}, startPos = {1}'.format(i, self.startPos))
if i + self.startPos < self._num_of_items:
line, pad = self._format_line(i, pad)
colour = self._get_color(i)
self._win.hline(i + 1, 1, ' ', self.maxX - 2, colour)
self._win.addstr(i + 1, 1, line[:self.maxX - 3], colour)
else:
break
self._win.refresh()
if not resizing:
if self._select_playlist_error > -2:
self.print_select_playlist_error()
def _resize(self):
if self.maxY - 2 == self._num_of_items:
self.startPos = 0
else:
self._fix_startPos()
def _get_color(self, i):
col = curses.color_pair(10)
if self._items[i + self.startPos] == self._orig_playlist:
if i + self.startPos == self._selected_playlist_id:
col = curses.color_pair(9)
else:
col = curses.color_pair(11)
elif i + self.startPos == self._selected_playlist_id:
col = curses.color_pair(6)
return col
def _format_line(self, i, pad):
''' PyRadioSelectPlaylist format line '''
line = '{0}. {1}'.format(
str(i + self.startPos + 1).rjust(pad),
self._items[i + self.startPos]
)
return line, pad
def _read_items(self):
self._items = []
self._items = glob.glob(path.join(self._config_path, '*.csv'))
if len(self._items) > 0:
self._items.sort()
if self._include_registers:
self._registers_path = path.join(self._config_path, '.registers')
if platform == 'win32':
self._registers_path.replace('.reg', '_reg')
r_items = glob.glob(path.join(self._registers_path, '*.csv'))
if r_items:
r_items.sort()
self._items.extend(r_items)
if len(self._items) == 0:
return 0, -1
for i, an_item in enumerate(self._items):
if self._include_registers:
self._items[i] = an_item.replace(self._registers_path + sep, '').replace('.csv', '').replace('register_', 'Register: ')
self._items[i] = self._items[i].replace(self._config_path + sep, '')
else:
self._items[i] = an_item.replace(self._config_path + sep, '').replace('.csv', '')
if self._include_registers:
''' Remove playlist in editor '''
try:
self._items.remove(self._playlist_in_editor)
except ValueError:
pass
else:
''' get already loaded playlist id '''
for i, a_playlist in enumerate(self._items):
if a_playlist ==self._selected_playlist:
self._selected_playlist_id = i
break
self._max_len = cjklen(max(self._items, key=cjklen))
self._num_of_items = len(self._items)
def setPlaylist(self, a_playlist, adjust=True):
self._selected_playlist = a_playlist
if a_playlist == 'False':
self._selected_playlist_id = 0
elif a_playlist == 'random' or \
a_playlist == 'Random' or \
a_playlist is None:
self._selected_playlist_id = 1
for i, a_playlist in enumerate(self._items):
if a_playlist == self._selected_playlist:
self._selected_playlist_id = i
break
else:
self.setPlaylistById(0, adjust)
self.startPos = 0
self._selected_playlist = self._items[self._selected_playlist_id]
return
if adjust:
self._fix_startPos()
self.refresh_selection()
def setPlaylistById(self, an_id, adjust=True):
self._selected_playlist_id = an_id
if self._selected_playlist_id == self._num_of_items:
self._selected_playlist_id = 0
elif self._selected_playlist_id < 0:
self._selected_playlist_id = self._num_of_items - 1
#self._selected_playlist = self._items[self._selected_playlist_id]
if adjust:
self._fix_startPos()
self._selected_playlist = self._items[self._selected_playlist_id]
self.refresh_selection()
def _get_result(self):
if self._include_registers:
if self._items[self._selected_playlist_id].startswith('Register: '):
ret = self._items[self._selected_playlist_id].replace('Register: ', 'register_')
ret = path.join(self._config_path, '.registers', ret + '.csv')
else:
ret = path.join(self._config_path, self._items[self._selected_playlist_id] + '.csv')
if platform == 'win32':
ret.replace('.registers', '_registers')
return 0, ret
stationFile = path.join(self._config_path, self._items[self._selected_playlist_id] + '.csv')
self._select_playlist_error = 0
with open(stationFile, 'r', encoding='utf-8') as cfgfile:
try:
for row in csv.reader(filter(lambda row: row[0] != '#', cfgfile), skipinitialspace=True):
if not row:
continue
try:
name, url = [s.strip() for s in row]
self._select_playlist_error = 1
except ValueError:
try:
name, url, enc = [s.strip() for s in row]
self._select_playlist_error = 1
except ValueError:
try:
name, url, enc, br = [s.strip() for s in row]
self._select_playlist_error = 1
except ValueError:
self._select_playlist_error = -1
break
except:
self._select_playlist_error = -1
if self._select_playlist_error == -1 or \
self._select_playlist_error == 0:
self.print_select_playlist_error()
return -1, ''
else:
return 0, self._items[self._selected_playlist_id]
def print_select_playlist_error(self):
if self._select_playlist_error == -1 or \
self._select_playlist_error == 0:
if self._select_playlist_error == 0:
msg = 'This playlist is empty!'
else:
msg = 'This playlist is corrupt!'
self._error_win = curses.newwin(
5, 38,
int((self._parent_maxY - 5) / 2) + 1,
int((self._parent_maxX - 38) / 2))
self._error_win.bkgdset(' ', curses.color_pair(12))
self._error_win.erase()
self._error_win.box()
self._error_win.addstr(0, 16, ' Error ', curses.color_pair(11))
self._error_win.addstr(1, 2, msg, curses.color_pair(10))
self._error_win.addstr(2, 2, 'Please select another playlist...', curses.color_pair(10))
self._error_win.addstr(4, 14, ' Press any key to hide ', curses.color_pair(12))
self._error_win.refresh()
def _fix_startPos(self):
if self._num_of_items < self.maxY - 2:
self.startPos = 0
return
if self._selected_playlist_id < self.maxY - 2:
if self._selected_playlist_id < 0:
self._selected_playlist_id = 0
self.startPos = 0
elif self._selected_playlist_id >= self._num_of_items:
self._selected_playlist_id = self._num_of_items - 1
self.startPos = self._num_of_items - self.maxY + 2
elif self._selected_playlist_id > self._num_of_items - self.maxY + 2:
self.startPos = self._num_of_items - self.maxY + 2
else:
self.startPos = self._selected_playlist_id - int((self.maxY - 2) / 2)
def keypress(self, char):
''' Return restlt from playlist selection window
Results are:
-1, '' - Continue in window
0, station title - selected station title (for config window)
0, station path - selected station path (for paste window)
1, '' - Cancel
'''
if char in self._global_functions.keys():
self._global_functions[char]()
elif self._select_playlist_error == -1 or \
self._select_playlist_error == 0:
self._error_win = None
self._select_playlist_error = -2
self.refresh_selection()
elif char == ord('M'):
if self._num_of_items > 0:
self.setPlaylistById(int(self._num_of_items / 2) - 1)
#self._put_selection_in_the_middle(force=True)
self.refresh_selection()
elif char in (ord('r'), ):
self.setPlaylist(self._orig_playlist)
elif char in (curses.KEY_EXIT, 27, ord('q'), curses.KEY_LEFT, ord('h')):
self._win.nodelay(True)
char = self._win.getch()
self._win.nodelay(False)
if char == -1:
''' ESCAPE '''
self._select_playlist_error = -2
return 1, ''
elif char in (curses.KEY_ENTER, ord('\n'),
ord('\r'), ord(' '), ord('l'),
curses.KEY_RIGHT):
return self._get_result()
elif char in (curses.KEY_DOWN, ord('j')):
self.jumpnr = ''
if self._num_of_items > 0:
self.setPlaylistById(self._selected_playlist_id + 1,
adjust=False)
if self._selected_playlist_id == 0:
self.startPos = 0
elif self.startPos + self.maxY - 2 == self._selected_playlist_id:
self.startPos += 1
self.refresh_selection()
elif char in (curses.KEY_UP, ord('k')):
self.jumpnr = ''
if self._num_of_items > 0:
self.setPlaylistById(self._selected_playlist_id - 1,
adjust=False)
if self._selected_playlist_id == self._num_of_items - 1:
self.startPos = self._num_of_items - self.maxY + 2
if self.startPos < 0:
self.startPos = 0
elif self.startPos > self._selected_playlist_id:
self.startPos = self._selected_playlist_id
self.refresh_selection()
elif char in (curses.KEY_PPAGE, ):
self.jumpnr = ''
if self._num_of_items > 0:
old_id = self._selected_playlist_id
self._selected_playlist_id -= self.pageChange
if old_id == 0:
self._selected_playlist_id = self._num_of_items - 1
self.startPos = self._num_of_items - self.maxY + 2
elif self._selected_playlist_id < 0:
self._selected_playlist_id = 0
self.startPos = 0
else:
if not (self.startPos < self._selected_playlist_id < self.startPos + self.maxY - 2):
self.startPos = old_id - self.pageChange
if self.startPos > self._num_of_items - self.maxY + 2:
self.startPos = self._num_of_items - self.maxY + 2
self.refresh_selection()
elif char in (curses.KEY_NPAGE, ):
self.jumpnr = ''
old_id = self._selected_playlist_id
self._selected_playlist_id += self.pageChange
if old_id == self._num_of_items - 1:
self._selected_playlist_id = 0
self.startPos = 0
elif self._selected_playlist_id >= self._num_of_items:
self._selected_playlist_id = self._num_of_items - 1
self.startPos = self._num_of_items - self.maxY + 2
else:
if not (self.startPos < self._selected_playlist_id < self.startPos + self.maxY - 2):
self.startPos = old_id + self.pageChange
if self.startPos > self._num_of_items - self.maxY + 2:
self.startPos = self._num_of_items - self.maxY + 2
self.refresh_selection()
elif char in (curses.KEY_HOME, ord('g')):
self.jumpnr = ''
self._selected_playlist_id = 0
self.startPos = 0
self.refresh_selection()
elif char in (curses.KEY_END, ):
self.jumpnr = ''
self._selected_playlist_id = self._num_of_items - 1
self.startPos = self._num_of_items - self.maxY + 2
self.refresh_selection()
elif char in (ord('G'), ):
if self.jumpnr:
try:
if type(self) is PyRadioSelectStation:
jump = int(self.jumpnr) + 1
else:
jump = int(self.jumpnr) - 1
self.setPlaylistById(jump)
self.jumpnr = ''
return -1, ''
except:
pass
self._selected_playlist_id = self._num_of_items - 1
self.startPos = self._num_of_items - self.maxY + 2
self.refresh_selection()
elif char in map(ord, map(str, range(0, 10))):
if self._num_of_items > 0:
self.jumpnr += chr(char)
else:
self.jumpnr = ""
return -1, ''
class PyRadioSelectStation(PyRadioSelectPlaylist):
_default_playlist = ''
def __init__(self, parent, config_path, default_playlist, default_station,
global_functions=None):
self._default_playlist = default_playlist
self._orig_default_playlist = default_playlist
if logger.isEnabledFor(logging.INFO):
logger.info('displaying stations from: "{}"'.format(default_playlist))
PyRadioSelectPlaylist.__init__(self, parent, config_path, default_station)
self._global_functions = set_global_functions(global_functions)
self._title = ' Station Selection '
''' adding 2 to padding calculation
(i.e. no selection and random selection
'''
self.pad_adjustment = 2
def update_playlist_and_station(self, a_playlist, a_station):
#if logger.isEnabledFor(logging.DEBUG):
# logger.debug('default_playlist = {0}\norig_playlist = {1}\nselected_playlist = {2}\nplaylist = {3}'.format(self._default_playlist, self._orig_playlist, self._selected_playlist, self.playlist))
self._default_playlist = a_playlist
self._orig_playlist = a_station
self._selected_playlist = a_station
self.playlist = a_station
self._read_items()
def setStation(self, a_station):
if a_station == 'False':
self._selected_playlist_id = 0
self.startPos = 0
self.refresh_selection()
elif a_station == 'random' or a_station == 'Random' or a_station is None:
self._selected_playlist_id = 1
self.startPos = 0
self.refresh_selection()
else:
try:
pl = int(a_station) + 1
self.setPlaylistById(pl)
return
except:
self.setPlaylist(a_station)
def _get_result(self):
if self._selected_playlist_id == 0:
return 0, 'False'
elif self._selected_playlist_id == 1:
return 0, 'Random'
else:
return 0, str(self._selected_playlist_id - 1)
def _read_items(self):
self._items = []
stationFile = path.join(self._config_path, self._default_playlist + '.csv')
if path.exists(stationFile):
with open(stationFile, 'r', encoding='utf-8') as cfgfile:
try:
for row in csv.reader(filter(lambda row: row[0] != '#', cfgfile), skipinitialspace=True):
if not row:
continue
try:
name, _ = [s.strip() for s in row]
except ValueError:
try:
name, _, _ = [s.strip() for s in row]
except ValueError:
name, _, _, _ = [s.strip() for s in row]
self._items.append(name)
except:
pass
self._items.reverse()
self._items.append('Play a Random station on startup')
self._items.append('Do not play a station on startup')
self._items.reverse()
self._num_of_items = len(self._items)
self._max_len = cjklen(max(self._items, key=cjklen))
def _get_color(self, i):
or_pl = self._orig_playlist
if self._orig_playlist == 'False':
or_pl = -1
elif self._orig_playlist == 'random' or \
self._orig_playlist == 'Random' or \
self._orig_playlist is None:
or_pl = 0
col = curses.color_pair(10)
if i + self.startPos == int(or_pl) + 1:
if i + self.startPos == self._selected_playlist_id:
col = curses.color_pair(9)
else:
col = curses.color_pair(11)
elif i + self.startPos == self._selected_playlist_id:
col = curses.color_pair(6)
return col
def _format_line(self, i, pad):
''' PyRadioSelectStation format line '''
fixed_pad = pad
if i + self.startPos < 2:
line = '{0} {1}'.format(' '.rjust(fixed_pad),
self._items[i + self.startPos])
else:
line = '{0}. {1}'.format(str(i + self.startPos - 1).rjust(fixed_pad),
self._items[i + self.startPos])
return line, pad
def keypress(self, char):
if char in (ord('r'), ):
self.setStation(self._orig_playlist)
return -1, ''
elif char in self._global_functions.keys():
self._global_functions[char]()
return -1, ''
return PyRadioSelectPlaylist.keypress(self, char)
class PyRadioServerConfig(object):
def __init__(self):
pass
def show(self):
pass
def keypress(self, char):
pass
# pymode:lint_ignore=W901
|
5549a7944fa9f980ab373ea01979fb322a8f5aec
|
f6cc11462f27b92ad6018100c638662e98d84bc9
|
/specutils/spectra/spectrum_mixin.py
|
e067df95713666cf2c479689c07391536d1964a4
|
[
"BSD-3-Clause"
] |
permissive
|
astropy/specutils
|
7d422b9e8792202b08c95ada4f88a64509e21cb7
|
85d07a98bf9ed6478d7ba43270e44e7ea990c43f
|
refs/heads/main
| 2023-09-01T17:42:16.027995
| 2023-08-23T16:46:57
| 2023-08-23T16:46:57
| 2,577,269
| 145
| 113
| null | 2023-09-12T21:59:52
| 2011-10-14T16:11:38
|
Python
|
UTF-8
|
Python
| false
| false
| 13,278
|
py
|
spectrum_mixin.py
|
from copy import deepcopy
import numpy as np
import astropy.units.equivalencies as eq
from astropy import units as u
from astropy.utils.decorators import deprecated
from specutils.utils.wcs_utils import gwcs_from_array
DOPPLER_CONVENTIONS = {}
DOPPLER_CONVENTIONS['radio'] = u.doppler_radio
DOPPLER_CONVENTIONS['optical'] = u.doppler_optical
DOPPLER_CONVENTIONS['relativistic'] = u.doppler_relativistic
__all__ = ['OneDSpectrumMixin']
class OneDSpectrumMixin():
@property
def _spectral_axis_numpy_index(self):
return self.data.ndim - 1 - self.wcs.wcs.spec
@property
def _spectral_axis_len(self):
"""
How many elements are in the spectral dimension?
"""
return self.data.shape[self._spectral_axis_numpy_index]
@property
def _data_with_spectral_axis_last(self):
"""
Returns a view of the data with the spectral axis last
"""
if self._spectral_axis_numpy_index == self.data.ndim - 1:
return self.data
else:
return self.data.swapaxes(self._spectral_axis_numpy_index,
self.data.ndim - 1)
@property
def _data_with_spectral_axis_first(self):
"""
Returns a view of the data with the spectral axis first
"""
if self._spectral_axis_numpy_index == 0:
return self.data
else:
return self.data.swapaxes(self._spectral_axis_numpy_index, 0)
@property
def spectral_wcs(self):
"""
Returns the spectral axes of the WCS
"""
return self.wcs.axes.spectral
@property
def spectral_axis(self):
"""
Returns the SpectralCoord object.
"""
return self._spectral_axis
@property
@deprecated('v1.1', alternative="spectral_axis.unit")
def spectral_axis_unit(self):
"""
Returns the units of the spectral axis.
"""
return u.Unit(self.wcs.world_axis_units[0])
@property
def flux(self):
"""
Converts the stored data and unit information into a quantity.
Returns
-------
`~astropy.units.Quantity`
Spectral data as a quantity.
"""
return u.Quantity(self.data, unit=self.unit, copy=False)
def new_flux_unit(self, unit, equivalencies=None, suppress_conversion=False):
"""
Converts the flux data to the specified unit. This is an in-place
change to the object.
Parameters
----------
unit : str or `~astropy.units.Unit`
The unit to convert the flux array to.
equivalencies : list of equivalencies
Custom equivalencies to apply to conversions.
Set to spectral_density by default.
suppress_conversion : bool
Set to true if updating the unit without
converting data values.
Returns
-------
`~specutils.Spectrum1D`
A new spectrum with the converted flux array
"""
new_spec = deepcopy(self)
if not suppress_conversion:
if equivalencies is None:
equivalencies = eq.spectral_density(self.spectral_axis)
new_data = self.flux.to(
unit, equivalencies=equivalencies)
new_spec._data = new_data.value
new_spec._unit = new_data.unit
else:
new_spec._unit = u.Unit(unit)
return new_spec
@property
def velocity_convention(self):
"""
Returns the velocity convention
"""
return self.spectral_axis.doppler_convention
def with_velocity_convention(self, velocity_convention):
return self.__class__(flux=self.flux, wcs=self.wcs, meta=self.meta,
velocity_convention=velocity_convention)
@property
def rest_value(self):
return self.spectral_axis.doppler_rest
@rest_value.setter
def rest_value(self, value):
self.spectral_axis.doppler_rest = value
@property
def velocity(self):
"""
Converts the spectral axis array to the given velocity space unit given
the rest value.
These aren't input parameters but required Spectrum attributes
Parameters
----------
unit : str or ~`astropy.units.Unit`
The unit to convert the dispersion array to.
rest : ~`astropy.units.Quantity`
Any quantity supported by the standard spectral equivalencies
(wavelength, energy, frequency, wave number).
type : {"doppler_relativistic", "doppler_optical", "doppler_radio"}
The type of doppler spectral equivalency.
redshift or radial_velocity
If present, this shift is applied to the final output velocity to
get into the rest frame of the object.
Returns
-------
~`astropy.units.Quantity`
The converted dispersion array in the new dispersion space.
"""
if self.rest_value is None:
raise ValueError("Cannot get velocity representation of spectral "
"axis without specifying a reference value.")
if self.velocity_convention is None:
raise ValueError("Cannot get velocity representation of spectral "
"axis without specifying a velocity convention.")
equiv = getattr(u.equivalencies, 'doppler_{0}'.format(
self.velocity_convention))(self.rest_value)
new_data = self.spectral_axis.to(u.km/u.s, equivalencies=equiv).quantity
# if redshift/rv is present, apply it:
if self.spectral_axis.radial_velocity is not None:
new_data += self.spectral_axis.radial_velocity
return new_data
def with_spectral_unit(self, unit, velocity_convention=None,
rest_value=None):
"""
Returns a new spectrum with a different spectral axis unit.
Parameters
----------
unit : :class:`~astropy.units.Unit`
Any valid spectral unit: velocity, (wave)length, or frequency.
Only vacuum units are supported.
velocity_convention : 'relativistic', 'radio', or 'optical'
The velocity convention to use for the output velocity axis.
Required if the output type is velocity. This can be either one
of the above strings, or an `astropy.units` equivalency.
rest_value : :class:`~astropy.units.Quantity`
A rest wavelength or frequency with appropriate units. Required if
output type is velocity. The spectrum's WCS should include this
already if the *input* type is velocity, but the WCS's rest
wavelength/frequency can be overridden with this parameter.
.. note: This must be the rest frequency/wavelength *in vacuum*,
even if your spectrum has air wavelength units
"""
new_wcs, new_meta = self._new_spectral_wcs(
unit=unit,
velocity_convention=velocity_convention or self.velocity_convention,
rest_value=rest_value or self.rest_value)
spectrum = self.__class__(flux=self.flux, wcs=new_wcs, meta=new_meta)
return spectrum
def _new_wcs_argument_validation(self, unit, velocity_convention,
rest_value):
# Allow string specification of units, for example
if not isinstance(unit, u.UnitBase):
unit = u.Unit(unit)
# Velocity conventions: required for frq <-> velo
# convert_spectral_axis will handle the case of no velocity
# convention specified & one is required
if velocity_convention in DOPPLER_CONVENTIONS:
velocity_convention = DOPPLER_CONVENTIONS[velocity_convention]
elif (velocity_convention is not None and
velocity_convention not in DOPPLER_CONVENTIONS.values()):
raise ValueError("Velocity convention must be radio, optical, "
"or relativistic.")
# If rest value is specified, it must be a quantity
if (rest_value is not None and
(not hasattr(rest_value, 'unit') or
not rest_value.unit.is_equivalent(u.m, u.spectral()))):
raise ValueError("Rest value must be specified as an astropy "
"quantity with spectral equivalence.")
return unit
def _new_spectral_wcs(self, unit, velocity_convention=None,
rest_value=None):
"""
Returns a new WCS with a different Spectral Axis unit.
Parameters
----------
unit : :class:`~astropy.units.Unit`
Any valid spectral unit: velocity, (wave)length, or frequency.
Only vacuum units are supported.
velocity_convention : 'relativistic', 'radio', or 'optical'
The velocity convention to use for the output velocity axis.
Required if the output type is velocity. This can be either one
of the above strings, or an `astropy.units` equivalency.
rest_value : :class:`~astropy.units.Quantity`
A rest wavelength or frequency with appropriate units. Required if
output type is velocity. The cube's WCS should include this
already if the *input* type is velocity, but the WCS's rest
wavelength/frequency can be overridden with this parameter.
.. note: This must be the rest frequency/wavelength *in vacuum*,
even if your cube has air wavelength units
"""
unit = self._new_wcs_argument_validation(unit, velocity_convention,
rest_value)
if velocity_convention is not None:
equiv = getattr(u, 'doppler_{0}'.format(velocity_convention))
rest_value.to(unit, equivalencies=equiv)
# Store the original unit information for posterity
meta = self._meta.copy()
orig_unit = self.wcs.unit[0] if hasattr(self.wcs, 'unit') else self.spectral_axis.unit
if 'original_unit' not in self._meta:
meta['original_unit'] = orig_unit
# Create the new wcs object
if isinstance(unit, u.UnitBase) and unit.is_equivalent(
orig_unit, equivalencies=u.spectral()):
return gwcs_from_array(self.spectral_axis), meta
raise u.UnitConversionError(f"WCS units incompatible: {unit} and {orig_unit}.")
def _check_strictly_increasing_decreasing(self):
"""
Check that the self._spectral_axis is strictly increasing or decreasing
and raise an error if its not.
"""
spec_axis = self._spectral_axis
sorted_increasing = np.all(spec_axis[1:] >= spec_axis[:-1])
if sorted_increasing: # check increasing first, probably most common case
self._spectral_axis_direction = 'increasing'
return True
sorted_decreasing = np.all(spec_axis[1:] <= spec_axis[:-1])
if sorted_decreasing:
self._spectral_axis_direction = 'decreasing'
return True
return False
class InplaceModificationMixin:
# Example methods follow to demonstrate how methods can be written to be
# agnostic of the non-spectral dimensions.
def substract_background(self, background):
"""
Proof of concept, this subtracts a background spectrum-wise
"""
data = self._data_with_spectral_axis_last
if callable(background):
# create substractable array
pass
elif (isinstance(background, np.ndarray) and
background.shape == data[-1].shape):
substractable_continuum = background
else:
raise ValueError(
"background needs to be callable or have the same shape as the spectum")
data[-1] -= substractable_continuum
def normalize(self):
"""
Proof of concept, this normalizes each spectral dimension based
on a trapezoidal integration.
"""
# this gets a view - if we want normalize to return a new NDData object
# then we should make _data_with_spectral_axis_first return a copy.
data = self._data_with_spectral_axis_first
dx = np.diff(self.spectral_axis)
dy = 0.5 * (data[:-1] + data[1:])
norm = np.sum(dx * dy.transpose(), axis=-1).transpose()
data /= norm
def spectral_interpolation(self, spectral_value, flux_unit=None):
"""
Proof of concept, this interpolates along the spectral dimension
"""
data = self._data_with_spectral_axis_last
from scipy.interpolate import interp1d
interp = interp1d(self.spectral_axis.value, data)
x = spectral_value.to(self.spectral_axis.unit,
equivalencies=u.spectral())
y = interp(x)
if self.unit is not None:
y *= self.unit
if flux_unit is None: # Lim: Is this acceptable?
return y
else:
return y.to(flux_unit, equivalencies=u.spectral_density(x))
|
edc5aaa0cd201681af0c0e4d0dbc0fc993c8067d
|
2337351b228818e41be3002bd38f68f77c2aa074
|
/core/stencil.py
|
9fff81644dfee1c8f4da92a5cf217c84caaa3f0a
|
[
"BSD-3-Clause"
] |
permissive
|
nocproject/noc
|
57d40c680a1499374463e472434f9595ed6d1374
|
6e6d71574e9b9d822bec572cc629a0ea73604a59
|
refs/heads/master
| 2023-08-31T01:11:33.544573
| 2023-08-30T17:31:11
| 2023-08-30T17:31:11
| 107,815,776
| 105
| 33
|
BSD-3-Clause
| 2023-07-31T07:57:45
| 2017-10-21T21:04:33
|
Python
|
UTF-8
|
Python
| false
| false
| 3,603
|
py
|
stencil.py
|
# ---------------------------------------------------------------------
# Stencil Registry
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Python modules
import os
import logging
from operator import itemgetter
from xml.etree.ElementTree import parse as xml_parse, ParseError as XMLParseError
from dataclasses import dataclass
from typing import Optional
logger = logging.getLogger(__name__)
@dataclass
class Stencil(object):
id: str
title: str
width: float
height: float
path: str
class StencilRegistry(object):
prefix = os.path.join("ui", "pkg", "stencils")
# Replace missed stencil with Cisco | Router
DEFAULT_STENCIL = "Cisco/router"
DEFAULT_CLOUD_STENCIL = "Cisco/cloud"
def __init__(self):
self.choices = []
self.stencils = {} # id -> stencil
@classmethod
def _stencil_from_svg(cls, path: str) -> Optional[Stencil]:
"""
Read SVG and fetch metadata
:param path:
:return: Stencil insance or None in case of parsing error
"""
# Get library path
group = os.path.basename(os.path.dirname(path))
file_name = os.path.basename(path)
s_path = "%s/%s" % (group, file_name[:-4])
# Parse SVG
try:
doc = xml_parse(path)
except XMLParseError as e:
logger.info("[%s] Cannot parse stencil: %s", s_path, e)
return None
svg = doc.getroot()
# Get attributes
# width
width = svg.attrib.get("width")
if not width:
logger.info(
"[%s] Cannot parse stencil: <svg> tag contains no 'width' attribute", s_path
)
return None
# height
height = svg.attrib.get("height")
if not height:
logger.info(
"[%s] Cannot parse stencil: <svg> tag contains no 'height' attribute", s_path
)
return None
# Get title from <title> tag
title_el = svg.find("{http://www.w3.org/2000/svg}title")
if title_el is None or title_el.text is None:
title = None
else:
title = title_el.text.strip()
if title:
title = "%s | %s" % (group, title)
else:
logger.info("[%s] Missed <title> tag, generating title from file name", s_path)
title = "%s | %s" % (group, os.path.basename(path)[:-4])
# Build Stencil structure
return Stencil(
id=s_path, title=title, width=float(width), height=float(height), path=s_path
)
def load(self):
for root, dirs, files in os.walk(self.prefix):
for f in files:
if not f.endswith(".svg"):
continue
stencil = self._stencil_from_svg(os.path.join(root, f))
if stencil:
self.stencils[stencil.id] = stencil
self.choices = sorted(
((stencil_id, self.stencils[stencil_id].title) for stencil_id in self.stencils),
key=itemgetter(1),
)
def get(self, stencil_id):
"""
Get stencil instance by id
:param stencil_id:
:return: Stencil instance
"""
stencil = self.stencils.get(stencil_id)
if stencil:
return stencil
return self.stencils.get(self.DEFAULT_STENCIL)
stencil_registry = StencilRegistry()
stencil_registry.load()
|
f7a98f08dfe4ae017206bf9a244a5627e19ceb3a
|
2d05050d0ada29f7680b4df20c10bb85b0530e45
|
/python/tvm/autotvm/measure/measure.py
|
c9b82cd81c54012bc40c854d812f7fa1745a51a6
|
[
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"Zlib",
"LLVM-exception",
"BSD-2-Clause"
] |
permissive
|
apache/tvm
|
87cb617f9a131fa44e1693303aaddf70e7a4c403
|
d75083cd97ede706338ab413dbc964009456d01b
|
refs/heads/main
| 2023-09-04T11:24:26.263032
| 2023-09-04T07:26:00
| 2023-09-04T07:26:00
| 70,746,484
| 4,575
| 1,903
|
Apache-2.0
| 2023-09-14T19:06:33
| 2016-10-12T22:20:28
|
Python
|
UTF-8
|
Python
| false
| false
| 9,650
|
py
|
measure.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=pointless-string-statement,consider-using-enumerate,invalid-name
"""User facing API for specifying how to measure the generated code"""
import enum
import multiprocessing
from collections import namedtuple
class MeasureInput(namedtuple("MeasureInput", ["target", "task", "config"])):
"""
Stores all the necessary inputs for a measurement.
Parameters
----------
target : tvm.target.Target
The target device
task : task.Task
Task function
config : ConfigEntity
Specific configuration.
"""
class MeasureResult(namedtuple("MeasureResult", ["costs", "error_no", "all_cost", "timestamp"])):
"""
Stores all the results of a measurement
Parameters
----------
costs: Array of float or Array of Exception
If no error occurs during measurement, it is an array of measured running times.
If an error occurs during measurement, it is an array of the exception objections.
error_no: int
Denote error type, defined by MeasureErrorNo
all_cost: float
All cost of this measure, including rpc, compilation, test runs
timestamp: float
The absolute time stamp when we finish measurement.
"""
def __repr__(self):
error_no_str = (
str(MeasureErrorNo(self.error_no))
if isinstance(self.error_no, (MeasureErrorNo, int))
else str(self.error_no)
)
return (
f"{self.__class__.__name__}(costs={self.costs!r}, error_no={error_no_str}, "
f"all_cost={self.all_cost}, timestamp={self.timestamp!r})"
)
class MeasureErrorNo(enum.IntEnum):
"""Error type for MeasureResult"""
NO_ERROR = 0 # no error
INSTANTIATION_ERROR = 1 # actively detected error in instantiating a template with a config
COMPILE_HOST = 2 # error when compiling code on host (e.g. tvm.build)
COMPILE_DEVICE = 3 # error when compiling code on device (e.g. OpenCL JIT on the device)
RUNTIME_DEVICE = 4 # error when run program on device
WRONG_ANSWER = 5 # answer is wrong when compared to a golden output
BUILD_TIMEOUT = 6 # timeout during compilation
RUN_TIMEOUT = 7 # timeout during run
UNKNOWN_ERROR = 8 # unknown error
class Builder(object):
"""Builder that builds programs in tuning
Parameters
----------
timeout: float, optional
The timeout of a build task
n_parallel: int, optional
The number of tasks submitted in parallel
By default it will use all cpu cores
build_kwargs: dict, optional
Keyword args given to the build function.
"""
def __init__(self, timeout=10, n_parallel=None, build_kwargs=None):
self.timeout = timeout
self.n_parallel = n_parallel or multiprocessing.cpu_count()
self.user_build_kwargs = build_kwargs if build_kwargs is not None else {}
self.runner_build_kwargs = None
self.task = None
def set_task(self, task, build_kwargs=None):
"""
Initialize for a new tuning task
Parameters
----------
task: Task
The tuning task
build_kwargs: dict, optional
The additional kwargs for build function
"""
self.task = task
self.build_kwargs = dict(build_kwargs.items()) if build_kwargs is not None else {}
if any(k in self.build_kwargs for k in self.user_build_kwargs):
logging.warn(
"Overriding these runner-supplied kwargs with user-supplied:\n%s",
"\n".join(
f" * {k}: from {build_kwargs[k]!r} to {self.user_build_kwargs[k]!r}"
for k in sorted([k for k in build_kwargs if k in self.user_build_kwargs])
),
)
for k, v in self.user_build_kwargs.items():
self.build_kwargs[k] = v
def build(self, measure_inputs):
"""Build programs
Parameters
----------
measure_inputs: List of MeasureInput
The measure input
Returns
-------
build_results: List of BuildResult
The build result.
"""
raise NotImplementedError()
class Runner(object):
"""Runner that runs and measures the time cost of a generated program in tuning
Parameters
----------
timeout: float, optional
The timeout of a build task
n_parallel: int, optional
The number of tasks submitted in parallel
By default it will use all cpu cores
"""
def __init__(self, timeout=5, n_parallel=None):
self.timeout = timeout
self.n_parallel = n_parallel or multiprocessing.cpu_count()
self.task = None
def set_task(self, task):
"""
Initialize for a new tuning task
Parameters
----------
task: Task
The tuning task
"""
self.task = task
def get_build_kwargs(self):
"""
Get device specific build arguments (e.g. maximum shared memory size)
Returns
----------
kwargs: dict
The additional keyword arguments
"""
raise NotImplementedError()
def run(self, measure_inputs, build_results):
"""Run amd measure built programs
Parameters
----------
measure_inputs: List of MeasureInput
The raw measure input
build_results: List of BuildResults
The build results
Returns
-------
measure_results: List of MeasureResult
The final results of measurement
"""
raise NotImplementedError()
def measure_option(builder, runner):
"""
Set options for measure. To measure a config, we will build it and run it.
So we have to set options for these two steps.
They have their own options on timeout, parallel, etc.
Parameters
----------
builder: Builder
Specify how to build programs
runner: Runner
Specify how to run programs
Examples
--------
# example setting for using local devices
>>> measure_option = autotvm.measure_option(
>>> builder=autotvm.LocalBuilder(), # use all local cpu cores for compilation
>>> runner=autotvm.LocalRunner( # measure them sequentially
>>> number=10,
>>> timeout=5)
>>> )
# example setting for using remote devices
>>> measure_option = autotvm.measure_option(
>>> builder=autotvm.LocalBuilder(), # use all local cpu cores for compilation
>>> runner=autotvm.RPCRunner(
>>> 'rasp3b', 'locahost', 9190, # device key, host and port of the rpc tracker
>>> number=4,
>>> timeout=4) # timeout of a run on the device. RPC request waiting time is excluded.
>>>)
Note
----
To make measurement results accurate, you should pick the correct value for the argument
`number` and `repeat` in Runner(). Some devices need a certain minimum running time to
"warm up," such as GPUs that need time to reach a performance power state.
Using `min_repeat_ms` can dynamically adjusts `number`, so it is recommended.
The typical value for NVIDIA GPU is 150 ms.
"""
# pylint: disable=import-outside-toplevel
from .measure_methods import LocalBuilder, LocalRunner
if isinstance(builder, str):
if builder == "local":
builder = LocalBuilder()
else:
raise ValueError("Invalid builder: " + builder)
if isinstance(runner, str):
if runner == "local":
runner = LocalRunner()
else:
raise ValueError("Invalid runner: " + runner)
opt = {
"builder": builder,
"runner": runner,
}
return opt
def create_measure_batch(task, option):
"""Get a standard measure_batch function.
Parameters
----------
task: tvm.autotvm.task.Task
The tuning task
option: dict
The option for measuring generated code.
You should use the return value of function :any:`measure_option` for this argument.
Returns
-------
measure_batch: callable
a callback function to measure a batch of configs
"""
builder = option["builder"]
runner = option["runner"]
attach_objects = runner.set_task(task)
# feed device related information from runner to builder
# (e.g. max shared memory for validity checking)
build_kwargs = runner.get_build_kwargs()
builder.set_task(task, build_kwargs)
def measure_batch(measure_inputs):
build_results = builder.build(measure_inputs)
results = runner.run(measure_inputs, build_results)
return results
measure_batch.n_parallel = builder.n_parallel
measure_batch.attach_objects = attach_objects
return measure_batch
|
328767c339b12ea910bf952b9885dff3bcbb763d
|
698c8b4409db131dfb2a42468db6e5f532ff3eec
|
/cluster-trace-gpu-v2020/simulator/node.py
|
30b5c515fc04794b7e710c76f6aa8ed7ed185ba2
|
[
"CC-BY-4.0"
] |
permissive
|
alibaba/clusterdata
|
125373a990be95ddc6713ff463290f164bcaad38
|
7358bbaf40778d4bd0464a64a430812088b7b74e
|
refs/heads/master
| 2023-09-01T00:12:43.572121
| 2023-08-24T03:15:53
| 2023-08-24T03:15:53
| 102,428,537
| 1,347
| 421
| null | 2023-09-09T02:37:18
| 2017-09-05T03:16:34
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 7,997
|
py
|
node.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from utils import print_fn
'''
Class Node
'''
class Node(object):
def __init__(self, id, num_gpus=8, num_cpus=96, mem=720,
job_runn_list=None, gpu_type=0):
self.id = id
self.num_gpus = num_gpus * 100 # in %
self.idl_gpus = self.num_gpus # in %
self.svc_gpus = 0 # occupied by higher-priority services
self.job_gpus = 0 # sum([j['num_gpu'] for j in self.job_runn_list])
# num_gpus = svc_gpus + job_gpus + idl_gpus
# = svc_gpus + cur_gpus
self.gpu_type = gpu_type
self.num_cpus = num_cpus * 100 # in %
self.idl_cpus = self.num_cpus # in %
self.svc_cpus = 0
self.job_cpus = 0
self.mem = mem
self.idl_mem = mem
self.svc_mem = 0
self.job_mem = 0
self.network_in = 0 # bw, or traffic amount
self.network_out = 0
if job_runn_list is None:
self.job_runn_list = list()
else:
self.job_runn_list = list(job_runn_list)
print_fn(' Node[%3d]:(%3d GPUs,%4d CPUs) %s' %
(id, num_gpus, num_cpus, gpu_type))
@property
def util_rate(self):
cpus_util = 1 - self.idl_cpus / self.num_cpus
if self.num_gpus > 0:
gpus_util = 1 - self.idl_gpus / self.num_gpus
util_rate = round(100 * (gpus_util + cpus_util) / 2)
else:
util_rate = round(100 * cpus_util)
return util_rate
def __repr__(self):
self.update_idl_gpus()
self.update_idl_cpus()
return 'N[%3d]: [(j %3d,i %3d)/%3d GPUs, (j %4d,i %4d)/%4d CPUs -- %3d Util.] %s' % (
self.id, self.job_gpus, self.idl_gpus, self.num_gpus, self.job_cpus, self.idl_cpus, self.num_cpus,
self.util_rate, self.gpu_type)
def check_rsrc(self):
assert self.num_gpus == self.svc_gpus + self.idl_gpus + self.job_gpus
assert self.num_cpus == self.svc_cpus + self.idl_cpus + self.job_cpus
def update_idl_gpus(self):
self.idl_gpus = self.num_gpus - self.svc_gpus - self.job_gpus
def update_idl_cpus(self):
self.idl_cpus = self.num_cpus - self.svc_cpus - self.job_cpus
'''alloc/release job'''
def alloc_job(self, job):
if self.alloc_res(num_gpus=job['num_gpu'], num_cpus=job['num_cpu']):
self.job_runn_list.append(job)
self.job_gpus += job['num_gpu']
self.job_cpus += job['num_cpu']
return True
else:
return False
def release_job(self, job):
if self.release_res(num_gpus=job['num_gpu'], num_cpus=job['num_cpu']):
self.job_runn_list.remove(job)
self.job_gpus -= job['num_gpu']
self.job_cpus -= job['num_cpu']
return True
else:
return False
'''alloc/release srv'''
def set_svc_res_by_ratio(self, ratio=0):
self.svc_gpus = int(ratio * self.num_gpus)
self.svc_cpus = int(ratio * self.num_cpus)
self.update_idl_gpus()
self.update_idl_cpus()
'''alloc/release resource'''
def alloc_res(self, num_gpus=0, num_cpus=0):
# alloc job resource
gpu = self.alloc_gpus(num_gpus)
cpu = self.alloc_cpus(num_cpus)
if not cpu and not gpu:
return False
elif not cpu and gpu:
self.release_gpus(num_gpus)
return False
elif cpu and not gpu:
self.release_cpus(num_cpus)
return False
return True
def release_res(self, num_gpus, num_cpus):
# input is gpu and cpu
cpu = self.release_cpus(num_cpus)
gpu = self.release_gpus(num_gpus)
return cpu and gpu
'''alloc/release resource with best efforts'''
def alloc_gpu_best_effort(self, num_gpus=0):
"""return: num_gpus_left_to_alloc"""
assert num_gpus >= 0
if num_gpus <= self.idl_gpus:
self.svc_gpus += num_gpus
self.idl_gpus -= num_gpus
num_gpus = 0
else:
self.svc_gpus += self.idl_gpus
num_gpus -= self.idl_gpus
self.idl_gpus = 0
return num_gpus
def alloc_cpu_best_effort(self, num_cpus=0):
"""return: num_cpus_left_to_alloc"""
assert num_cpus >= 0
if num_cpus <= self.idl_cpus:
self.svc_cpus += num_cpus
self.idl_cpus -= num_cpus
num_cpus = 0
else:
self.svc_cpus += self.idl_cpus
num_cpus -= self.idl_cpus
self.idl_cpus = 0
return num_cpus
def release_gpu_best_effort(self, num_gpus=0):
"""return: num_gpus_left_to_release"""
assert num_gpus >= 0
if num_gpus <= self.svc_gpus:
self.idl_gpus += num_gpus
self.svc_gpus -= num_gpus
num_gpus = 0
else:
self.idl_gpus += self.svc_gpus
num_gpus -= self.svc_gpus
self.svc_gpus = 0
return num_gpus
def release_cpu_best_effort(self, num_cpus=0):
"""return: num_cpus_left_to_release"""
assert num_cpus >= 0
if num_cpus <= self.svc_cpus:
self.idl_cpus += num_cpus
self.svc_cpus -= num_cpus
num_cpus = 0
else:
self.idl_cpus += self.svc_cpus
num_cpus -= self.svc_cpus
self.svc_cpus = 0
return num_cpus
''' GPU '''
def get_idl_gpus(self):
return self.idl_gpus
def alloc_gpus(self, num_gpus=0):
'''
If enough free gpus, allocate gpus
Return: True, for success;
False, for failure
'''
if num_gpus > self.idl_gpus:
return False
else:
self.idl_gpus -= num_gpus
return True
def release_gpus(self, num_gpus=0):
'''
release using gpus back to free list
'''
if self.idl_gpus + num_gpus > self.num_gpus:
self.idl_gpus = self.num_gpus
return False
else:
self.idl_gpus += num_gpus
return True
''' CPU '''
def get_idl_cpus(self):
return self.idl_cpus
def alloc_cpus(self, num_cpus=0):
'''
If enough free cpus, allocate gpus
Return: True, for success;
False, for failure
'''
if num_cpus > self.idl_cpus:
return False
else:
self.idl_cpus -= num_cpus
return True
def release_cpus(self, num_cpus=0):
'''
release using cpus back to free list
'''
if self.idl_cpus + num_cpus > self.num_cpus:
self.idl_cpus = self.num_cpus
return False
else:
self.idl_cpus += num_cpus
return True
'''network'''
def add_network_load(self, in_load=0, out_load=0):
self.network_in += in_load
self.network_out += out_load
self.network_in = round(self.network_in, 1)
self.network_out = round(self.network_in, 1)
def release_network_load(self, in_load=0, out_load=0):
self.network_in -= in_load
self.network_out -= out_load
self.network_in = round(self.network_in, 1)
self.network_out = round(self.network_in, 1)
def set_network_load(self, in_load=0, out_load=0):
self.network_in = in_load
self.network_out = out_load
self.network_in = round(self.network_in, 1)
self.network_out = round(self.network_in, 1)
def init_node(self, num_gpus=0, num_cpus=0, mem=0):
if num_gpus != 0:
self.num_gpus = num_gpus
self.idl_gpus = num_gpus
if num_cpus != 0:
self.num_cpus = num_cpus
self.idl_cpus = num_cpus
if mem != 0:
self.mem = mem
self.idl_mem = mem
|
8a491a33d08622cc80325fa1dbe876071fd44653
|
c85ec637dd7202eccbab3623f0e12608f2c58c73
|
/redditdownloader/sources/pushshift_subreddit.py
|
7b50ebb95d74afe33f92f57a99278c39b9475885
|
[] |
no_license
|
shadowmoose/RedditDownloader
|
2d7b8d68d3be7cd63614c5019e2935e25d8548f8
|
ebcb791f78e5d761efcca28b5ebd5b7e1b61df85
|
refs/heads/master
| 2023-07-13T09:55:21.700858
| 2023-07-02T05:02:18
| 2023-07-02T05:02:18
| 93,103,288
| 1,134
| 120
| null | 2023-05-04T05:57:26
| 2017-06-01T22:03:41
|
Python
|
UTF-8
|
Python
| false
| false
| 2,428
|
py
|
pushshift_subreddit.py
|
from sources import source
from psaw import PushshiftAPI
from static.settings import Setting
from processing.wrappers.redditelement import RedditElement
import time
class PushShiftSubmissionSource(source.Source):
def __init__(self):
super().__init__(source_type='pushshift-submission-source', description="PushShift: The (possibly unlimited) submissions in one or more subreddits.")
def get_elements(self):
ps = PushshiftAPI()
for sub in self.data['subreddit'].split(','):
sub = sub.replace('/r/', '', 1).strip()
_params = {'subreddit': sub, 'sort_type': self.data['sort_by'], 'after': self.convert_offset()}
if self.data['limit']:
_params['limit'] = self.data['limit']
if 'desc' in self.data['sort_order'].lower():
_params['sort'] = 'desc'
else:
_params['sort'] = 'asc'
for post in ps.search_submissions(**_params):
p = RedditElement(post)
if self.check_filters(p):
yield p
def get_settings(self):
yield Setting('subreddit', '', etype='str', desc='Name of the desired subreddit(s), separated by commas:')
yield Setting('limit', 1000, etype='int', desc='How many would you like to download? (0 for no limit):')
yield Setting("time", 'All Time', desc='Select a time span to filter by:', etype="str", opts=[('All Time', 'All posts ever made'), ('Day', 'Posts with the last 24hrs'), ('Week', 'Posts within the last 7 days'), ('Month', "Posts within the last 31 days"), ('Year', 'Posts within the last 365 days')])
yield Setting("sort_by", 'score', desc="Sort results by:", etype="str", opts=[('score', 'Sort by highest score'), ('created_utc', 'The datetime the Submission was created')])
yield Setting("sort_order", 'Descending', desc="Sort order:", etype="str", opts=[('Descending', 'Descending order'), ('Ascending', "Ascending order")])
def get_config_summary(self):
lim = self.data['limit']
if lim > 0:
lim = 'the first %s' % lim
else:
lim = 'all'
return 'Downloading %s submissions from subreddit(s) "%s".' % (
lim, self.data['subreddit']
)
def convert_offset(self):
current_time = int(time.time())
off = self.data['time'].lower()
day = 24*60*60
if 'all' in off:
return 0
if off == 'day':
return current_time - day
if off == 'week':
return current_time - (day*7)
if off == 'month':
return current_time - (day*31)
if off == 'year':
return current_time - (day*365)
raise Exception("Unhandled time span!")
|
063579fec7b6ab5c9443ca24827b972d09591805
|
fc89bb82dbb31cd876247e3decb9315cdf491d3e
|
/demos/moderator_bot/tests/conftest.py
|
1b491f3a116021e85a9558e2bdc2cb7be94fdd9c
|
[
"Apache-2.0"
] |
permissive
|
aio-libs/aiohttp-demos
|
3c341f532fa41d17a804764c8c150a300cb4fd52
|
ea628d0307834645eb6eda032812fbfdcab9e1cc
|
refs/heads/master
| 2023-08-31T06:39:23.152144
| 2023-08-30T10:08:15
| 2023-08-30T10:08:15
| 108,527,536
| 728
| 313
|
NOASSERTION
| 2023-09-14T09:44:34
| 2017-10-27T09:35:41
|
Makefile
|
UTF-8
|
Python
| false
| false
| 388
|
py
|
conftest.py
|
import pytest
from moderator_bot.server import init_application
from moderator_bot.settings import PROJECT_ROOT
from moderator_bot.utils import load_config
@pytest.fixture
def config():
return load_config(PROJECT_ROOT / "configs" / "base.yml")
@pytest.fixture
async def client(aiohttp_client, config):
app = await init_application(config)
return await aiohttp_client(app)
|
3de0170fb027eb3ded772eb5584d2ae8573630ce
|
1e92cc7daabe240b374d73da462878e80814171b
|
/manila/share/drivers/quobyte/quobyte.py
|
e2c2ec071a9b3327d61be3df80d583ec3bdecb3f
|
[
"Apache-2.0"
] |
permissive
|
openstack/manila
|
e211281dd16128ac5685cd7b1a13a09d9e6456e1
|
a93a844398a11a8a85f204782fb9456f7caccdbe
|
refs/heads/master
| 2023-08-19T04:23:24.084637
| 2023-08-17T14:55:58
| 2023-08-17T14:55:58
| 24,245,238
| 178
| 141
|
Apache-2.0
| 2023-08-03T10:43:19
| 2014-09-19T20:57:05
|
Python
|
UTF-8
|
Python
| false
| false
| 17,792
|
py
|
quobyte.py
|
# Copyright (c) 2015 Quobyte Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Quobyte driver.
Manila shares are directly mapped to Quobyte volumes. The access to the
shares is provided by the Quobyte NFS proxy (a Ganesha NFS server).
"""
import math
from oslo_config import cfg
from oslo_log import log
from oslo_utils import units
from manila.common import constants
from manila import exception
from manila.i18n import _
from manila.share import driver
from manila.share.drivers.quobyte import jsonrpc
LOG = log.getLogger(__name__)
quobyte_manila_share_opts = [
cfg.StrOpt('quobyte_api_url',
help='URL of the Quobyte API server (http or https)'),
cfg.StrOpt('quobyte_api_ca',
help='The X.509 CA file to verify the server cert.'),
cfg.BoolOpt('quobyte_delete_shares',
default=False,
help='Actually deletes shares (vs. unexport)'),
cfg.StrOpt('quobyte_api_username',
default='admin',
help='Username for Quobyte API server.'),
cfg.StrOpt('quobyte_api_password',
default='quobyte',
secret=True,
help='Password for Quobyte API server'),
cfg.StrOpt('quobyte_volume_configuration',
default='BASE',
help='Name of volume configuration used for new shares.'),
cfg.StrOpt('quobyte_default_volume_user',
default='root',
help='Default owning user for new volumes.'),
cfg.StrOpt('quobyte_default_volume_group',
default='root',
help='Default owning group for new volumes.'),
cfg.StrOpt('quobyte_export_path',
default='/quobyte',
help='Export path for shares of this bacckend. This needs '
'to match the quobyte-nfs services "Pseudo" option.'),
]
CONF = cfg.CONF
CONF.register_opts(quobyte_manila_share_opts)
class QuobyteShareDriver(driver.ExecuteMixin, driver.ShareDriver,):
"""Map share commands to Quobyte volumes.
Version history:
1.0 - Initial driver.
1.0.1 - Adds ensure_share() implementation.
1.1 - Adds extend_share() and shrink_share() implementation.
1.2 - Adds update_access() implementation and related methods
1.2.1 - Improved capacity calculation
1.2.2 - Minor optimizations
1.2.3 - Updated RPC layer for improved stability
1.2.4 - Fixed handling updated QB API error codes
1.2.5 - Fixed two quota handling bugs
1.2.6 - Fixed volume resize and jsonrpc code style bugs
1.2.7 - Add quobyte_export_path option
"""
DRIVER_VERSION = '1.2.7'
def __init__(self, *args, **kwargs):
super(QuobyteShareDriver, self).__init__(False, *args, **kwargs)
self.configuration.append_config_values(quobyte_manila_share_opts)
self.backend_name = (self.configuration.safe_get('share_backend_name')
or CONF.share_backend_name or 'Quobyte')
def _fetch_existing_access(self, context, share):
volume_uuid = self._resolve_volume_name(share['name'],
share['project_id'])
result = self.rpc.call('getConfiguration', {})
if result is None:
raise exception.QBException(
"Could not retrieve Quobyte configuration data!")
tenant_configs = result['tenant_configuration']
qb_access_list = []
for tc in tenant_configs:
for va in tc['volume_access']:
if va['volume_uuid'] == volume_uuid:
a_level = constants.ACCESS_LEVEL_RW
if va['read_only']:
a_level = constants.ACCESS_LEVEL_RO
qb_access_list.append({
'access_to': va['restrict_to_network'],
'access_level': a_level,
'access_type': 'ip'
})
return qb_access_list
def do_setup(self, context):
"""Prepares the backend."""
self.rpc = jsonrpc.JsonRpc(
url=self.configuration.quobyte_api_url,
ca_file=self.configuration.quobyte_api_ca,
user_credentials=(
self.configuration.quobyte_api_username,
self.configuration.quobyte_api_password))
try:
self.rpc.call('getInformation', {})
except Exception as exc:
LOG.error("Could not connect to API: %s", exc)
raise exception.QBException(
_('Could not connect to API: %s') % exc)
def _update_share_stats(self):
total_gb, free_gb = self._get_capacities()
data = dict(
storage_protocol='NFS',
vendor_name='Quobyte',
share_backend_name=self.backend_name,
driver_version=self.DRIVER_VERSION,
total_capacity_gb=total_gb,
free_capacity_gb=free_gb,
reserved_percentage=self.configuration.reserved_share_percentage,
reserved_snapshot_percentage=(
self.configuration.reserved_share_from_snapshot_percentage
or self.configuration.reserved_share_percentage),
reserved_share_extend_percentage=(
self.configuration.reserved_share_extend_percentage
or self.configuration.reserved_share_percentage))
super(QuobyteShareDriver, self)._update_share_stats(data)
def _get_capacities(self):
result = self.rpc.call('getSystemStatistics', {})
total = float(result['total_physical_capacity'])
used = float(result['total_physical_usage'])
LOG.info('Read capacity of %(cap)s bytes and '
'usage of %(use)s bytes from backend. ',
{'cap': total, 'use': used})
free = total - used
if free < 0:
free = 0 # no space available
free_replicated = free / self._get_qb_replication_factor()
# floor numbers to nine digits (bytes)
total = math.floor((total / units.Gi) * units.G) / units.G
free = math.floor((free_replicated / units.Gi) * units.G) / units.G
return total, free
def _get_qb_replication_factor(self):
result = self.rpc.call('getEffectiveVolumeConfiguration',
{'configuration_name': self.
configuration.quobyte_volume_configuration})
return int(result['configuration']['volume_metadata_configuration']
['replication_factor'])
def check_for_setup_error(self):
pass
def get_network_allocations_number(self):
return 0
def _get_project_name(self, context, project_id):
"""Retrieve the project name.
TODO (kaisers): retrieve the project name in order
to store and use in the backend for better usability.
"""
return project_id
def _resize_share(self, share, new_size):
newsize_bytes = new_size * units.Gi
self.rpc.call('setQuota', {"quotas": [
{"consumer":
[{"type": "VOLUME",
"identifier": self._resolve_volume_name(share["name"],
share['project_id']),
"tenant_id": share["project_id"]}],
"limits": [{"type": "LOGICAL_DISK_SPACE",
"value": newsize_bytes}]}
]})
def _resolve_volume_name(self, volume_name, tenant_domain):
"""Resolve a volume name to the global volume uuid."""
result = self.rpc.call('resolveVolumeName', dict(
volume_name=volume_name,
tenant_domain=tenant_domain), [jsonrpc.ERROR_ENOENT,
jsonrpc.ERROR_ENTITY_NOT_FOUND])
if result:
return result['volume_uuid']
return None # not found
def _subtract_access_lists(self, list_a, list_b):
"""Returns a list of elements in list_a that are not in list_b
:param list_a: Base list of access rules
:param list_b: List of access rules not to be returned
:return: List of elements of list_a not present in
list_b
"""
sub_tuples_list = [{"to": s.get('access_to'),
"type": s.get('access_type'),
"level": s.get('access_level')}
for s in list_b]
return [r for r in list_a if (
{"to": r.get("access_to"),
"type": r.get("access_type"),
"level": r.get("access_level")} not in sub_tuples_list)]
def create_share(self, context, share, share_server=None):
"""Create or export a volume that is usable as a Manila share."""
if share['share_proto'] != 'NFS':
raise exception.QBException(
_('Quobyte driver only supports NFS shares'))
volume_uuid = self._resolve_volume_name(share['name'],
share['project_id'])
if not volume_uuid:
# create tenant, expect ERROR_GARBAGE_ARGS if it already exists
self.rpc.call('setTenant',
dict(tenant=dict(tenant_id=share['project_id'])),
expected_errors=[jsonrpc.ERROR_GARBAGE_ARGS])
result = self.rpc.call('createVolume', dict(
name=share['name'],
tenant_domain=share['project_id'],
root_user_id=self.configuration.quobyte_default_volume_user,
root_group_id=self.configuration.quobyte_default_volume_group,
configuration_name=(self.configuration.
quobyte_volume_configuration)))
volume_uuid = result['volume_uuid']
result = self.rpc.call('exportVolume', dict(
volume_uuid=volume_uuid,
protocol='NFS'))
self._resize_share(share, share['size'])
return self._build_share_export_string(result)
def delete_share(self, context, share, share_server=None):
"""Delete the corresponding Quobyte volume."""
volume_uuid = self._resolve_volume_name(share['name'],
share['project_id'])
if not volume_uuid:
LOG.warning("No volume found for "
"share %(project_id)s/%(name)s",
{"project_id": share['project_id'],
"name": share['name']})
return
if self.configuration.quobyte_delete_shares:
self.rpc.call('deleteVolume', {'volume_uuid': volume_uuid})
else:
self.rpc.call('exportVolume', {"volume_uuid": volume_uuid,
"remove_export": True,
})
def ensure_share(self, context, share, share_server=None):
"""Invoked to ensure that share is exported.
:param context: The `context.RequestContext` object for the request
:param share: Share instance that will be checked.
:param share_server: Data structure with share server information.
Not used by this driver.
:returns: IP:<nfs_export_path> of share
:raises:
:ShareResourceNotFound: If the share instance cannot be found in
the backend
"""
volume_uuid = self._resolve_volume_name(share['name'],
share['project_id'])
LOG.debug("Ensuring Quobyte share %s", share['name'])
if not volume_uuid:
raise (exception.ShareResourceNotFound(
share_id=share['id']))
result = self.rpc.call('exportVolume', dict(
volume_uuid=volume_uuid,
protocol='NFS'))
return self._build_share_export_string(result)
def _allow_access(self, context, share, access, share_server=None):
"""Allow access to a share."""
if access['access_type'] != 'ip':
raise exception.InvalidShareAccess(
_('Quobyte driver only supports ip access control'))
volume_uuid = self._resolve_volume_name(share['name'],
share['project_id'])
ro = access['access_level'] == (constants.ACCESS_LEVEL_RO)
call_params = {
"volume_uuid": volume_uuid,
"read_only": ro,
"add_allow_ip": access['access_to']}
self.rpc.call('exportVolume', call_params)
def _build_share_export_string(self, rpc_result):
return '%(nfs_server_ip)s:%(qb_exp_path)s%(nfs_export_path)s' % {
"nfs_server_ip": rpc_result["nfs_server_ip"],
"qb_exp_path": self.configuration.quobyte_export_path,
"nfs_export_path": rpc_result["nfs_export_path"]}
def _deny_access(self, context, share, access, share_server=None):
"""Remove white-list ip from a share."""
if access['access_type'] != 'ip':
LOG.debug('Quobyte driver only supports ip access control. '
'Ignoring deny access call for %s , %s',
share['name'],
self._get_project_name(context, share['project_id']))
return
volume_uuid = self._resolve_volume_name(share['name'],
share['project_id'])
call_params = {
"volume_uuid": volume_uuid,
"remove_allow_ip": access['access_to']}
self.rpc.call('exportVolume', call_params)
def extend_share(self, ext_share, ext_size, share_server=None):
"""Uses _resize_share to extend a share.
:param ext_share: Share model.
:param ext_size: New size of share (new_size > share['size']).
:param share_server: Currently not used.
"""
self._resize_share(share=ext_share, new_size=ext_size)
def shrink_share(self, shrink_share, shrink_size, share_server=None):
"""Uses _resize_share to shrink a share.
Quobyte uses soft quotas. If a shares current size is bigger than
the new shrunken size no data is lost. Data can be continuously read
from the share but new writes receive out of disk space replies.
:param shrink_share: Share model.
:param shrink_size: New size of share (new_size < share['size']).
:param share_server: Currently not used.
"""
self._resize_share(share=shrink_share, new_size=shrink_size)
def update_access(self, context, share, access_rules, add_rules,
delete_rules, share_server=None):
"""Update access rules for given share.
Two different cases are supported in here:
1. Recovery after error - 'access_rules' contains all access_rules,
'add_rules' and 'delete_rules' are empty. Driver should apply all
access rules for given share.
2. Adding/Deleting of several access rules - 'access_rules' contains
all access_rules, 'add_rules' and 'delete_rules' contain rules which
should be added/deleted. Driver can ignore rules in 'access_rules' and
apply only rules from 'add_rules' and 'delete_rules'.
:param context: Current context
:param share: Share model with share data.
:param access_rules: All access rules for given share
:param add_rules: Empty List or List of access rules which should be
added. access_rules already contains these rules.
:param delete_rules: Empty List or List of access rules which should be
removed. access_rules doesn't contain these rules.
:param share_server: None or Share server model
:raises If all of the *_rules params are None the method raises an
InvalidShareAccess exception
"""
if (add_rules or delete_rules):
# Handling access rule update
for d_rule in delete_rules:
self._deny_access(context, share, d_rule)
for a_rule in add_rules:
self._allow_access(context, share, a_rule)
else:
if not access_rules:
LOG.warning("No access rules provided in update_access.")
else:
# Handling access rule recovery
existing_rules = self._fetch_existing_access(context, share)
missing_rules = self._subtract_access_lists(access_rules,
existing_rules)
for a_rule in missing_rules:
LOG.debug("Adding rule %s in recovery.",
str(a_rule))
self._allow_access(context, share, a_rule)
superfluous_rules = self._subtract_access_lists(existing_rules,
access_rules)
for d_rule in superfluous_rules:
LOG.debug("Removing rule %s in recovery.",
str(d_rule))
self._deny_access(context, share, d_rule)
|
07926b3c24fa79f7a8b648f9e43f2c7febfaf810
|
dcbef06d5a00f07756339b9e62c684dec2fee425
|
/tests/basics/GeneratorExpressionsTest.py
|
0c2c661acbd31b05e312c50b4c54d593cf6e9d81
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
Nuitka/Nuitka
|
f9543d8d95bfa0b81d4e60af0dfad99fb72893a4
|
d87faf2f7e1d6ed9bfe4cf8c1d648f34307e33f2
|
refs/heads/develop
| 2023-08-28T14:00:32.861328
| 2023-08-27T09:16:45
| 2023-08-27T09:16:45
| 9,626,741
| 8,573
| 599
|
Apache-2.0
| 2023-09-13T02:49:41
| 2013-04-23T15:40:33
|
Python
|
UTF-8
|
Python
| false
| false
| 5,809
|
py
|
GeneratorExpressionsTest.py
|
# Copyright 2023, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
""" Generator expression tests
"""
from __future__ import print_function
import inspect
print("Generator expression that demonstrates the timing:")
def iteratorCreationTiming():
def getIterable(x):
print("Getting iterable", x)
return Iterable(x)
class Iterable:
def __init__(self, x):
self.x = x # pylint: disable=invalid-name
self.values = list(range(x))
self.count = 0
def __iter__(self):
print("Giving iterator now", self.x)
return self
def __next__(self):
print("Next of", self.x, "is", self.count)
if len(self.values) > self.count:
self.count += 1
return self.values[self.count - 1]
else:
print("Raising StopIteration for", self.x)
raise StopIteration
# Python2/3 compatibility.
next = __next__
def __del__(self):
print("Deleting", self.x)
gen = ((y, z) for y in getIterable(3) for z in getIterable(2))
print("Using generator", gen)
next(gen)
res = tuple(gen)
print(res)
print("*" * 20)
try:
next(gen)
except StopIteration:
print("Usage past end gave StopIteration exception as expected.")
try:
print("Generator state then is", inspect.getgeneratorstate(gen))
except AttributeError:
pass
print("Its frame is now", gen.gi_frame)
print("Early aborting generator:")
gen2 = ((y, z) for y in getIterable(3) for z in getIterable(2))
del gen2
iteratorCreationTiming()
print("Generator expressions that demonstrate the use of conditions:")
print(tuple(x for x in range(8) if x % 2 == 1))
print(tuple(x for x in range(8) if x % 2 == 1 for z in range(8) if z == x))
print(tuple(x for (x, y) in zip(list(range(2)), list(range(4)))))
print("Directory of generator expressions:")
for_dir = (x for x in [1])
gen_dir = dir(for_dir)
print(sorted(g for g in gen_dir))
def genexprSend():
x = (x for x in range(9))
print("Sending too early:")
try:
x.send(3)
except TypeError as e:
print("Gave expected TypeError with text:", e)
try:
z = next(x)
except StopIteration as e:
print("Gave expected (3.10.0/1 only) StopIteration with text:", repr(e))
else:
print("Next return value (pre 3.10)", z)
try:
y = x.send(3)
except StopIteration as e:
print("Gave expected (3.10.0/1 only) StopIteration with text:", repr(e))
else:
print("Send return value", y)
try:
print("And then next gave", next(x))
except StopIteration as e:
print("Gave expected (3.10.0/1 only) StopIteration with text:", repr(e))
print("Throwing an exception to it.")
try:
x.throw(2)
assert False
except TypeError as e:
print("Gave expected TypeError:", e)
print("Throwing an exception to it.")
try:
x.throw(ValueError(2))
except ValueError as e:
print("Gave expected ValueError:", e)
try:
next(x)
print("Next worked even after thrown error")
except StopIteration as e:
print("Gave expected stop iteration after throwing exception in it:", e)
print("Throwing another exception from it.")
try:
x.throw(ValueError(5))
except ValueError as e:
print("Gave expected ValueError with text:", e)
print("Generator expressions have send too:")
genexprSend()
def genexprClose():
x = (x for x in range(9))
print("Immediate close:")
x.close()
print("Closed once")
x.close()
print("Closed again without any trouble")
genexprClose()
def genexprThrown():
def checked(z):
if z == 3:
raise ValueError
return z
x = (checked(x) for x in range(9))
try:
for count, value in enumerate(x):
print(count, value)
except ValueError:
print(count + 1, ValueError)
try:
next(x)
print(
"Allowed to do next() after raised exception from the generator expression"
)
except StopIteration:
print("Exception in generator, disallowed next() afterwards.")
genexprThrown()
def nestedExpressions():
a = [x for x in range(10)]
b = (x for x in (y for y in a))
print("nested generator expression", list(b))
nestedExpressions()
def lambdaGenerators():
a = 1
x = lambda: (yield a)
print("Simple lambda generator", x, x(), list(x()))
y = lambda: ((yield 1), (yield 2))
print("Complex lambda generator", y, y(), list(y()))
lambdaGenerators()
def functionGenerators():
# Like lambdaGenerators, to show how functions behave differently if at all.
a = 1
def x():
yield a
print("Simple function generator", x, x(), list(x()))
def y():
yield ((yield 1), (yield 2))
print("Complex function generator", y, y(), list(y()))
functionGenerators()
|
7f6c387d2a3e0a394b47427ad6524f5479806a94
|
184b40438287d124117dcd48cf9abdab71e116c7
|
/src/cosmic_ray/ast/ast_query.py
|
348b443baaad50122d60cc6b11a38ca8c23051fe
|
[
"MIT"
] |
permissive
|
sixty-north/cosmic-ray
|
45bea97513eb75d00c514e0df2c5c3d156268f0f
|
aa63d36ef84659d941c22da9d4d39ae0408d488e
|
refs/heads/master
| 2023-08-26T07:57:57.939516
| 2023-03-14T13:49:49
| 2023-03-14T13:49:49
| 34,157,278
| 569
| 77
|
MIT
| 2023-01-02T07:58:54
| 2015-04-18T07:44:21
|
Python
|
UTF-8
|
Python
| false
| false
| 3,118
|
py
|
ast_query.py
|
"Tools for querying ASTs."
class ASTQuery:
"""
Allowing to navigate into any object and test attribute of any object:
Examples:
>>> ASTQuery(node).parent.match(Node, type='node').ok
Test if node.parent isinstance of Node and node.parent.type == 'node'
At each step (each '.' (dot)) you receive an ObjTest object, then
Navigation:
You can call any properties or functions of the base object
>>> ASTQuery(node).parent.children[2].get_next_sibling()
Test:
>>> ASTQuery(node).match(attr='value').match(Class)
All in once:
>>> ASTQuery(node).match(Class, attr='value')
Conditional navigation:
>>> ASTQuery(node).IF.match(attr='intermediate').parent.FI
Final result:
>>> ASTQuery(node).ok
>>> bool(ASTQuery(node))
"""
def __init__(self, obj):
self.obj = obj
def _clone(self, obj) -> "ASTQuery":
"Clone this query."
return type(self)(obj)
def match(self, cls=None, **kwargs) -> "ASTQuery":
"Check if node matches a class."
obj = self.obj
if obj is None:
return self
if cls is None or isinstance(obj, cls):
for k, v in kwargs.items():
op = None
k__op = k.split("__")
if len(k__op) == 2:
k, op = k__op
node_value = getattr(obj, k)
if op is None:
if node_value != v:
break
elif op == "in":
if node_value not in v:
break
else:
raise ValueError("Can't handle operator {}".format(op))
else:
# All is true, continue recursion
return self
# A test fails
return self._clone(None)
@property
def ok(self):
"Is the query ok."
return bool(self.obj)
def __bool__(self):
return self.ok
def __getattr__(self, item) -> "ASTQuery":
obj = self.obj
if obj is None:
return self
return self._clone(getattr(obj, item))
@property
def IF(self):
"Conditional navigation."
return ASTQueryOptional(self.obj, obj_test=self)
def __call__(self, *args, **kwargs) -> "ASTQuery":
if self.obj is None:
return self
return self._clone(self.obj(*args, **kwargs))
def __getitem__(self, item) -> "ASTQuery":
if self.obj is None:
return self
return self._clone(self.obj[item])
class ASTQueryOptional(ASTQuery):
"Manages conditional navigation."
def __init__(self, obj, obj_test=None):
super().__init__(obj)
self._initial = obj_test
def _clone(self, obj):
o = super()._clone(obj)
o._initial = self._initial # pylint: disable=protected-access
return o
@property
def FI(self):
"End of conditional navigation."
if self:
return self._initial._clone(self.obj) # pylint: disable=protected-access
return self._initial
|
bc5ec1f75e278ca2b40ce23601c4e724d485cb71
|
6bf3efa384abc11398ab9c6cc902c6415bf7e478
|
/pyannotate_tools/fixes/tests/test_annotate_py3.py
|
e2c3f026496b8eb3a3568ad8d3bce8a907c400e2
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
dropbox/pyannotate
|
d9ab4919672e69853c6aa47f6b8d4ba85696de98
|
a7a46f394f0ba91a1b5fbf657e2393af542969ae
|
refs/heads/master
| 2022-08-14T03:55:19.082430
| 2021-10-12T20:53:49
| 2021-10-12T20:53:49
| 110,597,280
| 1,482
| 73
|
Apache-2.0
| 2023-02-01T22:35:54
| 2017-11-13T20:18:08
|
Python
|
UTF-8
|
Python
| false
| false
| 15,812
|
py
|
test_annotate_py3.py
|
# flake8: noqa
# Our flake extension misfires on type comments in strings below.
from lib2to3.tests.test_fixers import FixerTestCase
import unittest
# deadcode: fix_annotate is used as part of the fixer_pkg for this test
from pyannotate_tools.fixes import fix_annotate
class TestFixAnnotate3(FixerTestCase):
def setUp(self):
super(TestFixAnnotate3, self).setUp(
fix_list=["annotate"],
fixer_pkg="pyannotate_tools",
options={'annotation_style' : 'py3'}
)
def test_no_arg_1(self) :
a = """\
def nop():
return 42
"""
b = """\
from typing import Any
def nop() -> Any:
return 42
"""
self.check(a, b)
def test_no_arg_2(self) :
a = """\
def nop(): return 42
"""
b = """\
from typing import Any
def nop() -> Any: return 42
"""
self.check(a, b)
def test_no_arg_3(self) :
a = """\
def nop(
):
return 42
"""
b = """\
from typing import Any
def nop(
) -> Any:
return 42
"""
self.check(a, b)
def test_no_arg_4(self) :
a = """\
def nop(
) \
:
return 42
"""
b = """\
from typing import Any
def nop(
) -> Any \
:
return 42
"""
self.check(a, b)
def test_no_arg_5(self) :
a = """\
def nop( # blah
): # blah
return 42 # blah
"""
b = """\
from typing import Any
def nop( # blah
) -> Any: # blah
return 42 # blah
"""
self.check(a, b)
def test_no_arg_6(self) :
a = """\
def nop( # blah
) \
: # blah
return 42 # blah
"""
b = """\
from typing import Any
def nop( # blah
) -> Any \
: # blah
return 42 # blah
"""
self.check(a, b)
def test_one_arg_1(self):
a = """\
def incr(arg):
return arg+1
"""
b = """\
from typing import Any
def incr(arg: Any) -> Any:
return arg+1
"""
self.check(a, b)
def test_one_arg_2(self):
a = """\
def incr(arg=0):
return arg+1
"""
b = """\
from typing import Any
def incr(arg: int = 0) -> Any:
return arg+1
"""
self.check(a, b)
def test_one_arg_3(self):
a = """\
def incr( arg=0 ):
return arg+1
"""
b = """\
from typing import Any
def incr( arg: int = 0 ) -> Any:
return arg+1
"""
self.check(a, b)
def test_one_arg_4(self):
a = """\
def incr( arg = 0 ):
return arg+1
"""
b = """\
from typing import Any
def incr( arg: int = 0 ) -> Any:
return arg+1
"""
self.check(a, b)
def test_two_args_1(self):
a = """\
def add(arg1, arg2):
return arg1+arg2
"""
b = """\
from typing import Any
def add(arg1: Any, arg2: Any) -> Any:
return arg1+arg2
"""
self.check(a, b)
def test_two_args_2(self):
a = """\
def add(arg1=0, arg2=0.1):
return arg1+arg2
"""
b = """\
from typing import Any
def add(arg1: int = 0, arg2: float = 0.1) -> Any:
return arg1+arg2
"""
self.check(a, b)
def test_two_args_3(self):
a = """\
def add(arg1, arg2=0.1):
return arg1+arg2
"""
b = """\
from typing import Any
def add(arg1: Any, arg2: float = 0.1) -> Any:
return arg1+arg2
"""
def test_two_args_4(self):
a = """\
def add(arg1, arg2 = 0.1):
return arg1+arg2
"""
b = """\
from typing import Any
def add(arg1: Any, arg2: float = 0.1) -> Any:
return arg1+arg2
"""
self.check(a, b)
self.check(a, b)
def test_defaults_1(self):
a = """\
def foo(iarg=0, farg=0.0, sarg='', uarg=u'', barg=False):
return 42
"""
b = """\
from typing import Any
def foo(iarg: int = 0, farg: float = 0.0, sarg: str = '', uarg: unicode = u'', barg: bool = False) -> Any:
return 42
"""
self.check(a, b)
def test_defaults_2(self):
a = """\
def foo(iarg=0, farg=0.0, sarg='', uarg=u'', barg=False, targ=(1,2,3)):
return 42
"""
b = """\
from typing import Any
def foo(iarg: int = 0, farg: float = 0.0, sarg: str = '', uarg: unicode = u'', barg: bool = False, targ: Any = (1,2,3)) -> Any:
return 42
"""
self.check(a, b)
def test_defaults_3(self):
a = """\
def foo(iarg=0, farg, sarg='', uarg, barg=False, targ=(1,2,3)):
return 42
"""
b = """\
from typing import Any
def foo(iarg: int = 0, farg: Any, sarg: str = '', uarg: Any, barg: bool = False, targ: Any = (1,2,3)) -> Any:
return 42
"""
self.check(a, b)
def test_staticmethod(self):
a = """\
class C:
@staticmethod
def incr(self):
return 42
"""
b = """\
from typing import Any
class C:
@staticmethod
def incr(self: Any) -> Any:
return 42
"""
self.check(a, b)
def test_classmethod(self):
a = """\
class C:
@classmethod
def incr(cls, arg):
return 42
"""
b = """\
from typing import Any
class C:
@classmethod
def incr(cls, arg: Any) -> Any:
return 42
"""
self.check(a, b)
def test_instancemethod(self):
a = """\
class C:
def incr(self, arg):
return 42
"""
b = """\
from typing import Any
class C:
def incr(self, arg: Any) -> Any:
return 42
"""
self.check(a, b)
def test_fake_self(self):
a = """\
def incr(self, arg):
return 42
"""
b = """\
from typing import Any
def incr(self: Any, arg: Any) -> Any:
return 42
"""
self.check(a, b)
def test_nested_fake_self(self):
a = """\
class C:
def outer(self):
def inner(self, arg):
return 42
"""
b = """\
from typing import Any
class C:
def outer(self) -> None:
def inner(self: Any, arg: Any) -> Any:
return 42
"""
self.check(a, b)
def test_multiple_decorators(self):
a = """\
class C:
@contextmanager
@classmethod
@wrapped('func')
def incr(cls, arg):
return 42
"""
b = """\
from typing import Any
class C:
@contextmanager
@classmethod
@wrapped('func')
def incr(cls, arg: Any) -> Any:
return 42
"""
self.check(a, b)
def test_stars_1(self):
a = """\
def stuff(*a):
return 4, 2
"""
b = """\
from typing import Any
def stuff(*a: Any) -> Any:
return 4, 2
"""
self.check(a, b)
def test_stars_2(self):
a = """\
def stuff(a, *b):
return 4, 2
"""
b = """\
from typing import Any
def stuff(a: Any, *b: Any) -> Any:
return 4, 2
"""
self.check(a, b)
def test_keywords_1(self):
a = """\
def stuff(**kw):
return 4, 2
"""
b = """\
from typing import Any
def stuff(**kw: Any) -> Any:
return 4, 2
"""
self.check(a, b)
def test_keywords_2(self):
a = """\
def stuff(a, **kw):
return 4, 2
"""
b = """\
from typing import Any
def stuff(a: Any, **kw: Any) -> Any:
return 4, 2
"""
self.check(a, b)
def test_keywords_3(self):
a = """\
def stuff(a, *b, **kw):
return 4, 2
"""
b = """\
from typing import Any
def stuff(a: Any, *b: Any, **kw: Any) -> Any:
return 4, 2
"""
self.check(a, b)
def test_keywords_4(self):
a = """\
def stuff(*b, **kw):
return 4, 2
"""
b = """\
from typing import Any
def stuff(*b: Any, **kw: Any) -> Any:
return 4, 2
"""
self.check(a, b)
def test_no_return_expr(self):
a = """\
def proc1(arg):
return
def proc2(arg):
pass
"""
b = """\
from typing import Any
def proc1(arg: Any) -> None:
return
def proc2(arg: Any) -> None:
pass
"""
self.check(a, b)
def test_nested_return_expr(self):
# The 'return expr' in inner() shouldn't affect the return type of outer().
a = """\
def outer(arg):
def inner():
return 42
return
"""
b = """\
from typing import Any
def outer(arg: Any) -> None:
def inner() -> Any:
return 42
return
"""
self.check(a, b)
def test_nested_class_return_expr(self):
# The 'return expr' in class Inner shouldn't affect the return type of outer().
a = """\
def outer(arg):
class Inner:
return 42
return
"""
b = """\
from typing import Any
def outer(arg: Any) -> None:
class Inner:
return 42
return
"""
self.check(a, b)
def test_add_import(self):
a = """\
import typing
from typing import Callable
def incr(arg):
return 42
"""
b = """\
import typing
from typing import Callable
from typing import Any
def incr(arg: Any) -> Any:
return 42
"""
self.check(a, b)
def test_dont_add_import(self):
a = """\
def nop(arg=0):
return
"""
b = """\
def nop(arg: int = 0) -> None:
return
"""
self.check(a, b)
def test_long_form(self):
self.maxDiff = None
a = """\
def nop(arg0, arg1, arg2, arg3, arg4,
arg5, arg6, arg7, arg8=0, arg9='',
*args, **kwds):
return
"""
b = """\
from typing import Any
def nop(arg0: Any, arg1: Any, arg2: Any, arg3: Any, arg4: Any,
arg5: Any, arg6: Any, arg7: Any, arg8: int = 0, arg9: str = '',
*args: Any, **kwds: Any) -> None:
return
"""
self.check(a, b)
def test_long_form_trailing_comma(self):
self.maxDiff = None
a = """\
def nop(arg0, arg1, arg2, arg3, arg4, arg5, arg6,
arg7=None, arg8=0, arg9='', arg10=False,):
return
"""
b = """\
from typing import Any
def nop(arg0: Any, arg1: Any, arg2: Any, arg3: Any, arg4: Any, arg5: Any, arg6: Any,
arg7: Any = None, arg8: int = 0, arg9: str = '', arg10: bool = False,) -> None:
return
"""
self.check(a, b)
def test_one_liner(self):
a = """\
class C:
def nop(self, a): a = a; return a
# Something
# More
pass
"""
b = """\
from typing import Any
class C:
def nop(self, a: Any) -> Any: a = a; return a
# Something
# More
pass
"""
self.check(a, b)
def test_idempotency_long_1arg(self):
a = """\
def nop(a: int
):
pass
"""
self.unchanged(a)
def test_idempotency_long_1arg_comma(self):
a = """\
def nop(a: int,
):
pass
"""
self.unchanged(a)
def test_idempotency_long_2args_first(self):
a = """\
def nop(a: int,
b):
pass
"""
self.unchanged(a)
def test_idempotency_long_2args_last(self):
a = """\
def nop(a,
b: int
):
pass
"""
self.unchanged(a)
def test_idempotency_long_varargs(self):
a = """\
def nop(*a: int
):
pass
"""
self.unchanged(a)
def test_idempotency_long_kwargs(self):
a = """\
def nop(**a: int
):
pass
"""
self.unchanged(a)
def test_idempotency_arg0_ret_value(self):
a = """\
def nop() -> int:
pass
"""
self.unchanged(a)
def test_idempotency_arg1_ret_value(self):
a = """\
def nop(a) -> int:
pass
"""
self.unchanged(a)
def test_idempotency_arg1_default_1(self):
a = """\
def nop(a: int=0):
pass
"""
self.unchanged(a)
def test_idempotency_arg1_default_2(self):
a = """\
def nop(a: List[int]=[]):
pass
"""
self.unchanged(a)
def test_idempotency_arg1_default_3(self):
a = """\
def nop(a: List[int]=[1,2,3]):
pass
"""
self.unchanged(a)
|
99b2d1a6087315c706ddd8de9691b330a84820d7
|
c4b8e1e09dedbccd37ca008ecaaca4438610bbaf
|
/z3/geometric_puzzle.py
|
440de76b9f532d8381c265e4893a6aa5dee5fdb8
|
[
"MIT"
] |
permissive
|
hakank/hakank
|
4806598b98cb36dd51b24b0ab688f52dadfe9626
|
c337aaf8187f15dcdc4d5b09cd2ed0dbdb2e72c2
|
refs/heads/master
| 2023-08-15T00:21:52.750270
| 2023-07-27T16:21:40
| 2023-07-27T16:21:40
| 11,933,517
| 336
| 97
|
MIT
| 2023-07-27T11:19:42
| 2013-08-06T20:12:10
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 2,668
|
py
|
geometric_puzzle.py
|
#
# Geometric puzzle in z3.
#
# From https://stackoverflow.com/questions/63107267/solving-a-simple-geometric-puzzle-in-clpq-r-prolog
# """
# Consider the following square:
#
# --------------------------
# | A | |
# | | |
# -------------------- |
# | | | |
# | B | C | E |
# | | | |
# | ------------| |
# | | D | |
# | | | |
# | | | |
# -------------------------
#
#
# You are given three constraints:
#
# - All rectangles (A, B, C, D and E) have the same area;
# - Their geometric layout constitutes a square; and
# - The height of A is 2.
#
# Now, I know this is very simple to solve by hand, but I thought it would be a very good
# example to show off the capabilities of CLP(Q/R) with Prolog:
#
# ...
#
# """
#
# Solution:
#
# Exact:
# areas: [64/5, 64/5, 64/5, 64/5, 64/5]
# heights: [2, 6, 3, 3, 8]
# widths: [32/5, 32/15, 64/15, 64/15, 8/5]
# As float:
# areas: [12.8, 12.8, 12.8, 12.8, 12.8]
# heights: [2, 6, 3, 3, 8]
# widths: [6.4, 2.133333, 4.266666, 4.266666, 1.6]
#
# This Z3 model was written by Hakan Kjellerstrand (hakank@gmail.com)
# See also my Z3 page: http://hakank.org/z3/
#
from z3_utils_hakank import *
def geometric_puzzle():
# s = SimpleSolver()
s = SolverFor("QF_LIRA")
# s = Optimize() # too slow
a,b,c,d,e = Reals("a b c d e")
areas = [a,b,c,d,e]
aw,bw,cw,dw,ew = Reals("aw bw cw dw ew")
ws = [aw,bw,cw,dw,ew]
ah,bh,ch,dh,eh = Reals("ah bh ch dh eh")
hs = [ah,bh,ch,dh,eh]
s.add(a == b , b == c , c == d , d == e,
a >= 1, b >= 1, c >= 1, d >= 1, e >= 1,
aw >= 1, bw >= 1, cw >= 1, dw >= 1, ew >= 1 ,
ah == 2 ,
a == ah * aw,
b == bh * bw,
c == ch * cw,
d == dh * dw,
e == eh * ew,
bw + cw == aw,
dw == cw ,
ah + bh == eh,
ch + dh == bh,
aw + ew == eh
)
while s.check() == sat:
mod = s.model()
print("Exact:")
print("areas:", [mod[t] for t in areas])
print("heights:", [mod[t] for t in hs])
print("widths:", [mod[t] for t in ws])
print("As float:")
print("areas:", [float(mod[t].as_decimal(6)) for t in areas])
print("heights:", [mod[t] for t in hs])
print("widths:", [float(mod[t].as_decimal(6).replace('?','')) for t in ws])
getDifferentSolution(s,mod,areas,hs,ws)
geometric_puzzle()
|
0781f50ead243fbe64a0c24be8803783ac08a760
|
ea57d267ab31480d8d731b2c095e9da9ad989133
|
/tests/test_aea/test_cli/test_get_wealth.py
|
ed24716ae093c70445464c9f81a6abd9f67ae44d
|
[
"Apache-2.0"
] |
permissive
|
fetchai/agents-aea
|
6d034f1db6f3beacf31dac2f5a1baaa60c8edb7d
|
bec49adaeba661d8d0f03ac9935dc89f39d95a0d
|
refs/heads/main
| 2023-08-08T23:19:06.276643
| 2023-02-04T10:46:39
| 2023-02-04T10:46:39
| 203,558,879
| 192
| 58
|
Apache-2.0
| 2023-07-19T04:45:26
| 2019-08-21T10:12:47
|
Python
|
UTF-8
|
Python
| false
| false
| 2,952
|
py
|
test_get_wealth.py
|
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2023 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------
"""This test module contains the tests for commands in aea.cli.generate_wealth module."""
from unittest import TestCase, mock
from aea_ledger_fetchai import FetchAICrypto
from aea.cli import cli
from aea.cli.get_wealth import _try_get_wealth
from aea.test_tools.test_cases import AEATestCaseEmpty
from tests.conftest import CLI_LOG_OPTION, CliRunner, method_scope
from tests.test_aea.test_cli.tools_for_testing import ContextMock
class GetWealthTestCase(TestCase):
"""Test case for _get_wealth method."""
@mock.patch("aea.cli.utils.package_utils.Wallet")
@mock.patch("aea.cli.utils.package_utils.verify_private_keys_ctx")
@mock.patch("aea.cli.get_wealth.try_get_balance")
def test__get_wealth_positive(self, *mocks):
"""Test for _get_wealth method positive result."""
ctx = ContextMock()
_try_get_wealth(ctx, "type")
@mock.patch("aea.cli.utils.decorators.try_to_load_agent_config")
@mock.patch("aea.cli.utils.package_utils.verify_private_keys_ctx")
@mock.patch("aea.cli.get_wealth._try_get_wealth")
@mock.patch("aea.cli.get_wealth.click.echo")
class GetWealthCommandTestCase(TestCase):
"""Test case for CLI get_wealth command."""
def setUp(self):
"""Set it up."""
self.runner = CliRunner()
def test_run_positive(self, *mocks):
"""Test for CLI get_wealth positive result."""
result = self.runner.invoke(
cli,
[
*CLI_LOG_OPTION,
"--skip-consistency-check",
"get-wealth",
FetchAICrypto.identifier,
],
standalone_mode=False,
)
self.assertEqual(result.exit_code, 0)
@method_scope
class TestGetWealth(AEATestCaseEmpty):
"""Test 'get-wealth' command."""
@mock.patch("click.echo")
def test_get_wealth(self, _echo_mock, password_or_none):
"""Run the main test."""
self.generate_private_key(password=password_or_none)
self.add_private_key(password=password_or_none)
self.get_wealth(password=password_or_none)
expected_wealth = 0
_echo_mock.assert_called_with(expected_wealth)
|
e650181393a51f301403ff2080e6ef0ac49fd798
|
3e63608e1cad90bc845c4580723e57ae7ca3f61d
|
/tests/unit/driftdetect/test_cli.py
|
8feb4b067175b0ec8bdae357e79ac6876f101e54
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
lyft/cartography
|
06dcbf13907cbb9a31b75cd8b21f5721f7cc1b01
|
830b8944879a01f52b21ee12b6fddf245f9733cb
|
refs/heads/master
| 2023-08-31T12:27:59.752452
| 2023-08-28T20:42:12
| 2023-08-28T20:42:12
| 172,811,550
| 2,778
| 334
|
Apache-2.0
| 2023-09-13T04:59:46
| 2019-02-27T00:16:29
|
Python
|
UTF-8
|
Python
| false
| false
| 2,460
|
py
|
test_cli.py
|
from unittest.mock import patch
from cartography.driftdetect.cli import CLI
from cartography.driftdetect.config import UpdateConfig
from cartography.driftdetect.util import valid_directory
from tests.integration import settings
def test_valid_directory():
"""
Tests valid directory function.
"""
config = UpdateConfig("tests", "localhost")
assert valid_directory(config.drift_detection_directory)
config.drift_detection_directory = "temp"
assert not valid_directory(config.drift_detection_directory)
@patch('cartography.driftdetect.cli.run_get_states')
def test_cli_main(mock_run):
"""
Tests that CLI runs update.
"""
cli = CLI(prog="cartography-detectdrift")
cli.main([
"get-state",
"--neo4j-uri",
settings.get("NEO4J_URL"),
"--drift-detection-directory",
"tests/data/test_update_detectors",
])
mock_run.assert_called_once()
def test_configure():
"""
Tests that the configure method correctly parses args.
"""
cli = CLI(prog="cartography-detectdrift")
config = cli.configure([
"get-state",
"--neo4j-uri",
settings.get("NEO4J_URL"),
"--drift-detection-directory",
"tests/data/detectors",
])
assert config.drift_detection_directory == "tests/data/detectors"
assert config.neo4j_uri == settings.get("NEO4J_URL")
@patch('cartography.driftdetect.cli.run_drift_detection')
def test_cli_get_drift(mock_run_drift_detection):
"""
Tests that get_drift is called.
"""
start_state = "1.json"
end_state = "2.json"
directory = "tests/data/test_cli_detectors/detector"
cli = CLI(prog="cartography-detectdrift")
cli.main([
"get-drift",
"--query-directory",
directory,
"--start-state",
start_state,
"--end-state",
end_state,
])
mock_run_drift_detection.assert_called_once()
@patch('cartography.driftdetect.cli.run_add_shortcut')
def test_cli_shortcuts(mock_run_add_shortcut):
"""
Tests that the CLI calls add shortcuts.
"""
file = "1.json"
shortcut = "most-recent"
directory = "tests/data/test_cli_detectors/detector"
cli = CLI(prog="cartography-detectdrift")
cli.main([
"add-shortcut",
"--query-directory",
directory,
"--shortcut",
shortcut,
"--file",
file,
])
mock_run_add_shortcut.assert_called_once()
|
e2fb108a1c09ca721db913f7c37d6287c0337b87
|
dd4cc30a2e4368c0d350ced7218295819e102fba
|
/sample_files/multibyte_before.py
|
3ed538d8630720dab0f67411ab957196cf9e7c7f
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
Wilfred/difftastic
|
49c87b4feea6ef1b5ab97abdfa823aff6aa7f354
|
a4ee2cf99e760562c3ffbd016a996ff50ef99442
|
refs/heads/master
| 2023-08-28T17:28:55.097192
| 2023-08-27T04:41:41
| 2023-08-27T04:41:41
| 162,276,894
| 14,748
| 287
|
MIT
| 2023-08-26T15:44:44
| 2018-12-18T11:19:45
|
Rust
|
UTF-8
|
Python
| false
| false
| 17
|
py
|
multibyte_before.py
|
"foo€".format()
|
4d9310acc4e3a8f05a39836c8734617f442cf246
|
e61e664d95af3b93150cda5b92695be6551d2a7c
|
/vega/algorithms/nas/modnas/metrics/torch/rasp.py
|
3088339b7a43a83085e59875910f6e0a90efce18
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] |
permissive
|
huawei-noah/vega
|
44aaf8bb28b45f707ed6cd4e871ba70fc0c04846
|
12e37a1991eb6771a2999fe0a46ddda920c47948
|
refs/heads/master
| 2023-09-01T20:16:28.746745
| 2023-02-15T09:36:59
| 2023-02-15T09:36:59
| 273,667,533
| 850
| 184
|
NOASSERTION
| 2023-02-15T09:37:01
| 2020-06-20T08:20:06
|
Python
|
UTF-8
|
Python
| false
| false
| 6,541
|
py
|
rasp.py
|
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""RASP-based metrics."""
from typing import List, Any, Union
from torch.nn.modules.module import Module
from modnas.registry.metrics import register, build
from modnas.arch_space.mixed_ops import MixedOp
from modnas.registry import SPEC_TYPE
from ..base import MetricsBase
try:
import rasp
import rasp.frontend as F
from rasp.profiler.tree import StatTreeNode
except ImportError:
rasp = None
StatTreeNode = None
@register
class RASPStatsMetrics(MetricsBase):
"""RASP node statistics metrics class."""
def __init__(self, item: str) -> None:
super().__init__()
self.item = item
def __call__(self, node: StatTreeNode) -> int:
"""Return metrics output."""
return node[self.item]
@register
class RASPTraversalMetrics(MetricsBase):
"""RASP model traversal metrics class."""
def __init__(self,
input_shape: List[int],
metrics: SPEC_TYPE,
compute: bool = True,
timing: bool = False,
device: str = 'cuda',
mixed_only: bool = False,
keep_stats: bool = True,
traversal_type: str = 'tape_nodes') -> None:
super().__init__()
if rasp is None:
raise ValueError('package RASP is not found')
self.metrics = build(metrics)
self.eval_compute = compute
self.eval_timing = timing
self.input_shape = input_shape
self.device = device
self.mixed_only = mixed_only
self.keep_stats = keep_stats
if traversal_type == 'tape_leaves':
self.traverse = self._traverse_tape_leaves
elif traversal_type == 'tape_nodes':
self.traverse = self._traverse_tape_nodes
else:
raise ValueError('invalid traversal type')
self.excluded = set()
def _traverse_tape_nodes(self, node: StatTreeNode) -> Union[float, int]:
ret = 0
if node in self.excluded:
return ret
if node.num_children == 0:
ret = self.metrics(node)
return ret
if node.tape is None:
return ret
for cur_node in node.tape.items:
if cur_node['cand_type']:
n_ret = self.metrics(cur_node)
else:
n_ret = self._traverse_tape_nodes(cur_node)
if n_ret is None:
n_ret = 0
ret += n_ret
return ret
def _traverse_tape_leaves(self, node: StatTreeNode) -> Union[float, int]:
ret = 0
for cur_node in node.tape.items_all:
if cur_node in self.excluded:
continue
n_ret = self.metrics(cur_node)
if n_ret is None:
n_ret = 0
ret += n_ret
return ret
def _stat(self, module: Module, input_shape: List[int]) -> None:
"""Run profiling on given module."""
if self.eval_compute:
F.hook_compute(module)
if self.eval_timing:
F.hook_timing(module)
F.run(module, F.get_random_data(input_shape), self.device)
F.unhook_compute(module)
F.unhook_timing(module)
def __call__(self, net: Module) -> Any:
"""Return metrics output."""
self.excluded.clear()
root = F.get_stats_node(net)
if root is None:
root = F.reg_stats_node(net)
self._stat(net, self.input_shape)
mt = 0.
for m in net.modules():
if not isinstance(m, MixedOp):
continue
mixop_node = F.get_stats_node(m)
self.excluded.add(mixop_node)
if mixop_node['in_shape'] is None:
raise ValueError('Inshape of mixop is None.')
mixop_mt = 0
m_in, _ = mixop_node['in_shape'], mixop_node['out_shape']
for p, (pn, op) in zip(m.prob(), m.named_candidates()):
if not p:
continue
subn = F.get_stats_node(op)
if subn['cand_type'] is None:
subn['cand_type'] = pn
if subn['compute_updated'] is None:
if subn['in_shape'] is None:
subn['in_shape'] = m_in
self._stat(subn.module, subn['in_shape'])
subn['compute_updated'] = True
subn_mt = self.metrics(subn)
if subn_mt is None:
subn_mt = self.traverse(subn)
if subn_mt is None:
self.logger.warning('unresolved node: {} type: {}'.format(subn['name'], subn['type']))
subn_mt = 0
mixop_mt = mixop_mt + subn_mt * p
mt += mixop_mt
if not self.mixed_only:
mt = mt + self.traverse(root)
if not self.keep_stats:
F.unreg_stats_node(net)
return mt
@register
class RASPRootMetrics(MetricsBase):
"""RASP root node metrics class."""
def __init__(self, input_shape, metrics, compute=True, timing=False, device=None):
super().__init__()
if rasp is None:
raise ValueError('package RASP is not found')
self.metrics = build(metrics)
self.eval_compute = compute
self.eval_timing = timing
self.input_shape = input_shape
self.device = device
def __call__(self, net):
"""Return metrics output."""
root = F.get_stats_node(net)
if root is None:
root = F.reg_stats_node(net)
if self.eval_compute:
F.hook_compute(net)
if self.eval_timing:
F.hook_timing(net)
inputs = F.get_random_data(self.input_shape)
F.run(net, inputs, self.device)
F.unhook_compute(net)
F.unhook_timing(net)
return self.metrics(root)
|
46cb3193e3c8a14b6bc4bc46c6aa3cdc556bcca9
|
b6538247354ef14fcff6dcf41d1d22257e1c6cd3
|
/docs/video_moviepy.py
|
a778fcd4d10526737f17823a23a3432433657a73
|
[
"MIT"
] |
permissive
|
dariober/ASCIIGenome
|
15af4752fce62183f432baebc2a2a6517a9bc22b
|
ec6cde3576388dee47142970a396033cfe6e291d
|
refs/heads/master
| 2023-09-01T09:29:29.123499
| 2023-03-01T15:44:25
| 2023-03-01T15:44:25
| 58,925,144
| 209
| 21
|
MIT
| 2023-03-01T15:37:11
| 2016-05-16T10:46:30
|
Java
|
UTF-8
|
Python
| false
| false
| 2,141
|
py
|
video_moviepy.py
|
#!/usr/bin/env ipython
from moviepy.editor import *
from moviepy import editor
from moviepy.video.tools.subtitles import SubtitlesClip
import os
# ---------------------- 8< ----------------------------------------------------
def annotate(clip, txt, txt_color= 'grey20', fontsize=50, font='Xolonium-Bold'):
""" Writes a text at the bottom of the clip. """
txtclip = editor.TextClip(txt, fontsize=fontsize, font=font, color=txt_color)
cvc = editor.CompositeVideoClip([clip, txtclip.set_pos(('center', 'bottom'))])
return cvc.set_duration(clip.duration)
# ---------------------- 8< ----------------------------------------------------
os.chdir("/Users/berald01/Desktop/asciigenome_demo/")
clip = VideoFileClip("bam-3.mov")
sub1= clip.subclip(1.04, 3.17)
sub2= clip.subclip(8.16, 32.00)
#header = TextClip(txt= "ASCIIGenome!\n- Genome Browser for Terminals -\n",
# font='Amiri-Bold', fontsize=100, bg_color= 'white', color="grey20").set_duration(1)
final= concatenate_videoclips([sub1, sub2], method= 'compose')
final.write_videofile('bam-3.cut.mp4', fps= 3, codec= 'mpeg4')
clip = VideoFileClip("bam-3.cut.mp4")
subs = [((0, 3.17), 'Load bam file'),
((3.17, 7.21), 'Go to region'),
((7.21, 12), 'Zoom in'),
((12, 15), 'Move forward'),
((15, 18), 'Zoom out'),
((18, 26), 'Filter reads')
]
annotated_clips = [annotate(clip.subclip(from_t, to_t), txt, txt_color= 'blue') for (from_t, to_t), txt in subs]
final_clip = editor.concatenate_videoclips(annotated_clips)
final_clip.write_videofile("bam-3.subs.mp4", fps= 3)
# ---------------------- 8< ----------------------------------------------------
os.chdir("/Users/berald01/Desktop/asciigenome_demo/")
clip = VideoFileClip("bigWig-2.mov")
cat= [clip.subclip(20.00, 22.00),
clip.subclip(24.00, 29.00),
clip.subclip(30.00, 35.00),
clip.subclip(41.00, 45),
clip.subclip(46.5, 48),
clip.subclip(51, 53),
clip.subclip(56, 64),
clip.subclip(80, 82),
]
final= concatenate_videoclips(cat, method= 'compose')
final.write_videofile('bigWig-3.cut.mp4', fps= 3, codec= 'mpeg4')
|
b3828be36bd20e56d44987b97eca84c4edc29193
|
5ef6c8d47864f471e26b9902d61f8c687e941f05
|
/src/genie/libs/parser/iosxe/c9600/tests/ShowPlatformFedSwitchActiveIfmMapping/cli/equal/golden_output_expected.py
|
75f840e2a55d9e0b35541a1c1381eb5d06b46212
|
[
"Apache-2.0"
] |
permissive
|
CiscoTestAutomation/genieparser
|
169c196558f1c1a0f0d10650876096f993224917
|
b531eff760b2e44cd69d7a2716db6f866907c239
|
refs/heads/master
| 2023-09-03T08:56:18.831340
| 2023-08-29T22:32:02
| 2023-08-29T22:32:02
| 131,621,824
| 247
| 409
|
Apache-2.0
| 2023-08-29T22:32:04
| 2018-04-30T16:51:50
|
Python
|
UTF-8
|
Python
| false
| false
| 31,539
|
py
|
golden_output_expected.py
|
expected_output={
"interface":{
"FortyGigabitEthernet1/5/0/1":{
"IF_ID":"0x9",
"Inst":0,
"Asic":0,
"Core":0,
"Port":1,
"SubPort":0,
"Mac":10,
"Cntx":4,
"LPN":1,
"GPN":385,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/2":{
"IF_ID":"0xa",
"Inst":0,
"Asic":0,
"Core":0,
"Port":6,
"SubPort":0,
"Mac":8,
"Cntx":5,
"LPN":2,
"GPN":386,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/3":{
"IF_ID":"0xb",
"Inst":0,
"Asic":0,
"Core":0,
"Port":17,
"SubPort":0,
"Mac":20,
"Cntx":4,
"LPN":3,
"GPN":2360,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/4":{
"IF_ID":"0xc",
"Inst":0,
"Asic":0,
"Core":0,
"Port":22,
"SubPort":0,
"Mac":22,
"Cntx":5,
"LPN":4,
"GPN":388,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/5":{
"IF_ID":"0xd",
"Inst":1,
"Asic":0,
"Core":1,
"Port":10,
"SubPort":0,
"Mac":10,
"Cntx":9,
"LPN":5,
"GPN":389,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/6":{
"IF_ID":"0xe",
"Inst":1,
"Asic":0,
"Core":1,
"Port":2,
"SubPort":0,
"Mac":8,
"Cntx":8,
"LPN":6,
"GPN":390,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/7":{
"IF_ID":"0xf",
"Inst":1,
"Asic":0,
"Core":1,
"Port":26,
"SubPort":0,
"Mac":20,
"Cntx":9,
"LPN":7,
"GPN":391,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/8":{
"IF_ID":"0x10",
"Inst":1,
"Asic":0,
"Core":1,
"Port":18,
"SubPort":0,
"Mac":22,
"Cntx":8,
"LPN":8,
"GPN":392,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/9":{
"IF_ID":"0x11",
"Inst":2,
"Asic":1,
"Core":0,
"Port":1,
"SubPort":0,
"Mac":10,
"Cntx":4,
"LPN":9,
"GPN":393,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/10":{
"IF_ID":"0x12",
"Inst":2,
"Asic":1,
"Core":0,
"Port":6,
"SubPort":0,
"Mac":8,
"Cntx":5,
"LPN":10,
"GPN":394,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/11":{
"IF_ID":"0x13",
"Inst":2,
"Asic":1,
"Core":0,
"Port":17,
"SubPort":0,
"Mac":20,
"Cntx":4,
"LPN":11,
"GPN":395,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/12":{
"IF_ID":"0x14",
"Inst":2,
"Asic":1,
"Core":0,
"Port":22,
"SubPort":0,
"Mac":22,
"Cntx":5,
"LPN":12,
"GPN":396,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/13":{
"IF_ID":"0x15",
"Inst":3,
"Asic":1,
"Core":1,
"Port":10,
"SubPort":0,
"Mac":10,
"Cntx":9,
"LPN":13,
"GPN":397,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/14":{
"IF_ID":"0x16",
"Inst":3,
"Asic":1,
"Core":1,
"Port":2,
"SubPort":0,
"Mac":8,
"Cntx":8,
"LPN":14,
"GPN":398,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/15":{
"IF_ID":"0x17",
"Inst":3,
"Asic":1,
"Core":1,
"Port":26,
"SubPort":0,
"Mac":20,
"Cntx":9,
"LPN":15,
"GPN":399,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/16":{
"IF_ID":"0x18",
"Inst":3,
"Asic":1,
"Core":1,
"Port":18,
"SubPort":0,
"Mac":22,
"Cntx":8,
"LPN":16,
"GPN":400,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/17":{
"IF_ID":"0x19",
"Inst":4,
"Asic":2,
"Core":0,
"Port":1,
"SubPort":0,
"Mac":10,
"Cntx":4,
"LPN":17,
"GPN":401,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/18":{
"IF_ID":"0x1a",
"Inst":4,
"Asic":2,
"Core":0,
"Port":6,
"SubPort":0,
"Mac":8,
"Cntx":5,
"LPN":18,
"GPN":402,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/19":{
"IF_ID":"0x1b",
"Inst":4,
"Asic":2,
"Core":0,
"Port":17,
"SubPort":0,
"Mac":20,
"Cntx":4,
"LPN":19,
"GPN":403,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/20":{
"IF_ID":"0x1c",
"Inst":4,
"Asic":2,
"Core":0,
"Port":22,
"SubPort":0,
"Mac":22,
"Cntx":5,
"LPN":20,
"GPN":404,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/21":{
"IF_ID":"0x1d",
"Inst":5,
"Asic":2,
"Core":1,
"Port":10,
"SubPort":0,
"Mac":10,
"Cntx":9,
"LPN":21,
"GPN":405,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/22":{
"IF_ID":"0x1e",
"Inst":5,
"Asic":2,
"Core":1,
"Port":2,
"SubPort":0,
"Mac":8,
"Cntx":8,
"LPN":22,
"GPN":406,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/23":{
"IF_ID":"0x1f",
"Inst":5,
"Asic":2,
"Core":1,
"Port":26,
"SubPort":0,
"Mac":20,
"Cntx":9,
"LPN":23,
"GPN":407,
"Type":"NIF",
"Active":"Y"
},
"FortyGigabitEthernet1/5/0/24":{
"IF_ID":"0x20",
"Inst":5,
"Asic":2,
"Core":1,
"Port":18,
"SubPort":0,
"Mac":22,
"Cntx":8,
"LPN":24,
"GPN":408,
"Type":"NIF",
"Active":"Y"
},
"HundredGigE1/5/0/25":{
"IF_ID":"0x21",
"Inst":0,
"Asic":0,
"Core":0,
"Port":1,
"SubPort":0,
"Mac":8,
"Cntx":4,
"LPN":25,
"GPN":409,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/26":{
"IF_ID":"0x22",
"Inst":0,
"Asic":0,
"Core":0,
"Port":1,
"SubPort":0,
"Mac":8,
"Cntx":4,
"LPN":26,
"GPN":410,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/27":{
"IF_ID":"0x23",
"Inst":0,
"Asic":0,
"Core":0,
"Port":17,
"SubPort":0,
"Mac":20,
"Cntx":4,
"LPN":27,
"GPN":411,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/28":{
"IF_ID":"0x24",
"Inst":0,
"Asic":0,
"Core":0,
"Port":17,
"SubPort":0,
"Mac":20,
"Cntx":4,
"LPN":28,
"GPN":412,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/29":{
"IF_ID":"0x25",
"Inst":1,
"Asic":0,
"Core":1,
"Port":2,
"SubPort":0,
"Mac":8,
"Cntx":8,
"LPN":29,
"GPN":413,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/30":{
"IF_ID":"0x26",
"Inst":1,
"Asic":0,
"Core":1,
"Port":2,
"SubPort":0,
"Mac":8,
"Cntx":8,
"LPN":30,
"GPN":414,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/31":{
"IF_ID":"0x27",
"Inst":1,
"Asic":0,
"Core":1,
"Port":18,
"SubPort":0,
"Mac":20,
"Cntx":8,
"LPN":31,
"GPN":415,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/32":{
"IF_ID":"0x28",
"Inst":1,
"Asic":0,
"Core":1,
"Port":18,
"SubPort":0,
"Mac":20,
"Cntx":8,
"LPN":32,
"GPN":416,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/33":{
"IF_ID":"0x29",
"Inst":2,
"Asic":1,
"Core":0,
"Port":1,
"SubPort":0,
"Mac":8,
"Cntx":4,
"LPN":33,
"GPN":417,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/34":{
"IF_ID":"0x2a",
"Inst":2,
"Asic":1,
"Core":0,
"Port":1,
"SubPort":0,
"Mac":8,
"Cntx":4,
"LPN":34,
"GPN":418,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/35":{
"IF_ID":"0x2b",
"Inst":2,
"Asic":1,
"Core":0,
"Port":17,
"SubPort":0,
"Mac":20,
"Cntx":4,
"LPN":35,
"GPN":419,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/36":{
"IF_ID":"0x2c",
"Inst":2,
"Asic":1,
"Core":0,
"Port":17,
"SubPort":0,
"Mac":20,
"Cntx":4,
"LPN":36,
"GPN":420,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/37":{
"IF_ID":"0x2d",
"Inst":3,
"Asic":1,
"Core":1,
"Port":2,
"SubPort":0,
"Mac":8,
"Cntx":8,
"LPN":37,
"GPN":421,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/38":{
"IF_ID":"0x2e",
"Inst":3,
"Asic":1,
"Core":1,
"Port":2,
"SubPort":0,
"Mac":8,
"Cntx":8,
"LPN":38,
"GPN":422,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/39":{
"IF_ID":"0x2f",
"Inst":3,
"Asic":1,
"Core":1,
"Port":18,
"SubPort":0,
"Mac":20,
"Cntx":8,
"LPN":39,
"GPN":423,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/40":{
"IF_ID":"0x30",
"Inst":3,
"Asic":1,
"Core":1,
"Port":18,
"SubPort":0,
"Mac":20,
"Cntx":8,
"LPN":40,
"GPN":424,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/41":{
"IF_ID":"0x31",
"Inst":4,
"Asic":2,
"Core":0,
"Port":1,
"SubPort":0,
"Mac":8,
"Cntx":4,
"LPN":41,
"GPN":425,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/42":{
"IF_ID":"0x32",
"Inst":4,
"Asic":2,
"Core":0,
"Port":1,
"SubPort":0,
"Mac":8,
"Cntx":4,
"LPN":42,
"GPN":426,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/43":{
"IF_ID":"0x33",
"Inst":4,
"Asic":2,
"Core":0,
"Port":17,
"SubPort":0,
"Mac":20,
"Cntx":4,
"LPN":43,
"GPN":427,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/44":{
"IF_ID":"0x34",
"Inst":4,
"Asic":2,
"Core":0,
"Port":17,
"SubPort":0,
"Mac":20,
"Cntx":4,
"LPN":44,
"GPN":428,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/45":{
"IF_ID":"0x35",
"Inst":5,
"Asic":2,
"Core":1,
"Port":2,
"SubPort":0,
"Mac":8,
"Cntx":8,
"LPN":45,
"GPN":429,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/46":{
"IF_ID":"0x36",
"Inst":5,
"Asic":2,
"Core":1,
"Port":2,
"SubPort":0,
"Mac":8,
"Cntx":8,
"LPN":46,
"GPN":430,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/47":{
"IF_ID":"0x37",
"Inst":5,
"Asic":2,
"Core":1,
"Port":18,
"SubPort":0,
"Mac":20,
"Cntx":8,
"LPN":47,
"GPN":431,
"Type":"NIF",
"Active":"N"
},
"HundredGigE1/5/0/48":{
"IF_ID":"0x38",
"Inst":5,
"Asic":2,
"Core":1,
"Port":18,
"SubPort":0,
"Mac":20,
"Cntx":8,
"LPN":48,
"GPN":432,
"Type":"NIF",
"Active":"N"
},
"TwentyFiveGigE1/6/0/1":{
"IF_ID":"0x39",
"Inst":0,
"Asic":0,
"Core":0,
"Port":3,
"SubPort":0,
"Mac":3,
"Cntx":12,
"LPN":1,
"GPN":481,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/2":{
"IF_ID":"0x3a",
"Inst":0,
"Asic":0,
"Core":0,
"Port":13,
"SubPort":0,
"Mac":2,
"Cntx":13,
"LPN":2,
"GPN":482,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/3":{
"IF_ID":"0x3b",
"Inst":0,
"Asic":0,
"Core":0,
"Port":14,
"SubPort":0,
"Mac":1,
"Cntx":14,
"LPN":3,
"GPN":483,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/4":{
"IF_ID":"0x3c",
"Inst":0,
"Asic":0,
"Core":0,
"Port":15,
"SubPort":0,
"Mac":0,
"Cntx":15,
"LPN":4,
"GPN":484,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/5":{
"IF_ID":"0x3d",
"Inst":0,
"Asic":0,
"Core":0,
"Port":19,
"SubPort":0,
"Mac":28,
"Cntx":12,
"LPN":5,
"GPN":485,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/6":{
"IF_ID":"0x3e",
"Inst":0,
"Asic":0,
"Core":0,
"Port":29,
"SubPort":0,
"Mac":29,
"Cntx":13,
"LPN":6,
"GPN":486,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/7":{
"IF_ID":"0x3f",
"Inst":0,
"Asic":0,
"Core":0,
"Port":30,
"SubPort":0,
"Mac":30,
"Cntx":14,
"LPN":7,
"GPN":487,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/8":{
"IF_ID":"0x40",
"Inst":0,
"Asic":0,
"Core":0,
"Port":31,
"SubPort":0,
"Mac":31,
"Cntx":15,
"LPN":8,
"GPN":488,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/9":{
"IF_ID":"0x41",
"Inst":1,
"Asic":0,
"Core":1,
"Port":15,
"SubPort":0,
"Mac":3,
"Cntx":15,
"LPN":9,
"GPN":489,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/10":{
"IF_ID":"0x42",
"Inst":1,
"Asic":0,
"Core":1,
"Port":14,
"SubPort":0,
"Mac":2,
"Cntx":14,
"LPN":10,
"GPN":490,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/11":{
"IF_ID":"0x43",
"Inst":1,
"Asic":0,
"Core":1,
"Port":13,
"SubPort":0,
"Mac":1,
"Cntx":13,
"LPN":11,
"GPN":491,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/12":{
"IF_ID":"0x44",
"Inst":1,
"Asic":0,
"Core":1,
"Port":3,
"SubPort":0,
"Mac":0,
"Cntx":12,
"LPN":12,
"GPN":492,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/13":{
"IF_ID":"0x45",
"Inst":1,
"Asic":0,
"Core":1,
"Port":31,
"SubPort":0,
"Mac":28,
"Cntx":15,
"LPN":13,
"GPN":493,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/14":{
"IF_ID":"0x46",
"Inst":1,
"Asic":0,
"Core":1,
"Port":30,
"SubPort":0,
"Mac":29,
"Cntx":14,
"LPN":14,
"GPN":494,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/15":{
"IF_ID":"0x47",
"Inst":1,
"Asic":0,
"Core":1,
"Port":29,
"SubPort":0,
"Mac":30,
"Cntx":13,
"LPN":15,
"GPN":495,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/16":{
"IF_ID":"0x48",
"Inst":1,
"Asic":0,
"Core":1,
"Port":19,
"SubPort":0,
"Mac":31,
"Cntx":12,
"LPN":16,
"GPN":496,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/17":{
"IF_ID":"0x49",
"Inst":2,
"Asic":1,
"Core":0,
"Port":3,
"SubPort":0,
"Mac":3,
"Cntx":12,
"LPN":17,
"GPN":497,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/18":{
"IF_ID":"0x4a",
"Inst":2,
"Asic":1,
"Core":0,
"Port":13,
"SubPort":0,
"Mac":2,
"Cntx":13,
"LPN":18,
"GPN":498,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/19":{
"IF_ID":"0x4b",
"Inst":2,
"Asic":1,
"Core":0,
"Port":14,
"SubPort":0,
"Mac":1,
"Cntx":14,
"LPN":19,
"GPN":499,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/20":{
"IF_ID":"0x4c",
"Inst":2,
"Asic":1,
"Core":0,
"Port":15,
"SubPort":0,
"Mac":0,
"Cntx":15,
"LPN":20,
"GPN":500,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/21":{
"IF_ID":"0x4d",
"Inst":2,
"Asic":1,
"Core":0,
"Port":19,
"SubPort":0,
"Mac":28,
"Cntx":12,
"LPN":21,
"GPN":501,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/22":{
"IF_ID":"0x4e",
"Inst":2,
"Asic":1,
"Core":0,
"Port":29,
"SubPort":0,
"Mac":29,
"Cntx":13,
"LPN":22,
"GPN":502,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/23":{
"IF_ID":"0x4f",
"Inst":2,
"Asic":1,
"Core":0,
"Port":30,
"SubPort":0,
"Mac":30,
"Cntx":14,
"LPN":23,
"GPN":503,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/24":{
"IF_ID":"0x50",
"Inst":2,
"Asic":1,
"Core":0,
"Port":31,
"SubPort":0,
"Mac":31,
"Cntx":15,
"LPN":24,
"GPN":504,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/25":{
"IF_ID":"0x51",
"Inst":3,
"Asic":1,
"Core":1,
"Port":15,
"SubPort":0,
"Mac":3,
"Cntx":15,
"LPN":25,
"GPN":505,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/26":{
"IF_ID":"0x52",
"Inst":3,
"Asic":1,
"Core":1,
"Port":14,
"SubPort":0,
"Mac":2,
"Cntx":14,
"LPN":26,
"GPN":506,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/27":{
"IF_ID":"0x53",
"Inst":3,
"Asic":1,
"Core":1,
"Port":13,
"SubPort":0,
"Mac":1,
"Cntx":13,
"LPN":27,
"GPN":507,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/28":{
"IF_ID":"0x54",
"Inst":3,
"Asic":1,
"Core":1,
"Port":3,
"SubPort":0,
"Mac":0,
"Cntx":12,
"LPN":28,
"GPN":508,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/29":{
"IF_ID":"0xd3",
"Inst":3,
"Asic":1,
"Core":1,
"Port":31,
"SubPort":0,
"Mac":28,
"Cntx":15,
"LPN":29,
"GPN":509,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/30":{
"IF_ID":"0x56",
"Inst":3,
"Asic":1,
"Core":1,
"Port":30,
"SubPort":0,
"Mac":29,
"Cntx":14,
"LPN":30,
"GPN":510,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/31":{
"IF_ID":"0x57",
"Inst":3,
"Asic":1,
"Core":1,
"Port":29,
"SubPort":0,
"Mac":30,
"Cntx":13,
"LPN":31,
"GPN":511,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/32":{
"IF_ID":"0x58",
"Inst":3,
"Asic":1,
"Core":1,
"Port":19,
"SubPort":0,
"Mac":31,
"Cntx":12,
"LPN":32,
"GPN":512,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/33":{
"IF_ID":"0x59",
"Inst":4,
"Asic":2,
"Core":0,
"Port":3,
"SubPort":0,
"Mac":3,
"Cntx":12,
"LPN":33,
"GPN":513,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/34":{
"IF_ID":"0x5a",
"Inst":4,
"Asic":2,
"Core":0,
"Port":13,
"SubPort":0,
"Mac":2,
"Cntx":13,
"LPN":34,
"GPN":514,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/35":{
"IF_ID":"0x5b",
"Inst":4,
"Asic":2,
"Core":0,
"Port":14,
"SubPort":0,
"Mac":1,
"Cntx":14,
"LPN":35,
"GPN":515,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/36":{
"IF_ID":"0x5c",
"Inst":4,
"Asic":2,
"Core":0,
"Port":15,
"SubPort":0,
"Mac":0,
"Cntx":15,
"LPN":36,
"GPN":516,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/37":{
"IF_ID":"0x5d",
"Inst":4,
"Asic":2,
"Core":0,
"Port":19,
"SubPort":0,
"Mac":28,
"Cntx":12,
"LPN":37,
"GPN":517,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/38":{
"IF_ID":"0x5e",
"Inst":4,
"Asic":2,
"Core":0,
"Port":29,
"SubPort":0,
"Mac":29,
"Cntx":13,
"LPN":38,
"GPN":518,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/39":{
"IF_ID":"0x5f",
"Inst":4,
"Asic":2,
"Core":0,
"Port":30,
"SubPort":0,
"Mac":30,
"Cntx":14,
"LPN":39,
"GPN":519,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/40":{
"IF_ID":"0x60",
"Inst":4,
"Asic":2,
"Core":0,
"Port":31,
"SubPort":0,
"Mac":31,
"Cntx":15,
"LPN":40,
"GPN":520,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/41":{
"IF_ID":"0x61",
"Inst":5,
"Asic":2,
"Core":1,
"Port":15,
"SubPort":0,
"Mac":3,
"Cntx":15,
"LPN":41,
"GPN":521,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/42":{
"IF_ID":"0x62",
"Inst":5,
"Asic":2,
"Core":1,
"Port":14,
"SubPort":0,
"Mac":2,
"Cntx":14,
"LPN":42,
"GPN":522,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/43":{
"IF_ID":"0x63",
"Inst":5,
"Asic":2,
"Core":1,
"Port":13,
"SubPort":0,
"Mac":1,
"Cntx":13,
"LPN":43,
"GPN":523,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/44":{
"IF_ID":"0x64",
"Inst":5,
"Asic":2,
"Core":1,
"Port":3,
"SubPort":0,
"Mac":0,
"Cntx":12,
"LPN":44,
"GPN":524,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/45":{
"IF_ID":"0x65",
"Inst":5,
"Asic":2,
"Core":1,
"Port":31,
"SubPort":0,
"Mac":28,
"Cntx":15,
"LPN":45,
"GPN":525,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/46":{
"IF_ID":"0x66",
"Inst":5,
"Asic":2,
"Core":1,
"Port":30,
"SubPort":0,
"Mac":29,
"Cntx":14,
"LPN":46,
"GPN":526,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/47":{
"IF_ID":"0x67",
"Inst":5,
"Asic":2,
"Core":1,
"Port":29,
"SubPort":0,
"Mac":30,
"Cntx":13,
"LPN":47,
"GPN":527,
"Type":"NIF",
"Active":"Y"
},
"TwentyFiveGigE1/6/0/48":{
"IF_ID":"0x68",
"Inst":5,
"Asic":2,
"Core":1,
"Port":19,
"SubPort":0,
"Mac":31,
"Cntx":12,
"LPN":48,
"GPN":528,
"Type":"NIF",
"Active":"Y"
}
}
}
|
9a266380841c9794d368366375b88faee177e63b
|
b84517cc27cf91e2a29be81314e7f2629996d0f6
|
/examples/cache_machine/redis_settings.py
|
3263e6621e0173d94b8fb0162d3e5dc413c1005c
|
[
"BSD-2-Clause"
] |
permissive
|
django-cache-machine/django-cache-machine
|
7a881b38e445d4143f2acb31e3ab790cd344c30b
|
01f12b9a4907064440dcd8b2d4b1375b26b11e4d
|
refs/heads/main
| 2023-09-04T22:42:05.924757
| 2023-02-20T18:13:51
| 2023-02-20T18:13:51
| 510,383
| 403
| 87
|
BSD-3-Clause
| 2022-07-06T18:40:09
| 2010-02-09T23:01:12
|
Python
|
UTF-8
|
Python
| false
| false
| 98
|
py
|
redis_settings.py
|
# flake8: noqa
from .settings import *
CACHE_MACHINE_USE_REDIS = True
REDIS_BACKEND = "redis://"
|
ed02667d9e21a9fe35a1d4db00d7773e8deaf442
|
eecd5e4c50d8b78a769bcc2675250576bed34066
|
/lib/petsc/bin/maint/petsclinter/petsclinter/classes/docs/_doc_section_base.py
|
c174ffcfebfdb329e4f8053cd3243c5e44c5e63c
|
[
"BSD-2-Clause"
] |
permissive
|
petsc/petsc
|
3b1a04fea71858e0292f9fd4d04ea11618c50969
|
9c5460f9064ca60dd71a234a1f6faf93e7a6b0c9
|
refs/heads/main
| 2023-08-17T20:51:16.507070
| 2023-08-17T16:08:06
| 2023-08-17T16:08:06
| 8,691,401
| 341
| 169
|
NOASSERTION
| 2023-03-29T11:02:58
| 2013-03-10T20:55:21
|
C
|
UTF-8
|
Python
| false
| false
| 40,484
|
py
|
_doc_section_base.py
|
#!/usr/bin/env python3
"""
# Created: Sun Nov 20 12:27:36 2022 (-0500)
# @author: Jacob Faibussowitsch
"""
from __future__ import annotations
import re
import enum
import difflib
import textwrap
import itertools
import collections
from ..._typing import *
from ..._error import ParsingError
from .._diag import DiagnosticManager, Diagnostic
from .._src_pos import SourceRange
from .._patch import Patch
"""
==========================================================================================
Base Classes
==========================================================================================
"""
class DescribableItem:
__slots__ = 'text', 'prefix', 'arg', 'description', 'sep', 'expected_sep'
text: str
prefix: str
arg: str
description: str
sep: str
expected_sep: str
def __init__(self, raw: str, prefixes: Optional[Sequence[str]] = None, expected_sep: str = '-') -> None:
r"""Construct a `DescribableItem`
Parameters
----------
raw :
the raw line
prefixes : optional
the set of possible item prefixes
expected_sep : optional
the expected separator char between the arg and description
"""
if prefixes is None:
prefixes = tuple()
text = raw.strip()
sep = expected_sep
prefix, arg, descr = self.split_param(text, prefixes, sep)
if not descr:
found = False
for sep in (',', '='):
_, arg, descr = self.split_param(text, prefixes, sep)
if descr:
found = True
break
if not found:
sep = ' '
if prefix:
arg = text.split(prefix, maxsplit=1)[1].strip()
else:
arg, *rest = text.split(maxsplit=1)
if isinstance(rest, (list, tuple)):
descr = rest[0] if len(rest) else ''
assert isinstance(descr, str)
self.text = raw
self.prefix = prefix
self.arg = arg
self.description = descr
self.sep = sep
self.expected_sep = expected_sep
return
@staticmethod
def split_param(text: str, prefixes: Sequence[str], sep: str) -> tuple[str, str, str]:
r"""Retrieve groups '([\.+-$])\s*([A-z,-]+) - (.*)'
Parameters
----------
text :
the raw text line
prefixes :
the set of possible line prefixes to look for, empty set for no prexies
sep :
the separator char between the argument and its description
Returns
-------
prefix :
the detected prefix
arg :
the detected argument
descr :
the detected deescription
Notes
-----
Any one of the returned values may be the empty string, which indicates that value was not detected.
"""
stripped = text.strip()
if not prefixes:
prefix = ''
rest = stripped
else:
try:
prefix = next(filter(stripped.startswith, prefixes))
except StopIteration:
prefix = ''
rest = stripped
else:
rest = stripped.split(prefix, maxsplit=1)[1].strip()
assert len(prefix) >= 1
assert rest
arg, part_sep, descr = rest.partition(sep.join((' ', ' ')))
if not part_sep:
if rest.endswith(sep):
arg = rest[:-1]
elif sep + ' ' in rest:
arg, _, descr = rest.partition(sep + ' ')
# if we hit neither then there is no '-' in text, possible case of '[prefix] foo'?
return prefix, arg.strip(), descr.lstrip()
def arglen(self) -> int:
r"""Return the argument length
Returns
-------
alen :
the length l such that self.text[:l] returns all text up until the end of the arg name
"""
arg = self.arg
return self.text.find(arg) + len(arg)
def check(self, docstring: PetscDocStringImpl, section: SectionImpl, loc: SourceRange) -> None:
r"""Check a `DescribableItem` for errors
Parameters
----------
docstring :
the owning `PetscDocString` instance
section :
the owning section instance
loc :
the source range of the argument
"""
name = section.transform(section.name)
if self.sep != self.expected_sep:
diag = section.diags.wrong_description_separator
mess = f"{name} seems to be missing a description separator; I suspect you may be using '{self.sep}' as a separator instead of '{self.expected_sep}'. Expected '{self.arg} {self.expected_sep} {self.description}'"
elif not self.description:
diag = section.diags.missing_description
mess = f"{name} missing a description. Expected '{self.arg} {self.expected_sep} a very useful description'"
else:
return # ok?
docstring.add_diagnostic_from_source_range(Diagnostic.Kind.ERROR, diag, mess, loc)
return
class DocBase:
__slots__: tuple[str, ...] = tuple()
@classmethod
def __diagnostic_prefix__(cls, *flags: str) -> collections.deque[str]:
return cls.diagnostic_flag('-'.join(flags))
@classmethod
def diagnostic_flag(cls, text: Union[str, collections.deque[str]], *, prefix: str = 'doc') -> collections.deque[str]:
r"""Construct the diagnostic flag components
Parameters
----------
text :
the base flag or collections.deque of flags
prefix : optional
the flag prefix
Returns
-------
A collection.deque of flag components
"""
if isinstance(text, str):
ret = collections.deque((prefix, text))
if prefix != 'doc':
ret.appendleft('doc')
return ret
assert isinstance(text, collections.deque)
if not text[0].startswith(prefix):
text.appendleft(prefix)
return text
@DiagnosticManager.register(
('section-header-missing', 'Verify that required sections exist in the docstring'),
('section-header-unique', 'Verify that appropriate sections are unique per docstring'),
('section-barren', 'Verify there are no sections containing a title and nothing else'),
('section-header-solitary', 'Verify that qualifying section headers are alone on their line'),
('section-header-spelling', 'Verify section headers are correctly spelled'),
('section-header-unknown', 'Verify that section header is known'),
)
class SectionBase(DocBase):
"""
Container for a single section of the docstring
"""
__slots__ = (
'name', 'required', 'titles', 'keywords', 'raw', 'extent', '_lines', 'items', 'seen_headers',
'solitary'
)
name: str
required: bool
titles: tuple[str, ...]
keywords: tuple[str, ...]
extent: SourceRange
_lines: list[tuple[SourceRange, str, Verdict]]
items: Any
seen_headers: dict[str, list[SourceRange]]
solitary: bool
# to pacify type checkers...
diags: DiagnosticMap
LineInspector: TypeAlias = collections.abc.Callable[['PetscDocStringImpl', SourceRange, str, 'Verdict'], None]
def __init__(self, name: str, required: bool = False, keywords: Optional[tuple[str, ...]] = None, titles: Optional[tuple[str, ...]] = None, solitary: bool = True) -> None:
r"""Construct a `SectionBase`
Parameters
----------
name :
the name of this section
required : optional
is this section required in the docstring
keywords : optional
keywords to help match an unknown title to a section
titles :
header-titles, i.e. "Input Parameter", or "Level", must be spelled correctly
solitary : optional
should the heading be alone on the line it sits on
Notes
-----
In addition it has the following additional members
raw :
the raw text in the section
extent :
the SourceRange for the whole section
_lines :
a tuple of each line of text and its SourceRange in the section
items :
a container of extracted tokens of interest, e.g. the level value, options parameters,
function parameters, etc
"""
assert isinstance(name, str)
titlename = name.title()
if titles is None:
titles = (titlename,)
else:
titles = tuple(titles)
if keywords is None:
keywords = (titlename,)
else:
keywords = tuple(keywords)
self.name = name
self.required = required
self.titles = titles
self.keywords = tuple(set(keywords + self.titles))
self.solitary = solitary
self.clear()
return
def __str__(self) -> str:
return '\n'.join([
f'Type: {type(self)}',
f'Name: {self.name}',
f'Extent: {self.extent}'
])
def __bool__(self) -> bool:
return bool(self.lines())
def clear(self) -> None:
r"""Clear a `SectionBase`
Notes
-----
Resets the section to its default state
"""
self.raw = ''
self.extent = None # type: ignore[assignment]
self._lines = []
self.items = None
self.seen_headers = {}
return
def lines(self, headings_only: bool = False) -> list[tuple[SourceRange, str, Verdict]]:
r"""Retrieve the lines for this section
Parameters
----------
headings_only : optional
retrieve only lines which are definitely headings
Returns
-------
lines :
the iterable of lines
"""
if headings_only:
return [(loc, line, verdict) for loc, line, verdict in self._lines if verdict > 0]
return self._lines
def consume(self, data: Collection[tuple[SourceRange, str, Verdict]]) -> list[tuple[SourceRange, str, Verdict]]:
r"""Consume raw data and add it to the section
Parameters
----------
data :
the container of raw data to consume
Returns
-------
data :
the consumed (and now empty) container
"""
if data:
self.lines().extend(data)
self.raw = '\n'.join(s for _, s, _ in self.lines())
self.extent = SourceRange.from_locations(self.lines()[0][0].start, self.lines()[-1][0].end)
return []
def _do_setup(self, docstring: PetscDocStringImpl, inspect_line: LineInspector[PetscDocStringImpl]) -> None:
r"""Do the actual setting up
Parameters
----------
docstring :
the `PetscDocString` instance to use to log any errors
inspect_line
a callback to inspect each line
Notes
-----
This is intended to be called by derived classes that wish to set a custom line inspector
"""
seen = collections.defaultdict(list)
for loc, line, verdict in self.lines():
if verdict > 0:
possible_header = line.split(':' if ':' in line else None, maxsplit=1)[0].strip()
seen[possible_header.casefold()].append(
docstring.make_source_range(possible_header, line, loc.start.line)
)
# let each section type determine if this line is useful
inspect_line(docstring, loc, line, verdict)
self.seen_headers = dict(seen)
return
def setup(self, docstring: PetscDocStringImpl) -> None:
r"""Set up a section
Parameters
----------
docstring :
the `PetscDocString` instance to use to log any errors
Notes
-----
This routine is used to populate `self.items` and any other metadata before checking. As a rule,
subclasses should do minimal error handling or checking here, gathering only the necessary
statistics and data.
"""
self._do_setup(docstring, lambda ds, loc, line, verdict: None)
return
def barren(self) -> bool:
r"""Is this section empty?
Returns
-------
ret :
True if the sectino is empty, False otherwise
"""
lines = self.lines()
return not self.items and sum(not line.strip() for _, line, _ in lines) == len(lines) - 1
@staticmethod
def transform(text: str) -> str:
r"""Transform a text into the expected title form
Parameters
----------
text :
the string to transform
Returns
-------
text :
the transformed string
Notes
-----
This is used for the equality check:
```
if self.transform(text) in self.titles:
# text could be a title if transformed
else:
# text needs further work
```
"""
return text.title()
def check_indent_allowed(self) -> bool:
r"""Whether this section should check for indentation
Returns
-------
ret :
True if the linter should check indentation, False otherwise
Notes
-----
This is used to disable indentation checking in e.g. source code blocks, but the implementation
is very incomplete and likely needs a lot more work...
"""
return True
def _check_required_section_found(self, docstring: PetscDocStringImpl) -> None:
r"""Check a required section does in fact exist
Parameters
----------
docstring :
the `PetscDocString` owning the section
"""
if not self and self.required:
diag = self.diags.section_header_missing
mess = f'Required section \'{self.titles[0]}\' not found'
docstring.add_diagnostic_from_source_range(
Diagnostic.Kind.ERROR, diag, mess, docstring.extent, highlight=False
)
return
def _check_section_is_not_barren(self, docstring: PetscDocStringImpl) -> None:
r"""Check that a section isn't just a solitary header out on its own
Parameters
----------
docstring :
the `PetscDocString` owning the section
"""
if self and self.barren():
diag = self.diags.section_barren
highlight = len(self.lines()) == 1
mess = 'Section appears to be empty; while I\'m all for a good mystery, you should probably elaborate here'
docstring.add_diagnostic_from_source_range(
Diagnostic.Kind.ERROR, diag, mess, self.extent, highlight=highlight
)
return
def _check_section_header_spelling(self, linter: Linter, docstring: PetscDocStringImpl, headings: Optional[Sequence[tuple[SourceRange, str, Verdict]]] = None, transform: Optional[Callable[[str], str]] = None) -> None:
r"""Check that a section header is correctly spelled and formatted.
Parameters
----------
linter :
the `Linter` instance to log any errors with
docstring :
the `PetscDocString` that owns this section
headings : optional
a set of heading lines
transform : optional
the text transformation function to transform a line into a heading
Notes
-----
Sections may be found through fuzzy matching so this check asserts that a particular heading is
actually correct.
"""
if headings is None:
headings = self.lines(headings_only=True)
if transform is None:
transform = self.transform
diag = self.diags.section_header_spelling
for loc, text, verdict in headings:
before, sep, _ = text.partition(':')
if not sep:
# missing colon, but if we are at this point then we are pretty sure it is a
# header, so we assume the first word is the header
before, _, _ = docstring.guess_heading(text)
heading = before.strip()
if any(t in heading for t in self.titles):
continue
heading_loc = docstring.make_source_range(heading, text, loc.start.line)
correct = transform(heading)
if heading != correct and any(t in correct for t in self.titles):
docstring.add_diagnostic_from_source_range(
Diagnostic.Kind.ERROR, diag,
f'Invalid header spelling. Expected \'{correct}\' found \'{heading}\'',
heading_loc, patch=Patch(heading_loc, correct)
)
continue
try:
matchname = difflib.get_close_matches(correct, self.titles, n=1)[0]
except IndexError:
warn_diag = docstring.make_diagnostic(
Diagnostic.Kind.WARNING, self.diags.section_header_unknown,
f'Unknown section \'{heading}\'', heading_loc
)
prevline = docstring.extent.start.line - 1
loc = SourceRange.from_positions(
docstring.cursor.translation_unit, prevline, 1, prevline, -1
)
warn_diag.add_note(
f'If this is indeed a valid heading, you can locally silence this diagnostic by adding \'// PetscClangLinter pragma disable: {DiagnosticManager.make_command_line_flag(warn_diag.flag)}\' on its own line before the docstring'
).add_note(
Diagnostic.make_message_from_formattable(
'add it here', crange=loc, highlight=False
),
location=loc.start
)
docstring.add_diagnostic(warn_diag)
else:
docstring.add_diagnostic_from_source_range(
Diagnostic.Kind.ERROR, diag,
f'Unknown section header \'{heading}\', assuming you meant \'{matchname}\'',
heading_loc, patch=Patch(heading_loc, matchname)
)
return
def _check_duplicate_headers(self, docstring: PetscDocStringImpl) -> None:
r"""Check that a particular heading is not repeated within the docstring
Parameters
----------
docstring :
the `PetscDocString` owning the section
"""
for heading, where in self.seen_headers.items():
if len(where) <= 1:
continue
lasti = len(where) - 1
src_list = []
nbefore = 2
nafter = 0
prev_line_begin = 0
for i, loc in enumerate(where):
startline = loc.start.line
if i:
nbefore = startline - prev_line_begin - 1
if i == lasti:
nafter = 2
src_list.append(loc.formatted(num_before_context=nbefore, num_after_context=nafter, trim=False))
prev_line_begin = startline
mess = "Multiple '{}' subheadings. Much like Highlanders, there can only be one:\n{}".format(
self.transform(self.name), '\n'.join(src_list)
)
docstring.add_diagnostic(
Diagnostic(Diagnostic.Kind.ERROR, self.diags.section_header_unique, mess, self.extent.start)
)
return
def _check_section_header_solitary(self, docstring: PetscDocStringImpl, headings: Optional[Sequence[tuple[SourceRange, str, Verdict]]] = None) -> None:
r"""Check that a section appears solitarily on its line, i.e. that there is no other text after ':'
Parameters
----------
docstring :
the `PetscDocString` owning the section
headings : optional
a set of heading lines
"""
if not self.solitary:
return
if headings is None:
headings = self.lines(headings_only=True)
for loc, text, verdict in headings:
_, sep, after = text.partition(':')
if not sep:
head, _, _ = docstring.guess_heading(text)
_, sep, after = text.partition(head)
assert sep
if after.strip():
diag = self.diags.section_header_solitary
mess = 'Heading must appear alone on a line, any content must be on the next line'
docstring.add_diagnostic_from_source_range(
Diagnostic.Kind.ERROR, diag, mess, docstring.make_source_range(after, text, loc.start.line)
)
break
return
def check(self, linter: Linter, cursor: Cursor, docstring: PetscDocStringImpl) -> None:
r"""Perform a set of base checks for this instance
Parameters
----------
linter :
the `Linter` instance to log any errors with
cursor :
the cursor to which the docstring this section belongs to
docstring :
the docstring to which this section belongs
"""
self._check_required_section_found(docstring)
self._check_section_header_spelling(linter, docstring)
self._check_section_is_not_barren(docstring)
self._check_duplicate_headers(docstring)
self._check_section_header_solitary(docstring)
return
@DiagnosticManager.register(
('matching-symbol-name','Verify that description matches the symbol name'),
('missing-description','Verify that a synopsis has a description'),
('wrong-description-separator','Verify that synopsis uses the right description separator'),
('verbose-description','Verify that synopsis descriptions don\'t drone on and on'),
('macro-explicit-synopsis-missing','Verify that macro docstrings have an explicit synopsis section'),
('macro-explicit-synopsis-valid-header','Verify that macro docstrings with explicit synopses have the right header include')
)
class Synopsis(SectionBase):
_header_include_finder = re.compile(r'\s*#\s*include\s*[<"](.*)[>"]')
_sowing_include_finder = re.compile(
_header_include_finder.pattern + r'\s*/\*\s*I\s*(["<].*[>"])\s*I\s*\*/.*'
)
NameItemType: TypeAlias = Tuple[Optional[SourceRange], str]
BlurbItemType: TypeAlias = List[Tuple[SourceRange, str]]
ItemsType = TypedDict(
'ItemsType',
{
'name' : NameItemType,
'blurb' : BlurbItemType,
}
)
items: ItemsType
diags: DiagnosticMap # satisfy type checkers
class Inspector:
__slots__ = 'cursor_name', 'lo_name', 'found_description', 'found_synopsis', 'capturing', 'items'
class CaptureKind(enum.Enum):
NONE = enum.auto()
DESCRIPTION = enum.auto()
SYNOPSIS = enum.auto()
cursor_name: str
lo_name: str
found_description: bool
found_synopsis: bool
capturing: CaptureKind
items: Synopsis.ItemsType
def __init__(self, cursor: Cursor) -> None:
self.cursor_name = cursor.name
self.lo_name = self.cursor_name.casefold()
self.found_description = False
self.found_synopsis = False
self.capturing = self.CaptureKind.NONE
self.items = {
'name' : (None, ''),
'blurb' : []
}
return
def __call__(self, ds: PetscDocStringImpl, loc: SourceRange, line: str, verdict: Verdict) -> None:
r"""Look for the '<NAME> - description' block in a synopsis"""
if self.found_description:
return
startline = loc.start.line
if self.capturing == self.CaptureKind.NONE:
pre, dash, rest = line.partition('-')
if dash:
rest = rest.strip()
elif self.lo_name in line.casefold():
pre = self.cursor_name
rest = line.split(self.cursor_name, maxsplit=1)[1].strip()
else:
return
item = pre.strip()
self.items['name'] = (ds.make_source_range(item, line, startline), item)
self.items['blurb'].append((ds.make_source_range(rest, line, startline), rest))
self.capturing = self.CaptureKind.DESCRIPTION # now capture the rest of the blurb
else:
assert self.capturing == self.CaptureKind.DESCRIPTION, 'Mixing blurb and synopsis capture?'
if item := line.strip():
self.items['blurb'].append((ds.make_source_range(item, line, startline), item))
else:
self.capturing = self.CaptureKind.NONE
self.found_description = True
return
@classmethod
def __diagnostic_prefix__(cls, *flags):
return DiagnosticManager.flag_prefix(super())('synopsis', *flags)
def __init__(self, *args, **kwargs) -> None:
r"""Construct a `Synopsis`
Parameters
----------
*args :
additional positional arguments to `SectionBase.__init__()`
**kwargs :
additional keyword arguments to `SectionBase.__init__()`
"""
kwargs.setdefault('name', 'synopsis')
kwargs.setdefault('required', True)
kwargs.setdefault('keywords', ('Synopsis', 'Not Collective'))
super().__init__(*args, **kwargs)
return
def barren(self) -> bool:
return False # synoposis is never barren
def _check_symbol_matches_synopsis_name(self: SynopsisImpl, docstring: PetscDocStringImpl, cursor: Cursor, loc: SourceRange, symbol: str) -> None:
r"""Ensure that the name of the symbol matches that of the name in the custom synopsis (if provided)
Parameters
----------
docstring :
the `PetscDocString` this section belongs to
cursor :
the cursor this docstring belongs to
loc :
the source range for symbol
symbol :
the name of the symbol in the docstring description
Notes
-----
Checks:
/*@
FooBar - ....
^^^^^^------------------x-- Checks that these match
... ________|
@*/ vvvvvv
PetscErrorCode FooBar(...)
"""
if symbol != cursor.name:
if len(difflib.get_close_matches(symbol, [cursor.name], n=1)):
mess = f"Docstring name '{symbol}' does not match symbol. Assuming you meant '{cursor.name}'"
patch = Patch(loc, cursor.name)
else:
mess = f"Docstring name '{symbol}' does not match symbol name '{cursor.name}'"
patch = None
docstring.add_diagnostic_from_source_range(
Diagnostic.Kind.ERROR, self.diags.matching_symbol_name, mess, loc, patch=patch
)
return
def _check_synopsis_description_separator(self: SynopsisImpl, docstring: PetscDocStringImpl, start_line: int) -> None:
r"""Ensure that the synopsis uses the proper separator
Parameters
----------
docstring :
the docstring this section belongs to
start_line :
the line number of the description
"""
for sloc, sline, _ in self.lines():
if sloc.start.line == start_line:
DescribableItem(sline, expected_sep='-').check(docstring, self, sloc)
break
return
def _check_blurb_length(self: SynopsisImpl, docstring: PetscDocStringImpl, cursor: Cursor, blurb_items: Synopsis.BlurbItemType) -> None:
r"""Ensure the blurb is not too wordy
Paramaters
----------
docstring :
the docstring this section belongs to
cursor :
the cursor this docstring belongs to
items :
the synopsis items
"""
total_blurb = [line for _, line in blurb_items]
word_count = sum(len(l.split()) for l in total_blurb)
char_count = sum(map(len, total_blurb))
max_char_count = 250
max_word_count = 40
if char_count > max_char_count and word_count > max_word_count:
mess = f"Synopsis for '{cursor.name}' is too long (must be at most {max_char_count} characters or {max_word_count} words), consider moving it to Notes. If you can't explain it simply, then you don't understand it well enough!"
docstring.add_diagnostic_from_source_range(
Diagnostic.Kind.ERROR, self.diags.verbose_description, mess, self.extent, highlight=False
)
return
def _syn_common_checks(self: SynopsisImpl, linter: Linter, cursor: Cursor, docstring: PetscDocStringImpl) -> None:
r"""Perform the common set of checks for all synopses
Parameters
----------
linter :
the `Linter` instance to log any errors with
cursor :
the cursor to which the docstring this section belongs to
docstring :
the docstring to which this section belongs
Notes
-----
Does not call `super().check()`! Therefore this should be used as the epilogue to your synopsis
checks, after any potential early returns
"""
items = self.items
name_loc, symbol_name = items['name']
assert name_loc is not None # pacify type checkers
self._check_symbol_matches_synopsis_name(docstring, cursor, name_loc, symbol_name)
self._check_synopsis_description_separator(docstring, name_loc.start.line)
self._check_blurb_length(docstring, cursor, items['blurb'])
return
@DiagnosticManager.register(
('alignment', 'Verify that parameter list entries are correctly white-space aligned'),
('prefix', 'Verify that parameter list entries begin with the correct prefix'),
('missing-description', 'Verify that parameter list entries have a description'),
('wrong-description-separator', 'Verify that parameter list entries use the right description separator'),
('solitary-parameter', 'Verify that each parameter has its own entry'),
)
class ParameterList(SectionBase):
__slots__ = ('prefixes', )
prefixes: Tuple[str, ...]
ItemsType: TypeAlias = Dict[int, List[Tuple[SourceRange, DescribableItem, int]]]
items: ItemsType
@classmethod
def __diagnostic_prefix__(cls, *flags):
return DiagnosticManager.flag_prefix(super())('param-list', *flags)
def __init__(self, *args, prefixes: Optional[tuple[str, ...]] = None, **kwargs) -> None:
r"""Construct a `ParamaterList`
Parameters
----------
prefixes : optional
a set of prefixes which the parameter list starts with
"""
if prefixes is None:
prefixes = ('+', '.', '-')
self.prefixes = prefixes
kwargs.setdefault('name', 'parameters')
super().__init__(*args, **kwargs)
return
def check_indent_allowed(self) -> bool:
r"""Whether `ParameterList`s should check for indentation
Returns
-------
ret :
Always True
"""
return False
def check_aligned_descriptions(self, ds: PetscDocStringImpl, group: Sequence[tuple[SourceRange, DescribableItem, int]]) -> None:
r"""Verify that the position of the '-' before the description for each argument is aligned
Parameters
----------
ds :
the `PetscDocString` instance which owns this section
group :
the item group to check, each entry is a tuple of src_range for the item, the `DescribableItem`
instance, and the arg len for that item
"""
align_diag = self.diags.alignment
group_args = [item.arg for _, item, _ in group]
lens = list(map(len, group_args))
max_arg_len = max(lens, default=0)
longest_arg = group_args[lens.index(max_arg_len)] if lens else 'NO ARGS'
for loc, item, _ in group:
pre = item.prefix
arg = item.arg
descr = item.description
text = item.text
fixed = f'{pre} {arg:{max_arg_len}} - {descr}'
try:
diff_index = next(
i for i, (a1, a2) in enumerate(itertools.zip_longest(text, fixed)) if a1 != a2
)
except StopIteration:
assert text == fixed # equal
continue
if diff_index <= text.find(pre):
mess = f'Prefix \'{pre}\' must be indented to column (1)'
elif diff_index <= text.find(arg):
mess = f'Argument \'{arg}\' must be 1 space from prefix \'{pre}\''
else:
mess = f'Description \'{textwrap.shorten(descr, width=35)}\' must be aligned to 1 space from longest (valid) argument \'{longest_arg}\''
eloc = ds.make_source_range(text[diff_index:], text, loc.end.line)
ds.add_diagnostic_from_source_range(
Diagnostic.Kind.ERROR, align_diag, mess, eloc, patch=Patch(eloc, fixed[diff_index:])
)
return
def setup(self, ds: PetscDocStringImpl, parameter_list_prefix_check: Optional[Callable[[ParameterList, PetscDocString, ItemsType], ItemsType]] = None) -> None:
r"""Set up a `ParmeterList`
Parameters
----------
ds :
the `PetscDocString` instance for this section
parameters_list_prefix_check : optional
a callable to check the prefixes of each item
"""
groups: collections.defaultdict[
int,
list[tuple[SourceRange, DescribableItem, int]]
] = collections.defaultdict(list)
subheading = 0
def inspector(ds: PetscDocStringImpl, loc: SourceRange, line: str, verdict: Verdict) -> None:
if not line or line.isspace():
return
if verdict > 0 and len(groups.keys()):
nonlocal subheading
subheading += 1
lstp = line.lstrip()
# .ve and .vb might trip up the prefix detection since they start with '.'
if lstp.startswith(self.prefixes) and not lstp.startswith(('.vb', '.ve')):
item = DescribableItem(line, prefixes=self.prefixes)
groups[subheading].append((loc, item, item.arglen()))
return
super()._do_setup(ds, inspector)
items = dict(groups)
if parameter_list_prefix_check is not None:
assert callable(parameter_list_prefix_check)
items = parameter_list_prefix_check(self, ds, items)
self.items = items
return
def _check_opt_starts_with(self, docstring: PetscDocStringImpl, item: tuple[SourceRange, DescribableItem, int], entity_name: str, char: str) -> None:
r"""Check an option starts with the given prefix
Parameters
----------
docstring :
the `PetscDocString` that owns this section
item :
the `SourceRange`, `DescribableItem`, arg len triple for the line
entity_name :
the name of the entity to which the param list belongs, e.g. 'function' or 'enum'
char :
the prefix character
"""
loc, descr_item, _ = item
pre = descr_item.prefix
if pre != char:
eloc = docstring.make_source_range(pre, descr_item.text, loc.start.line)
mess = f'{entity_name} parameter list entry must start with \'{char}\''
docstring.add_diagnostic_from_source_range(
Diagnostic.Kind.ERROR, self.diags.prefix, mess, eloc, patch=Patch(eloc, char)
)
return
def _check_prefixes(self, docstring: PetscDocStringImpl) -> None:
r"""Check all prefixes in the section for validity
Parameters
----------
docstring :
the `PetscDocString` instance owning this section
"""
for key, opts in sorted(self.items.items()):
lopts = len(opts)
assert lopts >= 1, f'number of options {lopts} < 1, key: {key}, items: {self.items}'
if lopts == 1:
# only 1 option, should start with '.'
self._check_opt_starts_with(docstring, opts[0], 'Solitary', '.')
else:
# more than 1, should be '+', then however many '.', then last is '-'
self._check_opt_starts_with(docstring, opts[0], 'First multi', '+')
for opt in opts[1:-1]:
self._check_opt_starts_with(docstring, opt, 'Multi', '.')
self._check_opt_starts_with(docstring, opts[-1], 'Last multi', '-')
return
def check(self, linter: Linter, cursor: Cursor, docstring: PetscDocStringImpl) -> None:
r"""Perform all checks for this param list
Parameters
----------
linter :
the `Linter` instance to log any errors with
cursor :
the cursor to which the docstring this section belongs to
docstring :
the docstring to which this section belongs
"""
super().check(linter, cursor, docstring)
self._check_prefixes(docstring)
return
class Prose(SectionBase):
ItemsType: TypeAlias = Dict[int, Tuple[Tuple[SourceRange, str], List[Tuple[SourceRange, str]]]]
items: ItemsType
@classmethod
def __diagnostic_prefix__(cls, *flags):
return DiagnosticManager.flag_prefix(super())('prose', *flags)
def setup(self, ds: PetscDocStringImpl) -> None:
r"""Set up a `Prose`
Parameters
----------
ds :
the `PetscDocString` instance for this section
Raises
------
ParsingError
if a subheading does not exist yet??
"""
subheading = 0
self.items = {}
def inspector(ds: PetscDocStringImpl, loc: SourceRange, line: str, verdict: Verdict) -> None:
if verdict > 0:
head, _, rest = line.partition(':')
head = head.strip()
assert head, f'No heading in PROSE section?\n\n{loc.formatted(num_context=5)}'
if self.items.keys():
nonlocal subheading
subheading += 1
start_line = loc.start.line
self.items[subheading] = (
(ds.make_source_range(head, line, start_line), head),
[(ds.make_source_range(rest, line, start_line), rest)] if rest else []
)
elif line.strip():
try:
self.items[subheading][1].append((loc, line))
except KeyError as ke:
raise ParsingError from ke
return
super()._do_setup(ds, inspector)
return
class VerbatimBlock(SectionBase):
ItemsType: TypeAlias = Dict[int, List[int]]
items: ItemsType
def setup(self, ds: PetscDocStringImpl) -> None:
r"""Set up a `VerbatimBlock`
Parameters
----------
ds :
the `PetscDocString` instance for this section
"""
items = {}
class Inspector:
__slots__ = 'codeblocks', 'startline'
codeblocks: int
startline: int
def __init__(self, startline: int) -> None:
self.codeblocks = 0
self.startline = startline
return
def __call__(self, ds: PetscDocStringImpl, loc: SourceRange, line: str, verdict: Verdict) -> None:
sub = self.codeblocks
lstrp = line.lstrip()
if lstrp.startswith('.vb'):
items[sub] = [loc.start.line - self.startline]
elif lstrp.startswith('.ve'):
assert len(items[sub]) == 1
items[sub].append(loc.start.line - self.startline + 1)
self.codeblocks += 1
return
super()._do_setup(ds, Inspector(self.extent.start.line if self else 0))
self.items = items
return
@DiagnosticManager.register(
('formatting', 'Verify that inline lists are correctly white-space formatted')
)
class InlineList(SectionBase):
ItemsEntry: TypeAlias = Tuple[Tuple[str, str], List[Tuple[SourceRange, str]]]
ItemsType: TypeAlias = Tuple[ItemsEntry, ...]
items: ItemsType
def __init__(self, *args, **kwargs) -> None:
r"""Construct an `InlineList`
Parameters
----------
*args :
additional positional parameters to `SectionBase.__init__()`
**kwargs :
additional keywords parameters to `SectionBase.__init__()`
"""
kwargs.setdefault('solitary', False)
super().__init__(*args, **kwargs)
return
@classmethod
def __diagnostic_prefix__(cls, *flags):
return DiagnosticManager.flag_prefix(super())('inline-list', *flags)
def check_indent_allowed(self) -> bool:
r"""Whether this section should check for indentation
Returns
-------
ret :
always False
"""
return False
def setup(self, ds: PetscDocStringImpl) -> None:
r"""Set up an `InlineList`
Parameters
----------
ds :
the `PetscDocString` instance for this section
"""
items: list[InlineList.ItemsEntry] = []
titles = set(map(str.casefold, self.titles))
def inspector(ds: PetscDocStringImpl, loc: SourceRange, line: str, verdict: Verdict) -> None:
rest = (line.split(':', maxsplit=2)[1] if ':' in line else line).strip()
if not rest:
return
if ':' not in rest:
# try and see if this is one of the bad-egg lines where the heading is missing
# the colon
bad_title = next(filter(lambda t: t.casefold() in titles, rest.split()), None)
if bad_title:
# kind of a hack, we just erase the bad heading with whitespace so it isnt
# picked up below in the item detection
rest = rest.replace(bad_title, ' ' * len(bad_title))
start_line = loc.start.line
offset = 0
sub_items = []
for sub in filter(bool, map(str.strip, rest.split(','))):
subloc = ds.make_source_range(sub, line, start_line, offset=offset)
offset = subloc.end.column - 1
sub_items.append((subloc, sub))
if sub_items:
items.append(((line, rest), sub_items))
return
super()._do_setup(ds, inspector)
self.items = tuple(items)
return
def _check_whitespace_formatting(self, docstring: PetscDocStringImpl) -> None:
r"""Ensure that inline list ensures are on the same line and 1 space away from the title
Parameters
----------
docstring :
the `PetscDocString` which owns this section
"""
format_diag = self.diags.formatting
base_mess = f'{self.transform(self.name)} values must be (1) space away from colon not ({{}})'
for (line, line_after_colon), sub_items in self.items:
colon_idx = line.find(':')
if colon_idx < 0:
continue
correct_offset = colon_idx + 2
rest_idx = line.find(line_after_colon)
if rest_idx == correct_offset:
continue
nspaces = rest_idx - correct_offset
if rest_idx > correct_offset:
sub = ' ' * nspaces
offset = correct_offset
fix = ''
else:
sub = ':'
offset = colon_idx
fix = ': '
floc = docstring.make_source_range(sub, line, sub_items[0][0].start.line, offset=offset)
docstring.add_diagnostic_from_source_range(
Diagnostic.Kind.ERROR, format_diag, base_mess.format(nspaces + 1), floc, patch=Patch(floc, fix)
)
return
def check(self, linter: Linter, cursor: Cursor, docstring: PetscDocStringImpl) -> None:
r"""Perform all checks for this inline list
Parameters
----------
linter :
the `Linter` instance to log any errors with
cursor :
the cursor to which the docstring this section belongs to
docstring :
the docstring to which this section belongs
"""
super().check(linter, cursor, docstring)
self._check_whitespace_formatting(docstring)
return
|
89b5cddbd7de4db993529f1f342e9c25daf1af5d
|
fe4486e433edb71645adfff3c183b32f7cf2df43
|
/sqlacodegen/codegen.py
|
29498223b98346042e5ab0a4b1bfeee4c8e7752b
|
[
"MIT"
] |
permissive
|
ksindi/flask-sqlacodegen
|
f7d8af2d2767c97eec32758a8a4b9f3bf17ad80d
|
60797250801fc81fce17fe3e8d159973b71a25cc
|
refs/heads/master
| 2023-08-28T14:28:56.946789
| 2023-05-26T02:01:35
| 2023-05-26T02:01:35
| 18,734,623
| 295
| 66
|
NOASSERTION
| 2023-06-26T23:47:17
| 2014-04-13T17:06:26
|
Python
|
UTF-8
|
Python
| false
| false
| 31,073
|
py
|
codegen.py
|
"""Contains the code generation logic and helper functions."""
from __future__ import unicode_literals, division, print_function, absolute_import
from collections import defaultdict
from keyword import iskeyword
import inspect
import sys
import re
from sqlalchemy import (Enum, ForeignKeyConstraint, PrimaryKeyConstraint, CheckConstraint, UniqueConstraint, Table,
Column)
from sqlalchemy.schema import ForeignKey
from sqlalchemy.util import OrderedDict
from sqlalchemy.types import Boolean, String
import sqlalchemy
try:
from sqlalchemy.sql.expression import text, TextClause
except ImportError:
# SQLAlchemy < 0.8
from sqlalchemy.sql.expression import text, _TextClause as TextClause
_re_boolean_check_constraint = re.compile(r"(?:(?:.*?)\.)?(.*?) IN \(0, 1\)")
_re_column_name = re.compile(r'(?:(["`]?)(?:.*)\1\.)?(["`]?)(.*)\2')
_re_enum_check_constraint = re.compile(r"(?:(?:.*?)\.)?(.*?) IN \((.+)\)")
_re_enum_item = re.compile(r"'(.*?)(?<!\\)'")
_re_invalid_identifier = re.compile(r'[^a-zA-Z0-9_]' if sys.version_info[0] < 3 else r'(?u)\W')
_re_invalid_relationship = re.compile(r'[^a-zA-Z0-9._()\[\]{}= \'",]')
_re_first_cap = re.compile('(.)([A-Z][a-z]+)')
_re_all_cap = re.compile('([a-z0-9])([A-Z])')
_flask_prepend = 'db.'
_dataclass = False
class _DummyInflectEngine(object):
def singular_noun(self, noun):
return noun
def plural_noun(self, noun): # needed for backrefs
import inflect
inflect_engine = inflect.engine()
return inflect_engine.plural_noun(noun)
# In SQLAlchemy 0.x, constraint.columns is sometimes a list, on 1.x onwards, always a ColumnCollection
def _get_column_names(constraint):
if isinstance(constraint.columns, list):
return constraint.columns
return list(constraint.columns.keys())
def _convert_to_valid_identifier(name):
assert name, 'Identifier cannot be empty'
if name[0].isdigit() or iskeyword(name):
name = '_' + name
return _re_invalid_identifier.sub('_', name)
def _get_compiled_expression(statement):
"""Returns the statement in a form where any placeholders have been filled in."""
if isinstance(statement, TextClause):
return statement.text
dialect = statement._from_objects[0].bind.dialect
compiler = statement._compiler(dialect)
# Adapted from http://stackoverflow.com/a/5698357/242021
class LiteralCompiler(compiler.__class__):
def visit_bindparam(self, bindparam, within_columns_clause=False, literal_binds=False, **kwargs):
return super(LiteralCompiler, self).render_literal_bindparam(
bindparam, within_columns_clause=within_columns_clause,
literal_binds=literal_binds, **kwargs
)
compiler = LiteralCompiler(dialect, statement)
return compiler.process(statement)
def _get_constraint_sort_key(constraint):
if isinstance(constraint, CheckConstraint):
return 'C{0}'.format(constraint.sqltext)
return constraint.__class__.__name__[0] + repr(_get_column_names(constraint))
def _get_common_fk_constraints(table1, table2):
"""Returns a set of foreign key constraints the two tables have against each other."""
c1 = set(c for c in table1.constraints if isinstance(c, ForeignKeyConstraint) and
c.elements[0].column.table == table2)
c2 = set(c for c in table2.constraints if isinstance(c, ForeignKeyConstraint) and
c.elements[0].column.table == table1)
return c1.union(c2)
def _getargspec_init(method):
try:
return inspect.getfullargspec(method)
except TypeError:
if method is object.__init__:
return inspect.getfullargspec(lambda self: None)
else:
return inspect.getfullargspec(lambda self, *args, **kwargs: None)
def _render_column_type(coltype):
args = []
if isinstance(coltype, Enum):
args.extend(repr(arg) for arg in coltype.enums)
if coltype.name is not None:
args.append('name={0!r}'.format(coltype.name))
else:
# All other types
argspec = _getargspec_init(coltype.__class__.__init__)
defaults = dict(zip(argspec.args[-len(argspec.defaults or ()):], argspec.defaults or ()))
missing = object()
use_kwargs = False
for attr in argspec.args[1:]:
# Remove annoyances like _warn_on_bytestring
if attr.startswith('_'):
continue
value = getattr(coltype, attr, missing)
default = defaults.get(attr, missing)
if value is missing or value == default:
use_kwargs = True
elif use_kwargs:
args.append('{0}={1}'.format(attr, repr(value)))
else:
args.append(repr(value))
text = _flask_prepend + coltype.__class__.__name__
# In case of ENUM from sqlalchemy.dialects, the flask used db.Enum
if text == "db.ENUM":
text = "db.Enum"
if args:
text += '({0})'.format(', '.join(args))
return text
def _render_column(column, show_name):
kwarg = []
is_sole_pk = column.primary_key and len(column.table.primary_key) == 1
dedicated_fks = [c for c in column.foreign_keys if len(c.constraint.columns) == 1]
is_unique = any(isinstance(c, UniqueConstraint) and set(c.columns) == set([column])
for c in column.table.constraints)
is_unique = is_unique or any(i.unique and set(i.columns) == set([column]) for i in column.table.indexes)
has_index = any(set(i.columns) == set([column]) for i in column.table.indexes)
# Render the column type if there are no foreign keys on it or any of them points back to itself
render_coltype = not dedicated_fks or any(fk.column is column for fk in dedicated_fks)
if column.key != column.name:
kwarg.append('key')
if column.primary_key:
kwarg.append('primary_key')
if not column.nullable and not is_sole_pk:
kwarg.append('nullable')
if is_unique:
column.unique = True
kwarg.append('unique')
elif has_index:
column.index = True
kwarg.append('index')
if column.server_default:
server_default = 'server_default=' + _flask_prepend + 'FetchedValue()'
comment = getattr(column, 'comment', None)
return _flask_prepend + 'Column({0})'.format(', '.join(
([repr(column.name)] if show_name else []) +
([_render_column_type(column.type)] if render_coltype else []) +
[_render_constraint(x) for x in dedicated_fks] +
[repr(x) for x in column.constraints] +
['{0}={1}'.format(k, repr(getattr(column, k))) for k in kwarg] +
([server_default] if column.server_default else []) +
(['info={!r}'.format(comment)] if comment else [])
))
def _render_constraint(constraint):
def render_fk_options(*opts):
opts = [repr(opt) for opt in opts]
for attr in 'ondelete', 'onupdate', 'deferrable', 'initially', 'match':
value = getattr(constraint, attr, None)
if value:
opts.append('{0}={1!r}'.format(attr, value))
return ', '.join(opts)
if isinstance(constraint, ForeignKey):
remote_column = '{0}.{1}'.format(constraint.column.table.fullname, constraint.column.name)
return _flask_prepend + 'ForeignKey({0})'.format(render_fk_options(remote_column))
elif isinstance(constraint, ForeignKeyConstraint):
local_columns = _get_column_names(constraint)
remote_columns = ['{0}.{1}'.format(fk.column.table.fullname, fk.column.name)
for fk in constraint.elements]
return _flask_prepend + 'ForeignKeyConstraint({0})'.format(render_fk_options(local_columns, remote_columns))
elif isinstance(constraint, CheckConstraint):
return _flask_prepend + 'CheckConstraint({0!r})'.format(_get_compiled_expression(constraint.sqltext))
elif isinstance(constraint, UniqueConstraint):
columns = [repr(col.name) for col in constraint.columns]
return _flask_prepend + 'UniqueConstraint({0})'.format(', '.join(columns))
def _underscore(name):
"""Converts CamelCase to camel_case. See http://stackoverflow.com/questions/1175208"""
s1 = _re_first_cap.sub(r'\1_\2', name)
return _re_all_cap.sub(r'\1_\2', s1).lower()
def _is_model_descendant(model_a, model_b):
"""Check to see if model class A inherits from another model class B"""
if model_a.name == model_b.name:
return True
if not model_b.children:
return False
return any(_is_model_descendant(model_a, b) for b in model_b.children)
def _render_index(index):
columns = [repr(col.name) for col in index.columns]
return _flask_prepend + 'Index({0!r}, {1})'.format(index.name, ', '.join(columns))
class ImportCollector(OrderedDict):
def add_import(self, obj):
type_ = type(obj) if not isinstance(obj, type) else obj
pkgname = 'sqlalchemy' if type_.__name__ in sqlalchemy.__all__ else type_.__module__ # @UndefinedVariable
self.add_literal_import(pkgname, type_.__name__)
def add_literal_import(self, pkgname, name):
names = self.setdefault(pkgname, set())
names.add(name)
def render(self):
return '\n'.join('from {0} import {1}'.format(package, ', '.join(sorted(names)))
for package, names in self.items())
class Model(object):
def __init__(self, table):
super(Model, self).__init__()
self.table = table
self.schema = table.schema
# Adapt column types to the most reasonable generic types (ie. VARCHAR -> String)
for column in table.columns:
cls = column.type.__class__
for supercls in cls.__mro__:
if hasattr(supercls, '__visit_name__'):
cls = supercls
if supercls.__name__ != supercls.__name__.upper() and not supercls.__name__.startswith('_'):
break
column.type = column.type.adapt(cls)
def add_imports(self, collector):
if self.table.columns:
collector.add_import(Column)
for column in self.table.columns:
collector.add_import(column.type)
if column.server_default:
collector.add_literal_import('sqlalchemy.schema', 'FetchedValue')
for constraint in sorted(self.table.constraints, key=_get_constraint_sort_key):
if isinstance(constraint, ForeignKeyConstraint):
if len(constraint.columns) > 1:
collector.add_literal_import('sqlalchemy', 'ForeignKeyConstraint')
else:
collector.add_literal_import('sqlalchemy', 'ForeignKey')
elif isinstance(constraint, UniqueConstraint):
if len(constraint.columns) > 1:
collector.add_literal_import('sqlalchemy', 'UniqueConstraint')
elif not isinstance(constraint, PrimaryKeyConstraint):
collector.add_import(constraint)
for index in self.table.indexes:
if len(index.columns) > 1:
collector.add_import(index)
class ModelTable(Model):
def add_imports(self, collector):
super(ModelTable, self).add_imports(collector)
collector.add_import(Table)
def render(self):
met = ' metadata,' if _flask_prepend == '' else ''
text = 't_{0} = {1}Table(\n {0!r},{2}\n'.format(self.table.name, _flask_prepend, met)
for column in self.table.columns:
text += ' {0},\n'.format(_render_column(column, True))
for constraint in sorted(self.table.constraints, key=_get_constraint_sort_key):
if isinstance(constraint, PrimaryKeyConstraint):
continue
if isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint)) and len(constraint.columns) == 1:
continue
text += ' {0},\n'.format(_render_constraint(constraint))
for index in self.table.indexes:
if len(index.columns) > 1:
text += ' {0},\n'.format(_render_index(index))
if self.schema:
text += " schema='{0}',\n".format(self.schema)
return text.rstrip('\n,') + '\n)'
class ModelClass(Model):
parent_name = 'Base'
def __init__(self, table, association_tables, inflect_engine, detect_joined, collector):
super(ModelClass, self).__init__(table)
self.name = self._tablename_to_classname(table.name, inflect_engine)
self.children = []
self.attributes = OrderedDict()
# Assign attribute names for columns
for column in table.columns:
self._add_attribute(column.name, column)
if _dataclass:
if column.type.python_type.__module__ != 'builtins':
collector.add_literal_import(column.type.python_type.__module__, column.type.python_type.__name__)
# Add many-to-one relationships
pk_column_names = set(col.name for col in table.primary_key.columns)
for constraint in sorted(table.constraints, key=_get_constraint_sort_key):
if isinstance(constraint, ForeignKeyConstraint):
target_cls = self._tablename_to_classname(constraint.elements[0].column.table.name, inflect_engine)
if (detect_joined and self.parent_name == 'Base' and
set(_get_column_names(constraint)) == pk_column_names):
self.parent_name = target_cls
else:
relationship_ = ManyToOneRelationship(self.name, target_cls, constraint, inflect_engine)
self._add_attribute(relationship_.preferred_name, relationship_)
# Add many-to-many relationships
for association_table in association_tables:
fk_constraints = [c for c in association_table.constraints if isinstance(c, ForeignKeyConstraint)]
fk_constraints.sort(key=_get_constraint_sort_key)
target_cls = self._tablename_to_classname(fk_constraints[1].elements[0].column.table.name, inflect_engine)
relationship_ = ManyToManyRelationship(self.name, target_cls, association_table, inflect_engine)
self._add_attribute(relationship_.preferred_name, relationship_)
@staticmethod
def _tablename_to_classname(tablename, inflect_engine):
camel_case_name = ''.join(part[:1].upper() + part[1:] for part in re.split(r'_|-', tablename))
return inflect_engine.singular_noun(camel_case_name) or camel_case_name
def _add_attribute(self, attrname, value):
attrname = tempname = _convert_to_valid_identifier(attrname)
counter = 1
while tempname in self.attributes:
tempname = attrname + str(counter)
counter += 1
self.attributes[tempname] = value
return tempname
def add_imports(self, collector):
super(ModelClass, self).add_imports(collector)
if any(isinstance(value, Relationship) for value in self.attributes.values()):
collector.add_literal_import('sqlalchemy.orm', 'relationship')
for child in self.children:
child.add_imports(collector)
def render(self):
global _dataclass
text = 'class {0}({1}):\n'.format(self.name, self.parent_name)
if _dataclass:
text = '@dataclass\n' + text
text += ' __tablename__ = {0!r}\n'.format(self.table.name)
# Render constraints and indexes as __table_args__
table_args = []
for constraint in sorted(self.table.constraints, key=_get_constraint_sort_key):
if isinstance(constraint, PrimaryKeyConstraint):
continue
if isinstance(constraint, (ForeignKeyConstraint, UniqueConstraint)) and len(constraint.columns) == 1:
continue
table_args.append(_render_constraint(constraint))
for index in self.table.indexes:
if len(index.columns) > 1:
table_args.append(_render_index(index))
table_kwargs = {}
if self.schema:
table_kwargs['schema'] = self.schema
kwargs_items = ', '.join('{0!r}: {1!r}'.format(key, table_kwargs[key]) for key in table_kwargs)
kwargs_items = '{{{0}}}'.format(kwargs_items) if kwargs_items else None
if table_kwargs and not table_args:
text += ' __table_args__ = {0}\n'.format(kwargs_items)
elif table_args:
if kwargs_items:
table_args.append(kwargs_items)
if len(table_args) == 1:
table_args[0] += ','
text += ' __table_args__ = (\n {0}\n )\n'.format(',\n '.join(table_args))
# Render columns
text += '\n'
for attr, column in self.attributes.items():
if isinstance(column, Column):
show_name = attr != column.name
if _dataclass:
text += ' ' + attr + ' : ' + column.type.python_type.__name__ + '\n'
text += ' {0} = {1}\n'.format(attr, _render_column(column, show_name))
# Render relationships
if any(isinstance(value, Relationship) for value in self.attributes.values()):
text += '\n'
for attr, relationship in self.attributes.items():
if isinstance(relationship, Relationship):
text += ' {0} = {1}\n'.format(attr, relationship.render())
# Render subclasses
for child_class in self.children:
text += '\n\n' + child_class.render()
return text
class Relationship(object):
def __init__(self, source_cls, target_cls):
super(Relationship, self).__init__()
self.source_cls = source_cls
self.target_cls = target_cls
self.kwargs = OrderedDict()
self.backref_name = _underscore(self.source_cls)
def render(self):
text = _flask_prepend + 'relationship('
args = [repr(self.target_cls)]
if 'secondaryjoin' in self.kwargs:
text += '\n '
delimiter, end = ',\n ', '\n )'
else:
delimiter, end = ', ', ')'
args.extend([key + '=' + value for key, value in self.kwargs.items()])
return _re_invalid_relationship.sub('_', text + delimiter.join(args) + end)
def make_backref(self, relationships, classes):
backref = self.backref_name
original_backref = backref
# Check if backref already exists for relationship source_cls to target_cls and add suffix
suffix = 0
while (self.target_cls, backref) in [(x.target_cls, x.backref_name) for x in relationships]:
backref = original_backref + str('_{0}'.format(suffix))
suffix += 1
self.kwargs['backref'] = repr(backref)
# Check if any of the target_cls inherit from other target_cls
# If so, modify backref name of descendant
# "backref({0}, lazy='dynamic')".format(repr(backref))
for rel in [x for x in relationships if 'backref' in x.kwargs]:
if self.target_cls in classes and rel.target_cls in classes:
if _is_model_descendant(classes[self.target_cls], classes[rel.target_cls]):
self.backref_name = self.target_cls.lower() + '_' + backref
self.kwargs['backref'] = repr(self.backref_name)
if _is_model_descendant(classes[rel.target_cls], classes[self.target_cls]):
backref = rel.backref_name
rel.backref_name = rel.target_cls.lower() + '_' + backref
rel.kwargs['backref'] = repr(rel.backref_name)
class ManyToOneRelationship(Relationship):
def __init__(self, source_cls, target_cls, constraint, inflect_engine):
super(ManyToOneRelationship, self).__init__(source_cls, target_cls)
column_names = _get_column_names(constraint)
colname = column_names[0]
tablename = constraint.elements[0].column.table.name
if not colname.endswith('_id'):
self.preferred_name = inflect_engine.singular_noun(tablename) or tablename
else:
self.preferred_name = colname[:-3]
self.backref_name = inflect_engine.plural_noun(self.backref_name)
# Add uselist=False to One-to-One relationships
if any(isinstance(c, (PrimaryKeyConstraint, UniqueConstraint)) and
set(col.name for col in c.columns) == set(column_names)
for c in constraint.table.constraints):
self.kwargs['uselist'] = 'False'
# Handle self referential relationships
if source_cls == target_cls:
self.preferred_name = 'parent' if not colname.endswith('_id') else colname[:-3]
pk_col_names = [col.name for col in constraint.table.primary_key]
self.kwargs['remote_side'] = '[{0}]'.format(', '.join(pk_col_names))
# If the two tables share more than one foreign key constraint,
# SQLAlchemy needs an explicit primaryjoin to figure out which column(s) to join with
# common_fk_constraints = _get_common_fk_constraints(constraint.table, constraint.elements[0].column.table)
# if len(common_fk_constraints) > 1:
# self.kwargs['primaryjoin'] = "'{0}.{1} == {2}.{3}'".format(source_cls, constraint.columns[0], target_cls, constraint.elements[0].column.name)
if len(constraint.elements) > 1: # or
self.kwargs['primaryjoin'] = "'and_({0})'".format(', '.join(['{0}.{1} == {2}.{3}'.format(source_cls, k.parent.name, target_cls, k.column.name)
for k in constraint.elements]))
else:
self.kwargs['primaryjoin'] = "'{0}.{1} == {2}.{3}'".format(source_cls, column_names[0], target_cls,
constraint.elements[0].column.name)
class ManyToManyRelationship(Relationship):
def __init__(self, source_cls, target_cls, assocation_table, inflect_engine):
super(ManyToManyRelationship, self).__init__(source_cls, target_cls)
prefix = assocation_table.schema + '.' if assocation_table.schema is not None else ''
self.kwargs['secondary'] = repr(prefix + assocation_table.name)
constraints = [c for c in assocation_table.constraints if isinstance(c, ForeignKeyConstraint)]
constraints.sort(key=_get_constraint_sort_key)
colname = _get_column_names(constraints[1])[0]
tablename = constraints[1].elements[0].column.table.name
self.preferred_name = tablename if not colname.endswith('_id') else colname[:-3] + 's'
self.backref_name = inflect_engine.plural_noun(self.backref_name)
# Handle self referential relationships
if source_cls == target_cls:
self.preferred_name = 'parents' if not colname.endswith('_id') else colname[:-3] + 's'
pri_pairs = zip(_get_column_names(constraints[0]), constraints[0].elements)
sec_pairs = zip(_get_column_names(constraints[1]), constraints[1].elements)
pri_joins = ['{0}.{1} == {2}.c.{3}'.format(source_cls, elem.column.name, assocation_table.name, col)
for col, elem in pri_pairs]
sec_joins = ['{0}.{1} == {2}.c.{3}'.format(target_cls, elem.column.name, assocation_table.name, col)
for col, elem in sec_pairs]
self.kwargs['primaryjoin'] = (
repr('and_({0})'.format(', '.join(pri_joins))) if len(pri_joins) > 1 else repr(pri_joins[0]))
self.kwargs['secondaryjoin'] = (
repr('and_({0})'.format(', '.join(sec_joins))) if len(sec_joins) > 1 else repr(sec_joins[0]))
class CodeGenerator(object):
header = '# coding: utf-8'
footer = ''
def __init__(self, metadata, noindexes=False, noconstraints=False,
nojoined=False, noinflect=False, nobackrefs=False,
flask=False, ignore_cols=None, noclasses=False, nocomments=False, notables=False, dataclass=False):
super(CodeGenerator, self).__init__()
if noinflect:
inflect_engine = _DummyInflectEngine()
else:
import inflect
inflect_engine = inflect.engine()
# exclude these column names from consideration when generating association tables
_ignore_columns = ignore_cols or []
self.flask = flask
if not self.flask:
global _flask_prepend
_flask_prepend = ''
self.nocomments = nocomments
self.dataclass = dataclass
if self.dataclass:
global _dataclass
_dataclass = True
# Pick association tables from the metadata into their own set, don't process them normally
links = defaultdict(lambda: [])
association_tables = set()
for table in metadata.tables.values():
# Link tables have exactly two foreign key constraints and all columns are involved in them
# except for special columns like id, inserted, and updated
fk_constraints = [constr for constr in table.constraints if isinstance(constr, ForeignKeyConstraint)]
if len(fk_constraints) == 2 and all(col.foreign_keys for col in table.columns if col.name not in _ignore_columns):
association_tables.add(table.name)
tablename = sorted(fk_constraints, key=_get_constraint_sort_key)[0].elements[0].column.table.name
links[tablename].append(table)
# Iterate through the tables and create model classes when possible
self.models = []
self.collector = ImportCollector()
classes = {}
for table in sorted(metadata.tables.values(), key=lambda t: (t.schema or '', t.name)):
# Support for Alembic and sqlalchemy-migrate -- never expose the schema version tables
if table.name in ('alembic_version', 'migrate_version'):
continue
if noindexes:
table.indexes.clear()
if noconstraints:
table.constraints = set([table.primary_key])
table.foreign_keys.clear()
for col in table.columns:
col.foreign_keys.clear()
else:
# Detect check constraints for boolean and enum columns
for constraint in table.constraints.copy():
if isinstance(constraint, CheckConstraint):
sqltext = _get_compiled_expression(constraint.sqltext)
# Turn any integer-like column with a CheckConstraint like "column IN (0, 1)" into a Boolean
match = _re_boolean_check_constraint.match(sqltext)
if match:
colname = _re_column_name.match(match.group(1)).group(3)
table.constraints.remove(constraint)
table.c[colname].type = Boolean()
continue
# Turn any string-type column with a CheckConstraint like "column IN (...)" into an Enum
match = _re_enum_check_constraint.match(sqltext)
if match:
colname = _re_column_name.match(match.group(1)).group(3)
items = match.group(2)
if isinstance(table.c[colname].type, String):
table.constraints.remove(constraint)
if not isinstance(table.c[colname].type, Enum):
options = _re_enum_item.findall(items)
table.c[colname].type = Enum(*options, native_enum=False)
continue
# Only generate classes when notables is set to True
if notables:
model = ModelClass(table, links[table.name], inflect_engine, not nojoined, self.collector)
classes[model.name] = model
elif not table.primary_key or table.name in association_tables or noclasses:
# Only form model classes for tables that have a primary key and are not association tables
model = ModelTable(table)
elif not noclasses:
model = ModelClass(table, links[table.name], inflect_engine, not nojoined, self.collector)
classes[model.name] = model
self.models.append(model)
# collect imports for models only if flask is not specified
if not self.flask:
model.add_imports(self.collector)
# Nest inherited classes in their superclasses to ensure proper ordering
for model in classes.values():
if model.parent_name != 'Base':
classes[model.parent_name].children.append(model)
self.models.remove(model)
# If backrefs are allowed. Resolve any relationships conflicts where one
# target class might inherit from another
if not nobackrefs:
for model in classes.values():
visited = []
for relationship in model.attributes.values():
if isinstance(relationship, Relationship):
relationship.make_backref(visited, classes)
visited.append(relationship)
if self.flask:
# Add Flask-SQLAlchemy support
self.collector.add_literal_import('flask_sqlalchemy', 'SQLAlchemy')
parent_name = 'db.Model'
for model in classes.values():
if model.parent_name == 'Base':
model.parent_name = parent_name
else:
self.collector.add_literal_import('sqlalchemy.ext.declarative', 'declarative_base')
self.collector.add_literal_import('sqlalchemy', 'MetaData')
if self.dataclass:
self.collector.add_literal_import('dataclasses', 'dataclass')
def render(self, outfile=sys.stdout):
print(self.header, file=outfile)
# Render the collected imports
print(self.collector.render() + '\n\n', file=outfile)
if self.flask:
print('db = SQLAlchemy()', file=outfile)
else:
if any(isinstance(model, ModelClass) for model in self.models):
print('Base = declarative_base()\nmetadata = Base.metadata', file=outfile)
else:
print('metadata = MetaData()', file=outfile)
# Render the model tables and classes
for model in self.models:
print('\n\n', file=outfile)
print(model.render().rstrip('\n'), file=outfile)
if self.footer:
print(self.footer, file=outfile)
|
813b85626f3236c241dd211d12dd66f4d78d990a
|
e1e5c596f4ae06f8fddef063857fdd2961febb4d
|
/telnetlib3/tests/test_accessories.py
|
384065ae9ad10c17d159009b01b09898e43b896b
|
[
"BSD-3-Clause",
"ISC"
] |
permissive
|
jquast/telnetlib3
|
3ffcfd08f98c1bb90372273ce6cd5f5b922d3d50
|
5fbc6f723a6cb37651e782f6b35bd7e6cebabd5a
|
refs/heads/master
| 2023-07-29T21:34:56.668753
| 2023-07-23T16:03:53
| 2023-07-23T16:03:53
| 9,489,978
| 134
| 35
|
NOASSERTION
| 2023-06-16T17:28:24
| 2013-04-17T05:30:03
|
Python
|
UTF-8
|
Python
| false
| false
| 1,512
|
py
|
test_accessories.py
|
from telnetlib3.accessories import (
encoding_from_lang,
name_unicode,
eightbits,
)
def test_name_unicode():
""" Test mapping of ascii table to name_unicode result. """
given_expected = {
chr(0): r"^@",
chr(1): r"^A",
chr(26): r"^Z",
chr(29): r"^]",
chr(31): r"^_",
chr(32): r" ",
chr(126): r"~",
chr(127): r"^?",
chr(128): r"\x80",
chr(254): r"\xfe",
chr(255): r"\xff",
}
for given, expected in sorted(given_expected.items()):
# exercise,
result = name_unicode(given)
# verify,
assert result == expected
def test_eightbits():
""" Test mapping of bit values to binary appearance string. """
given_expected = {
0: "0b00000000",
127: "0b01111111",
128: "0b10000000",
255: "0b11111111",
}
for given, expected in sorted(given_expected.items()):
# exercise,
result = eightbits(given)
# verify
assert result == expected
def test_encoding_from_lang():
""" Test inference of encoding from LANG value. """
given_expected = {
"en_US.UTF-8@misc": "UTF-8",
"en_US.UTF-8": "UTF-8",
"abc.def": "def",
".def@ghi": "def",
"def@": "def",
"UTF-8": "UTF-8",
}
for given, expected in sorted(given_expected.items()):
# exercise,
result = encoding_from_lang(given)
# verify,
assert result == expected
|
f190fd0bd91da471cbbf6464f520b919c6f4065d
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/contrib/python/ipython/py2/IPython/testing/plugin/iptest.py
|
a75cab993fc684ab2ae8fd825d6e173fe1046f89
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
catboost/catboost
|
854c1a1f439a96f1ae6b48e16644be20aa04dba2
|
f5042e35b945aded77b23470ead62d7eacefde92
|
refs/heads/master
| 2023-09-01T12:14:14.174108
| 2023-09-01T10:01:01
| 2023-09-01T10:22:12
| 97,556,265
| 8,012
| 1,425
|
Apache-2.0
| 2023-09-11T03:32:32
| 2017-07-18T05:29:04
|
Python
|
UTF-8
|
Python
| false
| false
| 523
|
py
|
iptest.py
|
#!/usr/bin/env python
"""Nose-based test runner.
"""
from __future__ import print_function
from nose.core import main
from nose.plugins.builtin import plugins
from nose.plugins.doctests import Doctest
from . import ipdoctest
from .ipdoctest import IPDocTestRunner
if __name__ == '__main__':
print('WARNING: this code is incomplete!')
print()
pp = [x() for x in plugins] # activate all builtin plugins first
main(testRunner=IPDocTestRunner(),
plugins=pp+[ipdoctest.IPythonDoctest(),Doctest()])
|
e63109ab3dffc5e26f023c596a207daa508bfced
|
3083a4918f9a9a0670ce83566341eba04b290bc4
|
/kafka_utils/util/error.py
|
0e874da4d4649ab2433602f70d624f4ee548ad11
|
[
"Apache-2.0"
] |
permissive
|
Yelp/kafka-utils
|
b122c0aad0dfc225e948623ceaf466e7e63d9f91
|
def433ec4d07c60290d5dc937d3b4e5189eca9dc
|
refs/heads/master
| 2023-08-31T06:20:33.740273
| 2023-08-24T10:15:43
| 2023-08-24T10:15:43
| 55,727,134
| 322
| 142
|
Apache-2.0
| 2023-08-24T10:15:44
| 2016-04-07T20:50:50
|
Python
|
UTF-8
|
Python
| false
| false
| 1,945
|
py
|
error.py
|
# Copyright 2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from kafka.structs import OffsetCommitResponsePayload
class KafkaToolError(Exception):
"""Base class for kafka tool exceptions."""
pass
class ConfigurationError(KafkaToolError):
"""Error in configuration. For example: missing configuration file
or misformatted configuration."""
pass
class MissingConfigurationError(ConfigurationError):
"""Missing configuration file."""
pass
class InvalidConfigurationError(ConfigurationError):
"""Invalid configuration file."""
pass
class UnknownTopic(KafkaToolError):
"""Topic does not exist in kafka."""
pass
class UnknownPartitions(KafkaToolError):
"""Partition doesn't exist in kafka."""
pass
class OffsetCommitError(KafkaToolError):
"""Error during offset commit."""
def __init__(self, topic: str, partition: int, error: str) -> None:
self.topic = topic
self.partition = partition
self.error = error
def __eq__(self, other: object) -> bool:
assert isinstance(other, (OffsetCommitError, OffsetCommitResponsePayload))
if all([
self.topic == other.topic,
self.partition == other.partition,
self.error == other.error,
]):
return True
return False
class MaxConnectionAttemptsError(KafkaToolError):
"""Exceeded max connection attempts."""
pass
|
1856ab96ad9a4389d8ebe112a6df6641b6ab5ffe
|
043f6c509d32f7cf83174a9dedcb27575d6b29fe
|
/models/CIE/model_config.py
|
6ec59d14e39a09ed2866ecb5b2d30d83d7c71286
|
[
"LicenseRef-scancode-mulanpsl-2.0-en"
] |
permissive
|
Thinklab-SJTU/ThinkMatch
|
f07033e085d90496e796ce10e5ea6997c32ff3b9
|
cfd1c0d34b3614957a44ac73ed6090898a51c9f2
|
refs/heads/master
| 2023-07-19T13:40:37.929572
| 2023-07-19T05:55:45
| 2023-07-19T05:55:45
| 206,839,844
| 304
| 68
|
NOASSERTION
| 2023-07-19T05:55:46
| 2019-09-06T17:07:08
|
Python
|
UTF-8
|
Python
| false
| false
| 290
|
py
|
model_config.py
|
from easydict import EasyDict as edict
__C = edict()
model_cfg = __C
# CIE model options
__C.CIE = edict()
__C.CIE.FEATURE_CHANNEL = 512
__C.CIE.SK_ITER_NUM = 20
__C.CIE.SK_EPSILON = 1.0e-10
__C.CIE.SK_TAU = 0.005
__C.CIE.GNN_LAYER = 5
__C.CIE.GNN_FEAT = 1024
__C.CIE.CROSS_ITER = False
|
98d9cbef34b1e4968b9a63349b43e0e23b6b66fc
|
b2bcf07493b5a1bbfb7e29c7f13ac0b380cefead
|
/deprecated/scripts/linear_autoencoder_pca_tf.py
|
58b9d413935b9af6f6b37d407f12e00eb5f3fa84
|
[
"MIT"
] |
permissive
|
probml/pyprobml
|
e1952927bceec676eb414f9342470ba4b8e6703b
|
9cc22f3238ae092c2b9bff65d6283c93d38d25d4
|
refs/heads/master
| 2023-08-31T07:36:11.603301
| 2023-08-13T02:47:12
| 2023-08-13T02:47:12
| 65,924,871
| 6,263
| 1,598
|
MIT
| 2023-01-20T23:34:23
| 2016-08-17T16:42:24
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 2,211
|
py
|
linear_autoencoder_pca_tf.py
|
# Linear autoencoder (ie PCA) applied to a 3d dataset projecting to 2d
#https://github.com/ageron/handson-ml2/blob/master/17_autoencoders_and_gans.ipynb
import superimport
import numpy as np
import matplotlib.pyplot as plt
import os
figdir = "../figures"
def save_fig(fname): plt.savefig(os.path.join(figdir, fname))
import tensorflow as tf
from tensorflow import keras
from sklearn.decomposition import PCA
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
np.random.seed(4)
def generate_3d_data(m, w1=0.1, w2=0.3, noise=0.1):
angles = np.random.rand(m) * 3 * np.pi / 2 - 0.5
data = np.empty((m, 3))
data[:, 0] = np.cos(angles) + np.sin(angles)/2 + noise * np.random.randn(m) / 2
data[:, 1] = np.sin(angles) * 0.7 + noise * np.random.randn(m) / 2
data[:, 2] = data[:, 0] * w1 + data[:, 1] * w2 + noise * np.random.randn(m)
return data
X_train = generate_3d_data(60)
X_train = X_train - X_train.mean(axis=0, keepdims=0)
np.random.seed(42)
tf.random.set_seed(42)
encoder = keras.models.Sequential([keras.layers.Dense(2, input_shape=[3])])
decoder = keras.models.Sequential([keras.layers.Dense(3, input_shape=[2])])
autoencoder = keras.models.Sequential([encoder, decoder])
autoencoder.compile(loss="mse", optimizer=keras.optimizers.SGD(lr=1.5))
history = autoencoder.fit(X_train, X_train, epochs=20)
codings = encoder.predict(X_train)
X = X_train
fig = plt.figure().gca(projection='3d')
fig.scatter(X[:,0], X[:,1], X[:,2], s=50, marker='o')
save_fig("linear-autoecoder-data3d.pdf")
plt.show()
fig = plt.figure(figsize=(4,3))
plt.plot(codings[:,0], codings[:, 1], "b.")
plt.xlabel("$z_1$", fontsize=18)
plt.ylabel("$z_2$", fontsize=18, rotation=0)
plt.grid(True)
save_fig("linear-autoencoder-embedding.pdf")
plt.show()
# PCA version
pca = PCA(n_components=2)
mu = np.mean(X_train, axis=0)
Xc = X_train - mu # center the data
pca.fit(Xc)
W = pca.components_.T # D*K
Z = np.dot(Xc, W) # N * K latent scores
Xrecon = np.dot(Z, W.T) + mu # N*D
fig = plt.figure(figsize=(4,3))
plt.plot(Z[:,0], Z[:, 1], "b.")
plt.xlabel("$z_1$", fontsize=18)
plt.ylabel("$z_2$", fontsize=18, rotation=0)
plt.grid(True)
save_fig("linear-autoencoder-pca.pdf")
plt.show()
|
5f480cb74df8e1cd26334118e35829102e1ad893
|
2b66e0b0d7543585cc6be4ab5da19ae528f0c41a
|
/kaggler/const.py
|
8df2ec66721cd6bded2f8a7315d3377a50f9003d
|
[
"MIT"
] |
permissive
|
jeongyoonlee/Kaggler
|
84896f0da4ac0c8440dbffffbecde272859c0614
|
736622e2a59461c69dc3dce87c2fdce8ea45a242
|
refs/heads/master
| 2023-08-21T01:04:57.019400
| 2023-02-18T00:46:47
| 2023-02-18T00:46:47
| 29,987,631
| 786
| 188
|
MIT
| 2023-02-18T00:46:49
| 2015-01-28T20:51:13
|
Python
|
UTF-8
|
Python
| false
| false
| 46
|
py
|
const.py
|
RANDOM_SEED = 42
SEC_PER_MIN = 60
EPS = 1e-15
|
8bc2954a01b18c7dbd4c66ddb0cb7bc2efaf6aaf
|
eda1a85f7948a4232b6ee55c81211235cf135e70
|
/tests/test_mapping.py
|
e37afa377c8dcd1b44cce6a8e9e1b7349ca34544
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
kinnala/scikit-fem
|
b37ceae412db77eeb83b2ef5a74aaeceb65e84d8
|
eb6c86d1ee6d6867c702edaea87a66facb24b534
|
refs/heads/master
| 2023-09-01T01:45:53.206323
| 2023-08-28T19:11:35
| 2023-08-28T19:11:35
| 115,345,426
| 355
| 77
|
BSD-3-Clause
| 2023-09-01T21:23:55
| 2017-12-25T14:57:10
|
Python
|
UTF-8
|
Python
| false
| false
| 3,785
|
py
|
test_mapping.py
|
import unittest
import numpy as np
from skfem.mesh import MeshHex, MeshQuad, MeshTri
from skfem.element import ElementHex1, ElementQuad1, ElementHex2
from skfem.assembly import FacetBasis
from skfem.mapping import MappingMortar
class TestIsoparamNormals(unittest.TestCase):
"""Test that normals on x[i] == 0 are correct."""
mesh = MeshHex
elem = ElementHex1
def runTest(self):
m = self.mesh().refined()
e = self.elem()
fb = FacetBasis(m, e)
x = fb.global_coordinates().value
eps = 1e-6
for itr in range(m.p.shape[0]):
case = (x[itr] < eps) * (x[itr] > -eps)
for jtr in range(m.p.shape[0]):
normals = fb.normals.value[jtr][case]
if itr == jtr:
self.assertTrue((normals == -1).all())
else:
self.assertTrue((np.abs(normals) < 1e-14).all())
class TestIsoparamNormalsQuad(TestIsoparamNormals):
mesh = MeshQuad
elem = ElementQuad1
class TestIsoparamNormalsHex2(TestIsoparamNormals):
elem = ElementHex2
class TestInverseMapping(unittest.TestCase):
"""Test that inverse mapping works for non-rectangular elements."""
element = ElementQuad1
def initialize_meshes(self):
m0 = MeshQuad()
m = MeshQuad([[0, 1, 1, 0],
[0, .9, 1, 1]],
m0.t)
return m
def within_refelem(self, y):
return ((np.abs(y) < 1. + 1e-12).all()
and (np.abs(y) > 0. - 1e-12).all())
def runTest(self):
m = self.initialize_meshes()
e = self.element()
fb = FacetBasis(m, e)
x = fb.mapping.G(fb.X, find=fb.find)
Y0 = fb.mapping.invF(x, tind=fb.mesh.f2t[0, fb.find])
assert self.within_refelem(Y0)
class TestInverseMappingHex(TestInverseMapping):
element = ElementHex1
def initialize_meshes(self):
m0 = MeshHex()
m = MeshHex(np.array([[0., 0., 0.],
[0., 0., 1.],
[0., 1., 0.],
[1., 0.7, 0.7],
[0., 1., 1.],
[1., 0., 1.],
[1., 1., 0.],
[1., 1., 1.]]).T, m0.t)
return m
class TestInverseMappingHex2(TestInverseMappingHex):
"""This should be equivalent to TestInverseMappingHex."""
element = ElementHex2
class TestMortarPair(unittest.TestCase):
"""Check that mapped points match."""
mesh1_type = MeshTri
mesh2_type = MeshTri
nrefs1 = 2
nrefs2 = 3
translate_y = 0.0
def init_meshes(self):
m1 = self.mesh1_type().refined(self.nrefs1)
m2 = self.mesh2_type().refined(self.nrefs2).translated((1.0, self.translate_y))
return m1, m2
def runTest(self):
m1, m2 = self.init_meshes()
mp = MappingMortar.init_2D(m1, m2,
m1.facets_satisfying(lambda x: x[0] == 1.),
m2.facets_satisfying(lambda x: x[0] == 1.),
np.array([0., 1.]))
test_points = np.array([np.linspace(0., 1., 7)])
self.assertTrue((mp.G(test_points) -
mp.G(test_points) < 1e-10).all())
class TestMortarPairTriQuad(TestMortarPair):
mesh1_type = MeshTri
mesh2_type = MeshQuad
class TestMortarPairQuadQuad(TestMortarPair):
mesh1_type = MeshQuad
mesh2_type = MeshQuad
class TestMortarPairNoMatch1(TestMortarPair):
mesh1_type = MeshQuad
mesh2_type = MeshTri
translate_y = 0.1
class TestMortarPairNoMatch2(TestMortarPair):
mesh1_type = MeshQuad
mesh2_type = MeshTri
translate_y = -np.pi / 10.
|
881bce5c21a24509c830b2e62bdff0a94c09cac3
|
3dc647cd07a7361ed401e40d2b7cce8c826c8f6c
|
/Lib/test/test_sysconfig.py
|
6db1442980a338b288c1ee0592f79b00f3abf9bf
|
[
"Python-2.0",
"CC-BY-4.0",
"MIT"
] |
permissive
|
RustPython/RustPython
|
5ddce4a9848b9de8c041ffd2634f83c0105d3f39
|
b864e5da1f18897fc884180b7093df5aa170024f
|
refs/heads/main
| 2023-09-04T12:38:29.458699
| 2023-09-03T12:33:42
| 2023-09-03T12:33:42
| 135,201,145
| 15,815
| 1,302
|
MIT
| 2023-09-14T08:11:45
| 2018-05-28T19:27:01
|
Rust
|
UTF-8
|
Python
| false
| false
| 23,065
|
py
|
test_sysconfig.py
|
import unittest
import sys
import os
import subprocess
import shutil
from copy import copy
from test.support import (
captured_stdout, PythonSymlink, requires_subprocess, is_wasi
)
from test.support.import_helper import import_module
from test.support.os_helper import (TESTFN, unlink, skip_unless_symlink,
change_cwd)
from test.support.warnings_helper import check_warnings
import sysconfig
from sysconfig import (get_paths, get_platform, get_config_vars,
get_path, get_path_names, _INSTALL_SCHEMES,
get_default_scheme, get_scheme_names, get_config_var,
_expand_vars, _get_preferred_schemes, _main)
import _osx_support
HAS_USER_BASE = sysconfig._HAS_USER_BASE
class TestSysConfig(unittest.TestCase):
def setUp(self):
super(TestSysConfig, self).setUp()
self.sys_path = sys.path[:]
# patching os.uname
if hasattr(os, 'uname'):
self.uname = os.uname
self._uname = os.uname()
else:
self.uname = None
self._set_uname(('',)*5)
os.uname = self._get_uname
# saving the environment
self.name = os.name
self.platform = sys.platform
self.version = sys.version
self.sep = os.sep
self.join = os.path.join
self.isabs = os.path.isabs
self.splitdrive = os.path.splitdrive
self._config_vars = sysconfig._CONFIG_VARS, copy(sysconfig._CONFIG_VARS)
self._added_envvars = []
self._changed_envvars = []
for var in ('MACOSX_DEPLOYMENT_TARGET', 'PATH'):
if var in os.environ:
self._changed_envvars.append((var, os.environ[var]))
else:
self._added_envvars.append(var)
def tearDown(self):
sys.path[:] = self.sys_path
self._cleanup_testfn()
if self.uname is not None:
os.uname = self.uname
else:
del os.uname
os.name = self.name
sys.platform = self.platform
sys.version = self.version
os.sep = self.sep
os.path.join = self.join
os.path.isabs = self.isabs
os.path.splitdrive = self.splitdrive
sysconfig._CONFIG_VARS = self._config_vars[0]
sysconfig._CONFIG_VARS.clear()
sysconfig._CONFIG_VARS.update(self._config_vars[1])
for var, value in self._changed_envvars:
os.environ[var] = value
for var in self._added_envvars:
os.environ.pop(var, None)
super(TestSysConfig, self).tearDown()
def _set_uname(self, uname):
self._uname = os.uname_result(uname)
def _get_uname(self):
return self._uname
def _cleanup_testfn(self):
path = TESTFN
if os.path.isfile(path):
os.remove(path)
elif os.path.isdir(path):
shutil.rmtree(path)
def test_get_path_names(self):
self.assertEqual(get_path_names(), sysconfig._SCHEME_KEYS)
def test_get_paths(self):
scheme = get_paths()
default_scheme = get_default_scheme()
wanted = _expand_vars(default_scheme, None)
wanted = sorted(wanted.items())
scheme = sorted(scheme.items())
self.assertEqual(scheme, wanted)
def test_get_path(self):
config_vars = get_config_vars()
if os.name == 'nt':
# On Windows, we replace the native platlibdir name with the
# default so that POSIX schemes resolve correctly
config_vars = config_vars | {'platlibdir': 'lib'}
for scheme in _INSTALL_SCHEMES:
for name in _INSTALL_SCHEMES[scheme]:
expected = _INSTALL_SCHEMES[scheme][name].format(**config_vars)
self.assertEqual(
os.path.normpath(get_path(name, scheme)),
os.path.normpath(expected),
)
def test_get_default_scheme(self):
self.assertIn(get_default_scheme(), _INSTALL_SCHEMES)
def test_get_preferred_schemes(self):
expected_schemes = {'prefix', 'home', 'user'}
# Windows.
os.name = 'nt'
schemes = _get_preferred_schemes()
self.assertIsInstance(schemes, dict)
self.assertEqual(set(schemes), expected_schemes)
# Mac and Linux, shared library build.
os.name = 'posix'
schemes = _get_preferred_schemes()
self.assertIsInstance(schemes, dict)
self.assertEqual(set(schemes), expected_schemes)
# Mac, framework build.
os.name = 'posix'
sys.platform = 'darwin'
sys._framework = True
self.assertIsInstance(schemes, dict)
self.assertEqual(set(schemes), expected_schemes)
# NOTE: RUSTPYTHON this is hardcoded to 'python', we're set up for failure.
@unittest.expectedFailure
def test_posix_venv_scheme(self):
# The following directories were hardcoded in the venv module
# before bpo-45413, here we assert the posix_venv scheme does not regress
binpath = 'bin'
incpath = 'include'
libpath = os.path.join('lib',
'python%d.%d' % sys.version_info[:2],
'site-packages')
# Resolve the paths in prefix
binpath = os.path.join(sys.prefix, binpath)
incpath = os.path.join(sys.prefix, incpath)
libpath = os.path.join(sys.prefix, libpath)
self.assertEqual(binpath, sysconfig.get_path('scripts', scheme='posix_venv'))
self.assertEqual(libpath, sysconfig.get_path('purelib', scheme='posix_venv'))
# The include directory on POSIX isn't exactly the same as before,
# but it is "within"
sysconfig_includedir = sysconfig.get_path('include', scheme='posix_venv')
self.assertTrue(sysconfig_includedir.startswith(incpath + os.sep))
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
def test_nt_venv_scheme(self):
# The following directories were hardcoded in the venv module
# before bpo-45413, here we assert the posix_venv scheme does not regress
binpath = 'Scripts'
incpath = 'Include'
libpath = os.path.join('Lib', 'site-packages')
# Resolve the paths in prefix
binpath = os.path.join(sys.prefix, binpath)
incpath = os.path.join(sys.prefix, incpath)
libpath = os.path.join(sys.prefix, libpath)
self.assertEqual(binpath, sysconfig.get_path('scripts', scheme='nt_venv'))
self.assertEqual(incpath, sysconfig.get_path('include', scheme='nt_venv'))
self.assertEqual(libpath, sysconfig.get_path('purelib', scheme='nt_venv'))
def test_venv_scheme(self):
if sys.platform == 'win32':
self.assertEqual(
sysconfig.get_path('scripts', scheme='venv'),
sysconfig.get_path('scripts', scheme='nt_venv')
)
self.assertEqual(
sysconfig.get_path('include', scheme='venv'),
sysconfig.get_path('include', scheme='nt_venv')
)
self.assertEqual(
sysconfig.get_path('purelib', scheme='venv'),
sysconfig.get_path('purelib', scheme='nt_venv')
)
else:
self.assertEqual(
sysconfig.get_path('scripts', scheme='venv'),
sysconfig.get_path('scripts', scheme='posix_venv')
)
self.assertEqual(
sysconfig.get_path('include', scheme='venv'),
sysconfig.get_path('include', scheme='posix_venv')
)
self.assertEqual(
sysconfig.get_path('purelib', scheme='venv'),
sysconfig.get_path('purelib', scheme='posix_venv')
)
def test_get_config_vars(self):
cvars = get_config_vars()
self.assertIsInstance(cvars, dict)
self.assertTrue(cvars)
def test_get_platform(self):
# windows XP, 32bits
os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Intel)]')
sys.platform = 'win32'
self.assertEqual(get_platform(), 'win32')
# windows XP, amd64
os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Amd64)]')
sys.platform = 'win32'
self.assertEqual(get_platform(), 'win-amd64')
# macbook
os.name = 'posix'
sys.version = ('2.5 (r25:51918, Sep 19 2006, 08:49:13) '
'\n[GCC 4.0.1 (Apple Computer, Inc. build 5341)]')
sys.platform = 'darwin'
self._set_uname(('Darwin', 'macziade', '8.11.1',
('Darwin Kernel Version 8.11.1: '
'Wed Oct 10 18:23:28 PDT 2007; '
'root:xnu-792.25.20~1/RELEASE_I386'), 'PowerPC'))
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
'-fwrapv -O3 -Wall -Wstrict-prototypes')
maxint = sys.maxsize
try:
sys.maxsize = 2147483647
self.assertEqual(get_platform(), 'macosx-10.3-ppc')
sys.maxsize = 9223372036854775807
self.assertEqual(get_platform(), 'macosx-10.3-ppc64')
finally:
sys.maxsize = maxint
self._set_uname(('Darwin', 'macziade', '8.11.1',
('Darwin Kernel Version 8.11.1: '
'Wed Oct 10 18:23:28 PDT 2007; '
'root:xnu-792.25.20~1/RELEASE_I386'), 'i386'))
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3'
get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g '
'-fwrapv -O3 -Wall -Wstrict-prototypes')
maxint = sys.maxsize
try:
sys.maxsize = 2147483647
self.assertEqual(get_platform(), 'macosx-10.3-i386')
sys.maxsize = 9223372036854775807
self.assertEqual(get_platform(), 'macosx-10.3-x86_64')
finally:
sys.maxsize = maxint
# macbook with fat binaries (fat, universal or fat64)
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.4'
get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-fat')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-intel')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-fat3')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-universal')
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3')
self.assertEqual(get_platform(), 'macosx-10.4-fat64')
for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
_osx_support._remove_original_values(get_config_vars())
get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3' % arch)
self.assertEqual(get_platform(), 'macosx-10.4-%s' % arch)
# linux debian sarge
os.name = 'posix'
sys.version = ('2.3.5 (#1, Jul 4 2007, 17:28:59) '
'\n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)]')
sys.platform = 'linux2'
self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
'#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))
self.assertEqual(get_platform(), 'linux-i686')
# XXX more platforms to tests here
# TODO: RUSTPYTHON
@unittest.expectedFailure
@unittest.skipIf(is_wasi, "Incompatible with WASI mapdir and OOT builds")
def test_get_config_h_filename(self):
config_h = sysconfig.get_config_h_filename()
self.assertTrue(os.path.isfile(config_h), config_h)
def test_get_scheme_names(self):
wanted = ['nt', 'posix_home', 'posix_prefix', 'posix_venv', 'nt_venv', 'venv']
if HAS_USER_BASE:
wanted.extend(['nt_user', 'osx_framework_user', 'posix_user'])
self.assertEqual(get_scheme_names(), tuple(sorted(wanted)))
@skip_unless_symlink
@requires_subprocess()
def test_symlink(self): # Issue 7880
with PythonSymlink() as py:
cmd = "-c", "import sysconfig; print(sysconfig.get_platform())"
self.assertEqual(py.call_real(*cmd), py.call_link(*cmd))
def test_user_similar(self):
# Issue #8759: make sure the posix scheme for the users
# is similar to the global posix_prefix one
base = get_config_var('base')
if HAS_USER_BASE:
user = get_config_var('userbase')
# the global scheme mirrors the distinction between prefix and
# exec-prefix but not the user scheme, so we have to adapt the paths
# before comparing (issue #9100)
adapt = sys.base_prefix != sys.base_exec_prefix
for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
global_path = get_path(name, 'posix_prefix')
if adapt:
global_path = global_path.replace(sys.exec_prefix, sys.base_prefix)
base = base.replace(sys.exec_prefix, sys.base_prefix)
elif sys.base_prefix != sys.prefix:
# virtual environment? Likewise, we have to adapt the paths
# before comparing
global_path = global_path.replace(sys.base_prefix, sys.prefix)
base = base.replace(sys.base_prefix, sys.prefix)
if HAS_USER_BASE:
user_path = get_path(name, 'posix_user')
expected = os.path.normpath(global_path.replace(base, user, 1))
# bpo-44860: platlib of posix_user doesn't use sys.platlibdir,
# whereas posix_prefix does.
if name == 'platlib':
# Replace "/lib64/python3.11/site-packages" suffix
# with "/lib/python3.11/site-packages".
py_version_short = sysconfig.get_python_version()
suffix = f'python{py_version_short}/site-packages'
expected = expected.replace(f'/{sys.platlibdir}/{suffix}',
f'/lib/{suffix}')
self.assertEqual(user_path, expected)
def test_main(self):
# just making sure _main() runs and returns things in the stdout
with captured_stdout() as output:
_main()
self.assertTrue(len(output.getvalue().split('\n')) > 0)
# TODO: RUSTPYTHON
@unittest.expectedFailure
@unittest.skipIf(sys.platform == "win32", "Does not apply to Windows")
def test_ldshared_value(self):
ldflags = sysconfig.get_config_var('LDFLAGS')
ldshared = sysconfig.get_config_var('LDSHARED')
self.assertIn(ldflags, ldshared)
@unittest.skipUnless(sys.platform == "darwin", "test only relevant on MacOSX")
@requires_subprocess()
def test_platform_in_subprocess(self):
my_platform = sysconfig.get_platform()
# Test without MACOSX_DEPLOYMENT_TARGET in the environment
env = os.environ.copy()
if 'MACOSX_DEPLOYMENT_TARGET' in env:
del env['MACOSX_DEPLOYMENT_TARGET']
p = subprocess.Popen([
sys.executable, '-c',
'import sysconfig; print(sysconfig.get_platform())',
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=env)
test_platform = p.communicate()[0].strip()
test_platform = test_platform.decode('utf-8')
status = p.wait()
self.assertEqual(status, 0)
self.assertEqual(my_platform, test_platform)
# Test with MACOSX_DEPLOYMENT_TARGET in the environment, and
# using a value that is unlikely to be the default one.
env = os.environ.copy()
env['MACOSX_DEPLOYMENT_TARGET'] = '10.1'
p = subprocess.Popen([
sys.executable, '-c',
'import sysconfig; print(sysconfig.get_platform())',
],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
env=env)
test_platform = p.communicate()[0].strip()
test_platform = test_platform.decode('utf-8')
status = p.wait()
self.assertEqual(status, 0)
self.assertEqual(my_platform, test_platform)
@unittest.expectedFailureIf(sys.platform != "win32", "TODO: RUSTPYTHON")
@unittest.skipIf(is_wasi, "Incompatible with WASI mapdir and OOT builds")
def test_srcdir(self):
# See Issues #15322, #15364.
srcdir = sysconfig.get_config_var('srcdir')
self.assertTrue(os.path.isabs(srcdir), srcdir)
self.assertTrue(os.path.isdir(srcdir), srcdir)
if sysconfig._PYTHON_BUILD:
# The python executable has not been installed so srcdir
# should be a full source checkout.
Python_h = os.path.join(srcdir, 'Include', 'Python.h')
self.assertTrue(os.path.exists(Python_h), Python_h)
# <srcdir>/PC/pyconfig.h always exists even if unused on POSIX.
pyconfig_h = os.path.join(srcdir, 'PC', 'pyconfig.h')
self.assertTrue(os.path.exists(pyconfig_h), pyconfig_h)
pyconfig_h_in = os.path.join(srcdir, 'pyconfig.h.in')
self.assertTrue(os.path.exists(pyconfig_h_in), pyconfig_h_in)
elif os.name == 'posix':
makefile_dir = os.path.dirname(sysconfig.get_makefile_filename())
# Issue #19340: srcdir has been realpath'ed already
makefile_dir = os.path.realpath(makefile_dir)
self.assertEqual(makefile_dir, srcdir)
def test_srcdir_independent_of_cwd(self):
# srcdir should be independent of the current working directory
# See Issues #15322, #15364.
srcdir = sysconfig.get_config_var('srcdir')
with change_cwd(os.pardir):
srcdir2 = sysconfig.get_config_var('srcdir')
self.assertEqual(srcdir, srcdir2)
# TODO: RUSTPYTHON
@unittest.expectedFailure
@unittest.skipIf(sysconfig.get_config_var('EXT_SUFFIX') is None,
'EXT_SUFFIX required for this test')
def test_EXT_SUFFIX_in_vars(self):
import _imp
if not _imp.extension_suffixes():
self.skipTest("stub loader has no suffixes")
vars = sysconfig.get_config_vars()
self.assertEqual(vars['EXT_SUFFIX'], _imp.extension_suffixes()[0])
@unittest.skipUnless(sys.platform == 'linux' and
hasattr(sys.implementation, '_multiarch'),
'multiarch-specific test')
def test_triplet_in_ext_suffix(self):
ctypes = import_module('ctypes')
import platform, re
machine = platform.machine()
suffix = sysconfig.get_config_var('EXT_SUFFIX')
if re.match('(aarch64|arm|mips|ppc|powerpc|s390|sparc)', machine):
self.assertTrue('linux' in suffix, suffix)
if re.match('(i[3-6]86|x86_64)$', machine):
if ctypes.sizeof(ctypes.c_char_p()) == 4:
expected_suffixes = 'i386-linux-gnu.so', 'x86_64-linux-gnux32.so', 'i386-linux-musl.so'
else: # 8 byte pointer size
expected_suffixes = 'x86_64-linux-gnu.so', 'x86_64-linux-musl.so'
self.assertTrue(suffix.endswith(expected_suffixes),
f'unexpected suffix {suffix!r}')
# TODO: RUSTPYTHON
@unittest.expectedFailure
@unittest.skipUnless(sys.platform == 'darwin', 'OS X-specific test')
def test_osx_ext_suffix(self):
suffix = sysconfig.get_config_var('EXT_SUFFIX')
self.assertTrue(suffix.endswith('-darwin.so'), suffix)
class MakefileTests(unittest.TestCase):
# TODO: RUSTPYTHON
@unittest.expectedFailure
@unittest.skipIf(sys.platform.startswith('win'),
'Test is not Windows compatible')
@unittest.skipIf(is_wasi, "Incompatible with WASI mapdir and OOT builds")
def test_get_makefile_filename(self):
makefile = sysconfig.get_makefile_filename()
self.assertTrue(os.path.isfile(makefile), makefile)
def test_parse_makefile(self):
self.addCleanup(unlink, TESTFN)
with open(TESTFN, "w") as makefile:
print("var1=a$(VAR2)", file=makefile)
print("VAR2=b$(var3)", file=makefile)
print("var3=42", file=makefile)
print("var4=$/invalid", file=makefile)
print("var5=dollar$$5", file=makefile)
print("var6=${var3}/lib/python3.5/config-$(VAR2)$(var5)"
"-x86_64-linux-gnu", file=makefile)
vars = sysconfig._parse_makefile(TESTFN)
self.assertEqual(vars, {
'var1': 'ab42',
'VAR2': 'b42',
'var3': 42,
'var4': '$/invalid',
'var5': 'dollar$5',
'var6': '42/lib/python3.5/config-b42dollar$5-x86_64-linux-gnu',
})
if __name__ == "__main__":
unittest.main()
|
7e89e9b51872074275d0ddab40d35cb4317b3f03
|
689a78e08c957abc02ea5f89fb657b1f78f88b6e
|
/tools/waymo_tracking/test.py
|
db14135162284103677a52f6ab4dfbc87be932a4
|
[
"MIT",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
tianweiy/CenterPoint
|
2bb9a7def8d4bf87b66af2e3b671736eae6fa275
|
d3a248fa56db2601860d576d5934d00fee9916eb
|
refs/heads/master
| 2023-08-30T23:11:49.528882
| 2022-10-24T13:09:52
| 2022-10-24T13:09:52
| 274,006,091
| 1,692
| 476
|
MIT
| 2023-05-06T10:30:06
| 2020-06-22T00:32:05
|
Python
|
UTF-8
|
Python
| false
| false
| 7,812
|
py
|
test.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import json
import numpy as np
import time
import copy
import argparse
import copy
import json
import os
import numpy as np
from tools.waymo_tracking.tracker import PubTracker as Tracker
from tqdm import tqdm
import json
import time
from nuscenes.utils.geometry_utils import transform_matrix
import pickle
from pyquaternion import Quaternion
from det3d.datasets.waymo.waymo_common import _create_pd_detection
def parse_args():
parser = argparse.ArgumentParser(description="Tracking Evaluation")
parser.add_argument("--work_dir", help="the dir to save logs and tracking results")
parser.add_argument(
"--checkpoint", help="the dir to prediction file"
)
parser.add_argument(
"--info_path", type=str
)
parser.add_argument("--max_age", type=int, default=3)
parser.add_argument("--vehicle", type=float, default=0.8)
parser.add_argument("--pedestrian", type=float, default=0.4)
parser.add_argument("--cyclist", type=float, default=0.6)
parser.add_argument("--score_thresh", type=float, default=0.75)
args = parser.parse_args()
return args
def get_obj(path):
with open(path, 'rb') as f:
obj = pickle.load(f)
return obj
def veh_pos_to_transform(veh_pos):
"convert vehicle pose to two transformation matrix"
rotation = veh_pos[:3, :3]
tran = veh_pos[:3, 3]
global_from_car = transform_matrix(
tran, Quaternion(matrix=rotation), inverse=False
)
car_from_global = transform_matrix(
tran, Quaternion(matrix=rotation), inverse=True
)
return global_from_car, car_from_global
def reorganize_info(infos):
new_info = {}
for info in infos:
token = info['token']
new_info[token] = info
return new_info
def main():
args = parse_args()
print('Deploy OK')
max_dist = {
'VEHICLE': args.vehicle,
'PEDESTRIAN': args.pedestrian,
'CYCLIST': args.cyclist
}
tracker = Tracker(max_age=args.max_age, max_dist=max_dist, score_thresh=args.score_thresh)
with open(args.checkpoint, 'rb') as f:
predictions=pickle.load(f)
with open(args.info_path, 'rb') as f:
infos=pickle.load(f)
infos = reorganize_info(infos)
global_preds, detection_results = convert_detection_to_global_box(predictions, infos)
size = len(global_preds)
print("Begin Tracking {} frames\n".format(size))
predictions = {}
for i in tqdm(range(size)):
pred = global_preds[i]
token = pred['token']
# reset tracking after one video sequence
if pred['frame_id'] == 0:
tracker.reset()
last_time_stamp = pred['timestamp']
time_lag = (pred['timestamp'] - last_time_stamp)
last_time_stamp = pred['timestamp']
current_det = pred['global_boxs']
outputs = tracker.step_centertrack(current_det, time_lag)
tracking_ids = []
box_ids = []
for item in outputs:
if item['active'] == 0:
continue
box_ids.append(item['box_id'])
tracking_ids.append(item['tracking_id'])
# now reorder
detection = detection_results[token]
remained_box_ids = np.array(box_ids)
track_result = {}
# store box id
track_result['tracking_ids']= np.array(tracking_ids)
# store box parameter
track_result['box3d_lidar'] = detection['box3d_lidar'][remained_box_ids]
# store box label
track_result['label_preds'] = detection['label_preds'][remained_box_ids]
# store box score
track_result['scores'] = detection['scores'][remained_box_ids]
predictions[token] = track_result
os.makedirs(args.work_dir, exist_ok=True)
# save prediction files to args.work_dir
_create_pd_detection(predictions, infos, args.work_dir, tracking=True)
result_path = os.path.join(args.work_dir, 'tracking_pred.bin')
gt_path = os.path.join(args.work_dir, '../gt_preds.bin')
print("Use Waymo devkit or online server to evaluate the result")
print("After building the devkit, you can use the following command")
print("waymo-open-dataset/bazel-bin/waymo_open_dataset/metrics/tools/compute_tracking_metrics_main \
{} {} ".format(result_path, gt_path))
# os.system("waymo_open_dataset/metrics/tools/compute_tracking_metrics_main \
# {} {} ".format(result_path, gt_path))
def transform_box(box, pose):
"""Transforms 3d upright boxes from one frame to another.
Args:
box: [..., N, 7] boxes.
from_frame_pose: [...,4, 4] origin frame poses.
to_frame_pose: [...,4, 4] target frame poses.
Returns:
Transformed boxes of shape [..., N, 7] with the same type as box.
"""
transform = pose
heading = box[..., -1] + np.arctan2(transform[..., 1, 0], transform[..., 0,
0])
center = np.einsum('...ij,...nj->...ni', transform[..., 0:3, 0:3],
box[..., 0:3]) + np.expand_dims(
transform[..., 0:3, 3], axis=-2)
velocity = box[..., [6, 7]]
velocity = np.concatenate([velocity, np.zeros((velocity.shape[0], 1))], axis=-1) # add z velocity
velocity = np.einsum('...ij,...nj->...ni', transform[..., 0:3, 0:3],
velocity)[..., [0, 1]] # remove z axis
return np.concatenate([center, box[..., 3:6], velocity, heading[..., np.newaxis]], axis=-1)
def label_to_name(label):
if label == 0:
return "VEHICLE"
elif label == 1 :
return "PEDESTRIAN"
elif label == 2:
return "CYCLIST"
else:
raise NotImplemented()
def sort_detections(detections):
indices = []
for det in detections:
f = det['token']
seq_id = int(f.split("_")[1])
frame_id= int(f.split("_")[3][:-4])
idx = seq_id * 1000 + frame_id
indices.append(idx)
rank = list(np.argsort(np.array(indices)))
detections = [detections[r] for r in rank]
return detections
def convert_detection_to_global_box(detections, infos):
ret_list = []
detection_results = {} # copy.deepcopy(detections)
for token in tqdm(infos.keys()):
detection = detections[token]
detection_results[token] = copy.deepcopy(detection)
info = infos[token]
# pose = get_transform(info)
anno_path = info['anno_path']
ref_obj = get_obj(anno_path)
pose = np.reshape(ref_obj['veh_to_global'], [4, 4])
box3d = detection["box3d_lidar"].detach().clone().cpu().numpy()
labels = detection["label_preds"].detach().clone().cpu().numpy()
scores = detection['scores'].detach().clone().cpu().numpy()
box3d[:, -1] = -box3d[:, -1] - np.pi / 2
box3d[:, [3, 4]] = box3d[:, [4, 3]]
box3d = transform_box(box3d, pose)
frame_id = token.split('_')[3][:-4]
num_box = len(box3d)
anno_list =[]
for i in range(num_box):
anno = {
'translation': box3d[i, :3],
'velocity': box3d[i, [6, 7]],
'detection_name': label_to_name(labels[i]),
'score': scores[i],
'box_id': i
}
anno_list.append(anno)
ret_list.append({
'token': token,
'frame_id':int(frame_id),
'global_boxs': anno_list,
'timestamp': info['timestamp']
})
sorted_ret_list = sort_detections(ret_list)
return sorted_ret_list, detection_results
if __name__ == '__main__':
main()
|
1e497c9d6ddd82c288f7b937f755fd196940b498
|
6fdb4eaf5b0e6dbd7db4bf947547541e9aebf110
|
/api/tests/opentrons/protocol_runner/test_legacy_context_plugin.py
|
d7bb3fc9902f00da2944a7d1afca27331b96fb8a
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
Opentrons/opentrons
|
874321e01149184960eeaeaa31b1d21719a1ceda
|
026b523c8c9e5d45910c490efb89194d72595be9
|
refs/heads/edge
| 2023-09-02T02:51:49.579906
| 2023-08-31T16:02:45
| 2023-08-31T16:02:45
| 38,644,841
| 326
| 174
|
Apache-2.0
| 2023-09-14T21:47:20
| 2015-07-06T20:41:01
|
Python
|
UTF-8
|
Python
| false
| false
| 7,490
|
py
|
test_legacy_context_plugin.py
|
"""Tests for the PythonAndLegacyRunner's LegacyContextPlugin."""
import pytest
from anyio import to_thread
from decoy import Decoy, matchers
from datetime import datetime
from typing import Callable, cast
from opentrons.broker import Broker
from opentrons.equipment_broker import EquipmentBroker
from opentrons.commands.types import CommandMessage as LegacyCommand, PauseMessage
from opentrons.protocol_engine import (
StateView,
actions as pe_actions,
commands as pe_commands,
)
from opentrons.protocol_engine.resources.pipette_data_provider import (
LoadedStaticPipetteData,
)
from opentrons.protocol_runner.legacy_command_mapper import LegacyCommandMapper
from opentrons.protocol_runner.legacy_context_plugin import LegacyContextPlugin
from opentrons.protocol_runner.legacy_wrappers import (
LegacyLoadInfo,
LegacyLabwareLoadInfo,
)
from opentrons.types import DeckSlotName
from opentrons_shared_data.labware.dev_types import (
LabwareDefinition as LabwareDefinitionDict,
)
@pytest.fixture
def mock_broker(decoy: Decoy) -> Broker:
"""Get a mocked out LegacyProtocolContext dependency."""
return decoy.mock(cls=Broker)
@pytest.fixture
def mock_equipment_broker(decoy: Decoy) -> EquipmentBroker[LegacyLoadInfo]:
"""Get a mocked out LegacyProtocolContext dependency."""
return decoy.mock(cls=EquipmentBroker)
@pytest.fixture
def mock_legacy_command_mapper(decoy: Decoy) -> LegacyCommandMapper:
"""Get a mocked out LegacyCommandMapper dependency."""
return decoy.mock(cls=LegacyCommandMapper)
@pytest.fixture
def mock_state_view(decoy: Decoy) -> StateView:
"""Get a mock StateView."""
return decoy.mock(cls=StateView)
@pytest.fixture
def mock_action_dispatcher(decoy: Decoy) -> pe_actions.ActionDispatcher:
"""Get a mock ActionDispatcher."""
return decoy.mock(cls=pe_actions.ActionDispatcher)
@pytest.fixture
def subject(
mock_broker: Broker,
mock_equipment_broker: EquipmentBroker[LegacyLoadInfo],
mock_legacy_command_mapper: LegacyCommandMapper,
mock_state_view: StateView,
mock_action_dispatcher: pe_actions.ActionDispatcher,
) -> LegacyContextPlugin:
"""Get a configured LegacyContextPlugin with its dependencies mocked out."""
plugin = LegacyContextPlugin(
broker=mock_broker,
equipment_broker=mock_equipment_broker,
legacy_command_mapper=mock_legacy_command_mapper,
)
plugin._configure(state=mock_state_view, action_dispatcher=mock_action_dispatcher)
return plugin
async def test_broker_subscribe_unsubscribe(
decoy: Decoy,
mock_broker: Broker,
mock_equipment_broker: EquipmentBroker[LegacyLoadInfo],
subject: LegacyContextPlugin,
) -> None:
"""It should subscribe to the brokers on setup and unsubscribe on teardown."""
command_broker_unsubscribe: Callable[[], None] = decoy.mock()
equipment_broker_unsubscribe: Callable[[], None] = decoy.mock()
decoy.when(
mock_broker.subscribe(topic="command", handler=matchers.Anything())
).then_return(command_broker_unsubscribe)
decoy.when(
mock_equipment_broker.subscribe(callback=matchers.Anything())
).then_return(equipment_broker_unsubscribe)
subject.setup()
await subject.teardown()
decoy.verify(command_broker_unsubscribe())
decoy.verify(equipment_broker_unsubscribe())
async def test_command_broker_messages(
decoy: Decoy,
mock_broker: Broker,
mock_equipment_broker: EquipmentBroker[LegacyLoadInfo],
mock_legacy_command_mapper: LegacyCommandMapper,
mock_action_dispatcher: pe_actions.ActionDispatcher,
subject: LegacyContextPlugin,
) -> None:
"""It should dispatch commands from command broker messages."""
# Capture the function that the plugin sets up as its command broker callback.
# Also, ensure that all subscribe calls return an actual unsubscribe callable
# (instead of Decoy's default `None`) so subject.teardown() works.
command_handler_captor = matchers.Captor()
decoy.when(
mock_broker.subscribe(topic="command", handler=command_handler_captor)
).then_return(decoy.mock())
decoy.when(
mock_equipment_broker.subscribe(callback=matchers.Anything())
).then_return(decoy.mock())
subject.setup()
handler: Callable[[LegacyCommand], None] = command_handler_captor.value
legacy_command: PauseMessage = {
"$": "before",
"id": "message-id",
"name": "command.PAUSE",
"payload": {"userMessage": "hello", "text": "hello"},
"error": None,
}
engine_command = pe_commands.Custom(
id="command-id",
key="command-key",
status=pe_commands.CommandStatus.RUNNING,
createdAt=datetime(year=2021, month=1, day=1),
params=pe_commands.CustomParams(message="hello"), # type: ignore[call-arg]
)
decoy.when(
mock_legacy_command_mapper.map_command(command=legacy_command)
).then_return([pe_actions.UpdateCommandAction(engine_command)])
await to_thread.run_sync(handler, legacy_command)
await subject.teardown()
decoy.verify(
mock_action_dispatcher.dispatch(pe_actions.UpdateCommandAction(engine_command))
)
async def test_equipment_broker_messages(
decoy: Decoy,
mock_broker: Broker,
mock_equipment_broker: EquipmentBroker[LegacyLoadInfo],
mock_legacy_command_mapper: LegacyCommandMapper,
mock_action_dispatcher: pe_actions.ActionDispatcher,
subject: LegacyContextPlugin,
minimal_labware_def: LabwareDefinitionDict,
) -> None:
"""It should dispatch commands from equipment broker messages."""
# Capture the function that the plugin sets up as its labware load callback.
# Also, ensure that all subscribe calls return an actual unsubscribe callable
# (instead of Decoy's default `None`) so subject.teardown() works.
labware_handler_captor = matchers.Captor()
decoy.when(
mock_broker.subscribe(topic="command", handler=matchers.Anything())
).then_return(decoy.mock())
decoy.when(
mock_equipment_broker.subscribe(callback=labware_handler_captor)
).then_return(decoy.mock())
subject.setup()
handler: Callable[[LegacyLabwareLoadInfo], None] = labware_handler_captor.value
load_info = LegacyLabwareLoadInfo(
labware_definition=minimal_labware_def,
labware_namespace="some_namespace",
labware_load_name="some_load_name",
labware_display_name=None,
labware_version=123,
deck_slot=DeckSlotName.SLOT_1,
on_module=False,
offset_id=None,
)
engine_command = pe_commands.Custom(
id="command-id",
key="command-key",
status=pe_commands.CommandStatus.RUNNING,
createdAt=datetime(year=2021, month=1, day=1),
params=pe_commands.CustomParams(message="hello"), # type: ignore[call-arg]
)
pipette_config_action = pe_actions.AddPipetteConfigAction(
pipette_id="pipette-id",
serial_number="serial-number",
config=cast(LoadedStaticPipetteData, {"config": True}),
)
decoy.when(
mock_legacy_command_mapper.map_equipment_load(load_info=load_info)
).then_return((engine_command, pipette_config_action))
await to_thread.run_sync(handler, load_info)
await subject.teardown()
decoy.verify(
mock_action_dispatcher.dispatch(pipette_config_action),
mock_action_dispatcher.dispatch(pe_actions.UpdateCommandAction(engine_command)),
)
|
6f0220862230f3aecaf76ea6862a5d6a5fa9213f
|
796feb97223492c3b783caf96c8dbaef252dbc1b
|
/Chapter4/ch4_double_moving_average.py
|
2baaf56b6462a85c38ab3436cb94b93f0f337142
|
[
"MIT"
] |
permissive
|
PacktPublishing/Learn-Algorithmic-Trading
|
08b8139403b724c8ccad7aebf9ebc613498768a7
|
df2c7862b8c63595dd066071801556016f29cda8
|
refs/heads/master
| 2023-01-24T01:24:10.961522
| 2023-01-18T09:50:12
| 2023-01-18T09:50:12
| 227,788,202
| 701
| 260
|
MIT
| 2023-02-10T18:28:55
| 2019-12-13T08:06:53
|
Python
|
UTF-8
|
Python
| false
| false
| 1,996
|
py
|
ch4_double_moving_average.py
|
#!/bin/python3
import pandas as pd
import numpy as np
from pandas_datareader import data
import matplotlib.pyplot as plt
def load_financial_data(start_date, end_date,output_file):
try:
df = pd.read_pickle(output_file)
print('File data found...reading GOOG data')
except FileNotFoundError:
print('File not found...downloading the GOOG data')
df = data.DataReader('GOOG', 'yahoo', start_date, end_date)
df.to_pickle(output_file)
return df
goog_data=load_financial_data(start_date='2001-01-01',
end_date = '2018-01-01',
output_file='goog_data.pkl')
def double_moving_average(financial_data, short_window, long_window):
signals = pd.DataFrame(index=financial_data.index)
signals['signal'] = 0.0
signals['short_mavg'] = financial_data['Close'].\
rolling(window=short_window,
min_periods=1, center=False).mean()
signals['long_mavg'] = financial_data['Close'].\
rolling(window=long_window,
min_periods=1, center=False).mean()
signals['signal'][short_window:] =\
np.where(signals['short_mavg'][short_window:]
> signals['long_mavg'][short_window:], 1.0, 0.0)
signals['orders'] = signals['signal'].diff()
return signals
ts=double_moving_average(goog_data,20,100)
fig = plt.figure()
ax1 = fig.add_subplot(111, ylabel='Google price in $')
goog_data["Adj Close"].plot(ax=ax1, color='g', lw=.5)
ts["short_mavg"].plot(ax=ax1, color='r', lw=2.)
ts["long_mavg"].plot(ax=ax1, color='b', lw=2.)
ax1.plot(ts.loc[ts.orders== 1.0].index,
goog_data["Adj Close"][ts.orders == 1.0],
'^', markersize=7, color='k')
ax1.plot(ts.loc[ts.orders== -1.0].index,
goog_data["Adj Close"][ts.orders == -1.0],
'v', markersize=7, color='k')
plt.legend(["Price","Short mavg","Long mavg","Buy","Sell"])
plt.title("Double Moving Average Trading Strategy")
plt.show()
|
dfc5ffc958d4cfe14815c75d4de8ac0df2f83b38
|
f576f0ea3725d54bd2551883901b25b863fe6688
|
/sdk/cosmos/azure-mgmt-cosmosdb/azure/mgmt/cosmosdb/aio/operations/_mongo_db_resources_operations.py
|
03c854fa5bae5aeb7a30cb4d52b247bc92b86252
|
[
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] |
permissive
|
Azure/azure-sdk-for-python
|
02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c
|
c2ca191e736bb06bfbbbc9493e8325763ba990bb
|
refs/heads/main
| 2023-09-06T09:30:13.135012
| 2023-09-06T01:08:06
| 2023-09-06T01:08:06
| 4,127,088
| 4,046
| 2,755
|
MIT
| 2023-09-14T21:48:49
| 2012-04-24T16:46:12
|
Python
|
UTF-8
|
Python
| false
| false
| 260,140
|
py
|
_mongo_db_resources_operations.py
|
# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from io import IOBase
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._mongo_db_resources_operations import (
build_create_update_mongo_db_collection_request,
build_create_update_mongo_db_database_request,
build_create_update_mongo_role_definition_request,
build_create_update_mongo_user_definition_request,
build_delete_mongo_db_collection_request,
build_delete_mongo_db_database_request,
build_delete_mongo_role_definition_request,
build_delete_mongo_user_definition_request,
build_get_mongo_db_collection_request,
build_get_mongo_db_collection_throughput_request,
build_get_mongo_db_database_request,
build_get_mongo_db_database_throughput_request,
build_get_mongo_role_definition_request,
build_get_mongo_user_definition_request,
build_list_mongo_db_collection_partition_merge_request,
build_list_mongo_db_collections_request,
build_list_mongo_db_databases_request,
build_list_mongo_role_definitions_request,
build_list_mongo_user_definitions_request,
build_migrate_mongo_db_collection_to_autoscale_request,
build_migrate_mongo_db_collection_to_manual_throughput_request,
build_migrate_mongo_db_database_to_autoscale_request,
build_migrate_mongo_db_database_to_manual_throughput_request,
build_mongo_db_container_redistribute_throughput_request,
build_mongo_db_container_retrieve_throughput_distribution_request,
build_mongo_db_database_partition_merge_request,
build_mongo_db_database_redistribute_throughput_request,
build_mongo_db_database_retrieve_throughput_distribution_request,
build_retrieve_continuous_backup_information_request,
build_update_mongo_db_collection_throughput_request,
build_update_mongo_db_database_throughput_request,
)
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class MongoDBResourcesOperations: # pylint: disable=too-many-public-methods
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.cosmosdb.aio.CosmosDBManagementClient`'s
:attr:`mongo_db_resources` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
@distributed_trace
def list_mongo_db_databases(
self, resource_group_name: str, account_name: str, **kwargs: Any
) -> AsyncIterable["_models.MongoDBDatabaseGetResults"]:
"""Lists the MongoDB databases under an existing Azure Cosmos DB database account.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either MongoDBDatabaseGetResults or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.MongoDBDatabaseListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_mongo_db_databases_request(
resource_group_name=resource_group_name,
account_name=account_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_mongo_db_databases.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("MongoDBDatabaseListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_mongo_db_databases.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases"
}
@distributed_trace_async
async def get_mongo_db_database(
self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any
) -> _models.MongoDBDatabaseGetResults:
"""Gets the MongoDB databases under an existing Azure Cosmos DB database account with the provided
name.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: MongoDBDatabaseGetResults or the result of cls(response)
:rtype: ~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.MongoDBDatabaseGetResults] = kwargs.pop("cls", None)
request = build_get_mongo_db_database_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_mongo_db_database.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_mongo_db_database.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}"
}
async def _create_update_mongo_db_database_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
create_update_mongo_db_database_parameters: Union[_models.MongoDBDatabaseCreateUpdateParameters, IO],
**kwargs: Any
) -> Optional[_models.MongoDBDatabaseGetResults]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.MongoDBDatabaseGetResults]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(create_update_mongo_db_database_parameters, (IOBase, bytes)):
_content = create_update_mongo_db_database_parameters
else:
_json = self._serialize.body(
create_update_mongo_db_database_parameters, "MongoDBDatabaseCreateUpdateParameters"
)
request = build_create_update_mongo_db_database_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_update_mongo_db_database_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_create_update_mongo_db_database_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}"
}
@overload
async def begin_create_update_mongo_db_database(
self,
resource_group_name: str,
account_name: str,
database_name: str,
create_update_mongo_db_database_parameters: _models.MongoDBDatabaseCreateUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.MongoDBDatabaseGetResults]:
"""Create or updates Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param create_update_mongo_db_database_parameters: The parameters to provide for the current
MongoDB database. Required.
:type create_update_mongo_db_database_parameters:
~azure.mgmt.cosmosdb.models.MongoDBDatabaseCreateUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoDBDatabaseGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create_update_mongo_db_database(
self,
resource_group_name: str,
account_name: str,
database_name: str,
create_update_mongo_db_database_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.MongoDBDatabaseGetResults]:
"""Create or updates Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param create_update_mongo_db_database_parameters: The parameters to provide for the current
MongoDB database. Required.
:type create_update_mongo_db_database_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoDBDatabaseGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create_update_mongo_db_database(
self,
resource_group_name: str,
account_name: str,
database_name: str,
create_update_mongo_db_database_parameters: Union[_models.MongoDBDatabaseCreateUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.MongoDBDatabaseGetResults]:
"""Create or updates Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param create_update_mongo_db_database_parameters: The parameters to provide for the current
MongoDB database. Is either a MongoDBDatabaseCreateUpdateParameters type or a IO type.
Required.
:type create_update_mongo_db_database_parameters:
~azure.mgmt.cosmosdb.models.MongoDBDatabaseCreateUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoDBDatabaseGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBDatabaseGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.MongoDBDatabaseGetResults] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._create_update_mongo_db_database_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
create_update_mongo_db_database_parameters=create_update_mongo_db_database_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("MongoDBDatabaseGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create_update_mongo_db_database.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}"
}
async def _delete_mongo_db_database_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[None] = kwargs.pop("cls", None)
request = build_delete_mongo_db_database_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_mongo_db_database_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, None, response_headers)
_delete_mongo_db_database_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}"
}
@distributed_trace_async
async def begin_delete_mongo_db_database(
self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[None] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._delete_mongo_db_database_initial( # type: ignore
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_delete_mongo_db_database.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}"
}
@distributed_trace_async
async def get_mongo_db_database_throughput(
self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any
) -> _models.ThroughputSettingsGetResults:
"""Gets the RUs per second of the MongoDB database under an existing Azure Cosmos DB database
account with the provided name.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ThroughputSettingsGetResults or the result of cls(response)
:rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None)
request = build_get_mongo_db_database_throughput_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_mongo_db_database_throughput.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_mongo_db_database_throughput.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default"
}
async def _update_mongo_db_database_throughput_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO],
**kwargs: Any
) -> Optional[_models.ThroughputSettingsGetResults]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.ThroughputSettingsGetResults]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(update_throughput_parameters, (IOBase, bytes)):
_content = update_throughput_parameters
else:
_json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters")
request = build_update_mongo_db_database_throughput_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_mongo_db_database_throughput_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_update_mongo_db_database_throughput_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default"
}
@overload
async def begin_update_mongo_db_database_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
update_throughput_parameters: _models.ThroughputSettingsUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]:
"""Update RUs per second of the an Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param update_throughput_parameters: The RUs per second of the parameters to provide for the
current MongoDB database. Required.
:type update_throughput_parameters:
~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update_mongo_db_database_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
update_throughput_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]:
"""Update RUs per second of the an Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param update_throughput_parameters: The RUs per second of the parameters to provide for the
current MongoDB database. Required.
:type update_throughput_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update_mongo_db_database_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]:
"""Update RUs per second of the an Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param update_throughput_parameters: The RUs per second of the parameters to provide for the
current MongoDB database. Is either a ThroughputSettingsUpdateParameters type or a IO type.
Required.
:type update_throughput_parameters:
~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._update_mongo_db_database_throughput_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
update_throughput_parameters=update_throughput_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_update_mongo_db_database_throughput.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default"
}
async def _migrate_mongo_db_database_to_autoscale_initial(
self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any
) -> Optional[_models.ThroughputSettingsGetResults]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[Optional[_models.ThroughputSettingsGetResults]] = kwargs.pop("cls", None)
request = build_migrate_mongo_db_database_to_autoscale_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._migrate_mongo_db_database_to_autoscale_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_migrate_mongo_db_database_to_autoscale_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale"
}
@distributed_trace_async
async def begin_migrate_mongo_db_database_to_autoscale(
self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any
) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]:
"""Migrate an Azure Cosmos DB MongoDB database from manual throughput to autoscale.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._migrate_mongo_db_database_to_autoscale_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_migrate_mongo_db_database_to_autoscale.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/migrateToAutoscale"
}
async def _migrate_mongo_db_database_to_manual_throughput_initial(
self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any
) -> Optional[_models.ThroughputSettingsGetResults]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[Optional[_models.ThroughputSettingsGetResults]] = kwargs.pop("cls", None)
request = build_migrate_mongo_db_database_to_manual_throughput_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._migrate_mongo_db_database_to_manual_throughput_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_migrate_mongo_db_database_to_manual_throughput_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput"
}
@distributed_trace_async
async def begin_migrate_mongo_db_database_to_manual_throughput(
self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any
) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]:
"""Migrate an Azure Cosmos DB MongoDB database from autoscale to manual throughput.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._migrate_mongo_db_database_to_manual_throughput_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_migrate_mongo_db_database_to_manual_throughput.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/migrateToManualThroughput"
}
async def _mongo_db_database_retrieve_throughput_distribution_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO],
**kwargs: Any
) -> Optional[_models.PhysicalPartitionThroughputInfoResult]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.PhysicalPartitionThroughputInfoResult]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(retrieve_throughput_parameters, (IOBase, bytes)):
_content = retrieve_throughput_parameters
else:
_json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters")
request = build_mongo_db_database_retrieve_throughput_distribution_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._mongo_db_database_retrieve_throughput_distribution_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_mongo_db_database_retrieve_throughput_distribution_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/retrieveThroughputDistribution"
}
@overload
async def begin_mongo_db_database_retrieve_throughput_distribution(
self,
resource_group_name: str,
account_name: str,
database_name: str,
retrieve_throughput_parameters: _models.RetrieveThroughputParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Retrieve throughput distribution for an Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param retrieve_throughput_parameters: The parameters to provide for retrieving throughput
distribution for the current MongoDB database. Required.
:type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_mongo_db_database_retrieve_throughput_distribution(
self,
resource_group_name: str,
account_name: str,
database_name: str,
retrieve_throughput_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Retrieve throughput distribution for an Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param retrieve_throughput_parameters: The parameters to provide for retrieving throughput
distribution for the current MongoDB database. Required.
:type retrieve_throughput_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_mongo_db_database_retrieve_throughput_distribution(
self,
resource_group_name: str,
account_name: str,
database_name: str,
retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Retrieve throughput distribution for an Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param retrieve_throughput_parameters: The parameters to provide for retrieving throughput
distribution for the current MongoDB database. Is either a RetrieveThroughputParameters type or
a IO type. Required.
:type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters
or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._mongo_db_database_retrieve_throughput_distribution_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
retrieve_throughput_parameters=retrieve_throughput_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs)
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_mongo_db_database_retrieve_throughput_distribution.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/retrieveThroughputDistribution"
}
async def _mongo_db_database_redistribute_throughput_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO],
**kwargs: Any
) -> Optional[_models.PhysicalPartitionThroughputInfoResult]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.PhysicalPartitionThroughputInfoResult]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(redistribute_throughput_parameters, (IOBase, bytes)):
_content = redistribute_throughput_parameters
else:
_json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters")
request = build_mongo_db_database_redistribute_throughput_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._mongo_db_database_redistribute_throughput_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_mongo_db_database_redistribute_throughput_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/redistributeThroughput"
}
@overload
async def begin_mongo_db_database_redistribute_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
redistribute_throughput_parameters: _models.RedistributeThroughputParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Redistribute throughput for an Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param redistribute_throughput_parameters: The parameters to provide for redistributing
throughput for the current MongoDB database. Required.
:type redistribute_throughput_parameters:
~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_mongo_db_database_redistribute_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
redistribute_throughput_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Redistribute throughput for an Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param redistribute_throughput_parameters: The parameters to provide for redistributing
throughput for the current MongoDB database. Required.
:type redistribute_throughput_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_mongo_db_database_redistribute_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Redistribute throughput for an Azure Cosmos DB MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param redistribute_throughput_parameters: The parameters to provide for redistributing
throughput for the current MongoDB database. Is either a RedistributeThroughputParameters type
or a IO type. Required.
:type redistribute_throughput_parameters:
~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._mongo_db_database_redistribute_throughput_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
redistribute_throughput_parameters=redistribute_throughput_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs)
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_mongo_db_database_redistribute_throughput.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/throughputSettings/default/redistributeThroughput"
}
async def _mongo_db_container_retrieve_throughput_distribution_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO],
**kwargs: Any
) -> Optional[_models.PhysicalPartitionThroughputInfoResult]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.PhysicalPartitionThroughputInfoResult]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(retrieve_throughput_parameters, (IOBase, bytes)):
_content = retrieve_throughput_parameters
else:
_json = self._serialize.body(retrieve_throughput_parameters, "RetrieveThroughputParameters")
request = build_mongo_db_container_retrieve_throughput_distribution_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._mongo_db_container_retrieve_throughput_distribution_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_mongo_db_container_retrieve_throughput_distribution_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/retrieveThroughputDistribution"
}
@overload
async def begin_mongo_db_container_retrieve_throughput_distribution(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
retrieve_throughput_parameters: _models.RetrieveThroughputParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Retrieve throughput distribution for an Azure Cosmos DB MongoDB container.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param retrieve_throughput_parameters: The parameters to provide for retrieving throughput
distribution for the current MongoDB container. Required.
:type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_mongo_db_container_retrieve_throughput_distribution(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
retrieve_throughput_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Retrieve throughput distribution for an Azure Cosmos DB MongoDB container.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param retrieve_throughput_parameters: The parameters to provide for retrieving throughput
distribution for the current MongoDB container. Required.
:type retrieve_throughput_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_mongo_db_container_retrieve_throughput_distribution(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
retrieve_throughput_parameters: Union[_models.RetrieveThroughputParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Retrieve throughput distribution for an Azure Cosmos DB MongoDB container.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param retrieve_throughput_parameters: The parameters to provide for retrieving throughput
distribution for the current MongoDB container. Is either a RetrieveThroughputParameters type
or a IO type. Required.
:type retrieve_throughput_parameters: ~azure.mgmt.cosmosdb.models.RetrieveThroughputParameters
or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._mongo_db_container_retrieve_throughput_distribution_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
retrieve_throughput_parameters=retrieve_throughput_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs)
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_mongo_db_container_retrieve_throughput_distribution.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/retrieveThroughputDistribution"
}
async def _mongo_db_container_redistribute_throughput_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO],
**kwargs: Any
) -> Optional[_models.PhysicalPartitionThroughputInfoResult]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.PhysicalPartitionThroughputInfoResult]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(redistribute_throughput_parameters, (IOBase, bytes)):
_content = redistribute_throughput_parameters
else:
_json = self._serialize.body(redistribute_throughput_parameters, "RedistributeThroughputParameters")
request = build_mongo_db_container_redistribute_throughput_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._mongo_db_container_redistribute_throughput_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_mongo_db_container_redistribute_throughput_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/redistributeThroughput"
}
@overload
async def begin_mongo_db_container_redistribute_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
redistribute_throughput_parameters: _models.RedistributeThroughputParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Redistribute throughput for an Azure Cosmos DB MongoDB container.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param redistribute_throughput_parameters: The parameters to provide for redistributing
throughput for the current MongoDB container. Required.
:type redistribute_throughput_parameters:
~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_mongo_db_container_redistribute_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
redistribute_throughput_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Redistribute throughput for an Azure Cosmos DB MongoDB container.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param redistribute_throughput_parameters: The parameters to provide for redistributing
throughput for the current MongoDB container. Required.
:type redistribute_throughput_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_mongo_db_container_redistribute_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
redistribute_throughput_parameters: Union[_models.RedistributeThroughputParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionThroughputInfoResult]:
"""Redistribute throughput for an Azure Cosmos DB MongoDB container.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param redistribute_throughput_parameters: The parameters to provide for redistributing
throughput for the current MongoDB container. Is either a RedistributeThroughputParameters type
or a IO type. Required.
:type redistribute_throughput_parameters:
~azure.mgmt.cosmosdb.models.RedistributeThroughputParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionThroughputInfoResult or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionThroughputInfoResult]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.PhysicalPartitionThroughputInfoResult] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._mongo_db_container_redistribute_throughput_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
redistribute_throughput_parameters=redistribute_throughput_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("PhysicalPartitionThroughputInfoResult", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs)
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_mongo_db_container_redistribute_throughput.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/redistributeThroughput"
}
@distributed_trace
def list_mongo_db_collections(
self, resource_group_name: str, account_name: str, database_name: str, **kwargs: Any
) -> AsyncIterable["_models.MongoDBCollectionGetResults"]:
"""Lists the MongoDB collection under an existing Azure Cosmos DB database account.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either MongoDBCollectionGetResults or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.MongoDBCollectionListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_mongo_db_collections_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_mongo_db_collections.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("MongoDBCollectionListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_mongo_db_collections.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections"
}
@distributed_trace_async
async def get_mongo_db_collection(
self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any
) -> _models.MongoDBCollectionGetResults:
"""Gets the MongoDB collection under an existing Azure Cosmos DB database account.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: MongoDBCollectionGetResults or the result of cls(response)
:rtype: ~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.MongoDBCollectionGetResults] = kwargs.pop("cls", None)
request = build_get_mongo_db_collection_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_mongo_db_collection.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_mongo_db_collection.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}"
}
async def _create_update_mongo_db_collection_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
create_update_mongo_db_collection_parameters: Union[_models.MongoDBCollectionCreateUpdateParameters, IO],
**kwargs: Any
) -> Optional[_models.MongoDBCollectionGetResults]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.MongoDBCollectionGetResults]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(create_update_mongo_db_collection_parameters, (IOBase, bytes)):
_content = create_update_mongo_db_collection_parameters
else:
_json = self._serialize.body(
create_update_mongo_db_collection_parameters, "MongoDBCollectionCreateUpdateParameters"
)
request = build_create_update_mongo_db_collection_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_update_mongo_db_collection_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_create_update_mongo_db_collection_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}"
}
@overload
async def begin_create_update_mongo_db_collection(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
create_update_mongo_db_collection_parameters: _models.MongoDBCollectionCreateUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.MongoDBCollectionGetResults]:
"""Create or update an Azure Cosmos DB MongoDB Collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param create_update_mongo_db_collection_parameters: The parameters to provide for the current
MongoDB Collection. Required.
:type create_update_mongo_db_collection_parameters:
~azure.mgmt.cosmosdb.models.MongoDBCollectionCreateUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoDBCollectionGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create_update_mongo_db_collection(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
create_update_mongo_db_collection_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.MongoDBCollectionGetResults]:
"""Create or update an Azure Cosmos DB MongoDB Collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param create_update_mongo_db_collection_parameters: The parameters to provide for the current
MongoDB Collection. Required.
:type create_update_mongo_db_collection_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoDBCollectionGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create_update_mongo_db_collection(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
create_update_mongo_db_collection_parameters: Union[_models.MongoDBCollectionCreateUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.MongoDBCollectionGetResults]:
"""Create or update an Azure Cosmos DB MongoDB Collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param create_update_mongo_db_collection_parameters: The parameters to provide for the current
MongoDB Collection. Is either a MongoDBCollectionCreateUpdateParameters type or a IO type.
Required.
:type create_update_mongo_db_collection_parameters:
~azure.mgmt.cosmosdb.models.MongoDBCollectionCreateUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoDBCollectionGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoDBCollectionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.MongoDBCollectionGetResults] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._create_update_mongo_db_collection_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
create_update_mongo_db_collection_parameters=create_update_mongo_db_collection_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("MongoDBCollectionGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create_update_mongo_db_collection.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}"
}
async def _delete_mongo_db_collection_initial( # pylint: disable=inconsistent-return-statements
self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[None] = kwargs.pop("cls", None)
request = build_delete_mongo_db_collection_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_mongo_db_collection_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
response_headers = {}
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, None, response_headers)
_delete_mongo_db_collection_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}"
}
@distributed_trace_async
async def begin_delete_mongo_db_collection(
self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing Azure Cosmos DB MongoDB Collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[None] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._delete_mongo_db_collection_initial( # type: ignore
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_delete_mongo_db_collection.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}"
}
async def _mongo_db_database_partition_merge_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
merge_parameters: Union[_models.MergeParameters, IO],
**kwargs: Any
) -> Optional[_models.PhysicalPartitionStorageInfoCollection]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.PhysicalPartitionStorageInfoCollection]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(merge_parameters, (IOBase, bytes)):
_content = merge_parameters
else:
_json = self._serialize.body(merge_parameters, "MergeParameters")
request = build_mongo_db_database_partition_merge_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._mongo_db_database_partition_merge_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_mongo_db_database_partition_merge_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/partitionMerge"
}
@overload
async def begin_mongo_db_database_partition_merge(
self,
resource_group_name: str,
account_name: str,
database_name: str,
merge_parameters: _models.MergeParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]:
"""Merges the partitions of a MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param merge_parameters: The parameters for the merge operation. Required.
:type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionStorageInfoCollection or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_mongo_db_database_partition_merge(
self,
resource_group_name: str,
account_name: str,
database_name: str,
merge_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]:
"""Merges the partitions of a MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param merge_parameters: The parameters for the merge operation. Required.
:type merge_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionStorageInfoCollection or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_mongo_db_database_partition_merge(
self,
resource_group_name: str,
account_name: str,
database_name: str,
merge_parameters: Union[_models.MergeParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]:
"""Merges the partitions of a MongoDB database.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param merge_parameters: The parameters for the merge operation. Is either a MergeParameters
type or a IO type. Required.
:type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionStorageInfoCollection or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._mongo_db_database_partition_merge_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
merge_parameters=merge_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs)
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_mongo_db_database_partition_merge.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/partitionMerge"
}
async def _list_mongo_db_collection_partition_merge_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
merge_parameters: Union[_models.MergeParameters, IO],
**kwargs: Any
) -> Optional[_models.PhysicalPartitionStorageInfoCollection]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.PhysicalPartitionStorageInfoCollection]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(merge_parameters, (IOBase, bytes)):
_content = merge_parameters
else:
_json = self._serialize.body(merge_parameters, "MergeParameters")
request = build_list_mongo_db_collection_partition_merge_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._list_mongo_db_collection_partition_merge_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_list_mongo_db_collection_partition_merge_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/partitionMerge"
}
@overload
async def begin_list_mongo_db_collection_partition_merge(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
merge_parameters: _models.MergeParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]:
"""Merges the partitions of a MongoDB Collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param merge_parameters: The parameters for the merge operation. Required.
:type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionStorageInfoCollection or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_list_mongo_db_collection_partition_merge(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
merge_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]:
"""Merges the partitions of a MongoDB Collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param merge_parameters: The parameters for the merge operation. Required.
:type merge_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionStorageInfoCollection or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_list_mongo_db_collection_partition_merge(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
merge_parameters: Union[_models.MergeParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.PhysicalPartitionStorageInfoCollection]:
"""Merges the partitions of a MongoDB Collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param merge_parameters: The parameters for the merge operation. Is either a MergeParameters
type or a IO type. Required.
:type merge_parameters: ~azure.mgmt.cosmosdb.models.MergeParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either
PhysicalPartitionStorageInfoCollection or the result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.PhysicalPartitionStorageInfoCollection]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.PhysicalPartitionStorageInfoCollection] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._list_mongo_db_collection_partition_merge_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
merge_parameters=merge_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("PhysicalPartitionStorageInfoCollection", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs)
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_list_mongo_db_collection_partition_merge.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/partitionMerge"
}
@distributed_trace_async
async def get_mongo_db_collection_throughput(
self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any
) -> _models.ThroughputSettingsGetResults:
"""Gets the RUs per second of the MongoDB collection under an existing Azure Cosmos DB database
account with the provided name.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ThroughputSettingsGetResults or the result of cls(response)
:rtype: ~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None)
request = build_get_mongo_db_collection_throughput_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_mongo_db_collection_throughput.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_mongo_db_collection_throughput.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default"
}
async def _update_mongo_db_collection_throughput_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO],
**kwargs: Any
) -> Optional[_models.ThroughputSettingsGetResults]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.ThroughputSettingsGetResults]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(update_throughput_parameters, (IOBase, bytes)):
_content = update_throughput_parameters
else:
_json = self._serialize.body(update_throughput_parameters, "ThroughputSettingsUpdateParameters")
request = build_update_mongo_db_collection_throughput_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._update_mongo_db_collection_throughput_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_update_mongo_db_collection_throughput_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default"
}
@overload
async def begin_update_mongo_db_collection_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
update_throughput_parameters: _models.ThroughputSettingsUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]:
"""Update the RUs per second of an Azure Cosmos DB MongoDB collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param update_throughput_parameters: The RUs per second of the parameters to provide for the
current MongoDB collection. Required.
:type update_throughput_parameters:
~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_update_mongo_db_collection_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
update_throughput_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]:
"""Update the RUs per second of an Azure Cosmos DB MongoDB collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param update_throughput_parameters: The RUs per second of the parameters to provide for the
current MongoDB collection. Required.
:type update_throughput_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_update_mongo_db_collection_throughput(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
update_throughput_parameters: Union[_models.ThroughputSettingsUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]:
"""Update the RUs per second of an Azure Cosmos DB MongoDB collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param update_throughput_parameters: The RUs per second of the parameters to provide for the
current MongoDB collection. Is either a ThroughputSettingsUpdateParameters type or a IO type.
Required.
:type update_throughput_parameters:
~azure.mgmt.cosmosdb.models.ThroughputSettingsUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._update_mongo_db_collection_throughput_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
update_throughput_parameters=update_throughput_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_update_mongo_db_collection_throughput.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default"
}
async def _migrate_mongo_db_collection_to_autoscale_initial(
self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any
) -> Optional[_models.ThroughputSettingsGetResults]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[Optional[_models.ThroughputSettingsGetResults]] = kwargs.pop("cls", None)
request = build_migrate_mongo_db_collection_to_autoscale_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._migrate_mongo_db_collection_to_autoscale_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_migrate_mongo_db_collection_to_autoscale_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/migrateToAutoscale"
}
@distributed_trace_async
async def begin_migrate_mongo_db_collection_to_autoscale(
self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any
) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]:
"""Migrate an Azure Cosmos DB MongoDB collection from manual throughput to autoscale.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._migrate_mongo_db_collection_to_autoscale_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_migrate_mongo_db_collection_to_autoscale.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/migrateToAutoscale"
}
async def _migrate_mongo_db_collection_to_manual_throughput_initial(
self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any
) -> Optional[_models.ThroughputSettingsGetResults]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[Optional[_models.ThroughputSettingsGetResults]] = kwargs.pop("cls", None)
request = build_migrate_mongo_db_collection_to_manual_throughput_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._migrate_mongo_db_collection_to_manual_throughput_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
response_headers = {}
if response.status_code == 200:
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if response.status_code == 202:
response_headers["azure-AsyncOperation"] = self._deserialize(
"str", response.headers.get("azure-AsyncOperation")
)
response_headers["location"] = self._deserialize("str", response.headers.get("location"))
if cls:
return cls(pipeline_response, deserialized, response_headers)
return deserialized
_migrate_mongo_db_collection_to_manual_throughput_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/migrateToManualThroughput"
}
@distributed_trace_async
async def begin_migrate_mongo_db_collection_to_manual_throughput(
self, resource_group_name: str, account_name: str, database_name: str, collection_name: str, **kwargs: Any
) -> AsyncLROPoller[_models.ThroughputSettingsGetResults]:
"""Migrate an Azure Cosmos DB MongoDB collection from autoscale to manual throughput.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either ThroughputSettingsGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.ThroughputSettingsGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.ThroughputSettingsGetResults] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._migrate_mongo_db_collection_to_manual_throughput_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("ThroughputSettingsGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_migrate_mongo_db_collection_to_manual_throughput.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/throughputSettings/default/migrateToManualThroughput"
}
@distributed_trace_async
async def get_mongo_role_definition(
self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any
) -> _models.MongoRoleDefinitionGetResults:
"""Retrieves the properties of an existing Azure Cosmos DB Mongo Role Definition with the given
Id.
:param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required.
:type mongo_role_definition_id: str
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: MongoRoleDefinitionGetResults or the result of cls(response)
:rtype: ~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.MongoRoleDefinitionGetResults] = kwargs.pop("cls", None)
request = build_get_mongo_role_definition_request(
mongo_role_definition_id=mongo_role_definition_id,
resource_group_name=resource_group_name,
account_name=account_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_mongo_role_definition.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_mongo_role_definition.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}"
}
async def _create_update_mongo_role_definition_initial(
self,
mongo_role_definition_id: str,
resource_group_name: str,
account_name: str,
create_update_mongo_role_definition_parameters: Union[_models.MongoRoleDefinitionCreateUpdateParameters, IO],
**kwargs: Any
) -> Optional[_models.MongoRoleDefinitionGetResults]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.MongoRoleDefinitionGetResults]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(create_update_mongo_role_definition_parameters, (IOBase, bytes)):
_content = create_update_mongo_role_definition_parameters
else:
_json = self._serialize.body(
create_update_mongo_role_definition_parameters, "MongoRoleDefinitionCreateUpdateParameters"
)
request = build_create_update_mongo_role_definition_request(
mongo_role_definition_id=mongo_role_definition_id,
resource_group_name=resource_group_name,
account_name=account_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_update_mongo_role_definition_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_update_mongo_role_definition_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}"
}
@overload
async def begin_create_update_mongo_role_definition(
self,
mongo_role_definition_id: str,
resource_group_name: str,
account_name: str,
create_update_mongo_role_definition_parameters: _models.MongoRoleDefinitionCreateUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.MongoRoleDefinitionGetResults]:
"""Creates or updates an Azure Cosmos DB Mongo Role Definition.
:param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required.
:type mongo_role_definition_id: str
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param create_update_mongo_role_definition_parameters: The properties required to create or
update a Role Definition. Required.
:type create_update_mongo_role_definition_parameters:
~azure.mgmt.cosmosdb.models.MongoRoleDefinitionCreateUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoRoleDefinitionGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create_update_mongo_role_definition(
self,
mongo_role_definition_id: str,
resource_group_name: str,
account_name: str,
create_update_mongo_role_definition_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.MongoRoleDefinitionGetResults]:
"""Creates or updates an Azure Cosmos DB Mongo Role Definition.
:param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required.
:type mongo_role_definition_id: str
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param create_update_mongo_role_definition_parameters: The properties required to create or
update a Role Definition. Required.
:type create_update_mongo_role_definition_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoRoleDefinitionGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create_update_mongo_role_definition(
self,
mongo_role_definition_id: str,
resource_group_name: str,
account_name: str,
create_update_mongo_role_definition_parameters: Union[_models.MongoRoleDefinitionCreateUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.MongoRoleDefinitionGetResults]:
"""Creates or updates an Azure Cosmos DB Mongo Role Definition.
:param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required.
:type mongo_role_definition_id: str
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param create_update_mongo_role_definition_parameters: The properties required to create or
update a Role Definition. Is either a MongoRoleDefinitionCreateUpdateParameters type or a IO
type. Required.
:type create_update_mongo_role_definition_parameters:
~azure.mgmt.cosmosdb.models.MongoRoleDefinitionCreateUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoRoleDefinitionGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.MongoRoleDefinitionGetResults] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._create_update_mongo_role_definition_initial(
mongo_role_definition_id=mongo_role_definition_id,
resource_group_name=resource_group_name,
account_name=account_name,
create_update_mongo_role_definition_parameters=create_update_mongo_role_definition_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("MongoRoleDefinitionGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create_update_mongo_role_definition.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}"
}
async def _delete_mongo_role_definition_initial( # pylint: disable=inconsistent-return-statements
self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[None] = kwargs.pop("cls", None)
request = build_delete_mongo_role_definition_request(
mongo_role_definition_id=mongo_role_definition_id,
resource_group_name=resource_group_name,
account_name=account_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_mongo_role_definition_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_mongo_role_definition_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}"
}
@distributed_trace_async
async def begin_delete_mongo_role_definition(
self, mongo_role_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing Azure Cosmos DB Mongo Role Definition.
:param mongo_role_definition_id: The ID for the Role Definition {dbName.roleName}. Required.
:type mongo_role_definition_id: str
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[None] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._delete_mongo_role_definition_initial( # type: ignore
mongo_role_definition_id=mongo_role_definition_id,
resource_group_name=resource_group_name,
account_name=account_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_delete_mongo_role_definition.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions/{mongoRoleDefinitionId}"
}
@distributed_trace
def list_mongo_role_definitions(
self, resource_group_name: str, account_name: str, **kwargs: Any
) -> AsyncIterable["_models.MongoRoleDefinitionGetResults"]:
"""Retrieves the list of all Azure Cosmos DB Mongo Role Definitions.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either MongoRoleDefinitionGetResults or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoRoleDefinitionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.MongoRoleDefinitionListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_mongo_role_definitions_request(
resource_group_name=resource_group_name,
account_name=account_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_mongo_role_definitions.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("MongoRoleDefinitionListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_mongo_role_definitions.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbRoleDefinitions"
}
@distributed_trace_async
async def get_mongo_user_definition(
self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any
) -> _models.MongoUserDefinitionGetResults:
"""Retrieves the properties of an existing Azure Cosmos DB Mongo User Definition with the given
Id.
:param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required.
:type mongo_user_definition_id: str
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: MongoUserDefinitionGetResults or the result of cls(response)
:rtype: ~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.MongoUserDefinitionGetResults] = kwargs.pop("cls", None)
request = build_get_mongo_user_definition_request(
mongo_user_definition_id=mongo_user_definition_id,
resource_group_name=resource_group_name,
account_name=account_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get_mongo_user_definition.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_mongo_user_definition.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}"
}
async def _create_update_mongo_user_definition_initial(
self,
mongo_user_definition_id: str,
resource_group_name: str,
account_name: str,
create_update_mongo_user_definition_parameters: Union[_models.MongoUserDefinitionCreateUpdateParameters, IO],
**kwargs: Any
) -> Optional[_models.MongoUserDefinitionGetResults]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.MongoUserDefinitionGetResults]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(create_update_mongo_user_definition_parameters, (IOBase, bytes)):
_content = create_update_mongo_user_definition_parameters
else:
_json = self._serialize.body(
create_update_mongo_user_definition_parameters, "MongoUserDefinitionCreateUpdateParameters"
)
request = build_create_update_mongo_user_definition_request(
mongo_user_definition_id=mongo_user_definition_id,
resource_group_name=resource_group_name,
account_name=account_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._create_update_mongo_user_definition_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_update_mongo_user_definition_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}"
}
@overload
async def begin_create_update_mongo_user_definition(
self,
mongo_user_definition_id: str,
resource_group_name: str,
account_name: str,
create_update_mongo_user_definition_parameters: _models.MongoUserDefinitionCreateUpdateParameters,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.MongoUserDefinitionGetResults]:
"""Creates or updates an Azure Cosmos DB Mongo User Definition.
:param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required.
:type mongo_user_definition_id: str
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param create_update_mongo_user_definition_parameters: The properties required to create or
update a User Definition. Required.
:type create_update_mongo_user_definition_parameters:
~azure.mgmt.cosmosdb.models.MongoUserDefinitionCreateUpdateParameters
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoUserDefinitionGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_create_update_mongo_user_definition(
self,
mongo_user_definition_id: str,
resource_group_name: str,
account_name: str,
create_update_mongo_user_definition_parameters: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.MongoUserDefinitionGetResults]:
"""Creates or updates an Azure Cosmos DB Mongo User Definition.
:param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required.
:type mongo_user_definition_id: str
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param create_update_mongo_user_definition_parameters: The properties required to create or
update a User Definition. Required.
:type create_update_mongo_user_definition_parameters: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoUserDefinitionGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_create_update_mongo_user_definition(
self,
mongo_user_definition_id: str,
resource_group_name: str,
account_name: str,
create_update_mongo_user_definition_parameters: Union[_models.MongoUserDefinitionCreateUpdateParameters, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.MongoUserDefinitionGetResults]:
"""Creates or updates an Azure Cosmos DB Mongo User Definition.
:param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required.
:type mongo_user_definition_id: str
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param create_update_mongo_user_definition_parameters: The properties required to create or
update a User Definition. Is either a MongoUserDefinitionCreateUpdateParameters type or a IO
type. Required.
:type create_update_mongo_user_definition_parameters:
~azure.mgmt.cosmosdb.models.MongoUserDefinitionCreateUpdateParameters or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either MongoUserDefinitionGetResults or the
result of cls(response)
:rtype:
~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.MongoUserDefinitionGetResults] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._create_update_mongo_user_definition_initial(
mongo_user_definition_id=mongo_user_definition_id,
resource_group_name=resource_group_name,
account_name=account_name,
create_update_mongo_user_definition_parameters=create_update_mongo_user_definition_parameters,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("MongoUserDefinitionGetResults", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_create_update_mongo_user_definition.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}"
}
async def _delete_mongo_user_definition_initial( # pylint: disable=inconsistent-return-statements
self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[None] = kwargs.pop("cls", None)
request = build_delete_mongo_user_definition_request(
mongo_user_definition_id=mongo_user_definition_id,
resource_group_name=resource_group_name,
account_name=account_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._delete_mongo_user_definition_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_mongo_user_definition_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}"
}
@distributed_trace_async
async def begin_delete_mongo_user_definition(
self, mongo_user_definition_id: str, resource_group_name: str, account_name: str, **kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes an existing Azure Cosmos DB Mongo User Definition.
:param mongo_user_definition_id: The ID for the User Definition {dbName.userName}. Required.
:type mongo_user_definition_id: str
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[None] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._delete_mongo_user_definition_initial( # type: ignore
mongo_user_definition_id=mongo_user_definition_id,
resource_group_name=resource_group_name,
account_name=account_name,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method: AsyncPollingMethod = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs))
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_delete_mongo_user_definition.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions/{mongoUserDefinitionId}"
}
@distributed_trace
def list_mongo_user_definitions(
self, resource_group_name: str, account_name: str, **kwargs: Any
) -> AsyncIterable["_models.MongoUserDefinitionGetResults"]:
"""Retrieves the list of all Azure Cosmos DB Mongo User Definition.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either MongoUserDefinitionGetResults or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.cosmosdb.models.MongoUserDefinitionGetResults]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
cls: ClsType[_models.MongoUserDefinitionListResult] = kwargs.pop("cls", None)
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_mongo_user_definitions_request(
resource_group_name=resource_group_name,
account_name=account_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_mongo_user_definitions.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
else:
# make call to next link with the client's api-version
_parsed_next_link = urllib.parse.urlparse(next_link)
_next_request_params = case_insensitive_dict(
{
key: [urllib.parse.quote(v) for v in value]
for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
}
)
_next_request_params["api-version"] = self._config.api_version
request = HttpRequest(
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("MongoUserDefinitionListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem) # type: ignore
return None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_mongo_user_definitions.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbUserDefinitions"
}
async def _retrieve_continuous_backup_information_initial(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
location: Union[_models.ContinuousBackupRestoreLocation, IO],
**kwargs: Any
) -> Optional[_models.BackupInformation]:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[Optional[_models.BackupInformation]] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_json = None
_content = None
if isinstance(location, (IOBase, bytes)):
_content = location
else:
_json = self._serialize.body(location, "ContinuousBackupRestoreLocation")
request = build_retrieve_continuous_backup_information_request(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
content_type=content_type,
json=_json,
content=_content,
template_url=self._retrieve_continuous_backup_information_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
_stream = False
pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access
request, stream=_stream, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize("BackupInformation", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_retrieve_continuous_backup_information_initial.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/retrieveContinuousBackupInformation"
}
@overload
async def begin_retrieve_continuous_backup_information(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
location: _models.ContinuousBackupRestoreLocation,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.BackupInformation]:
"""Retrieves continuous backup information for a Mongodb collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param location: The name of the continuous backup restore location. Required.
:type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation
:keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either BackupInformation or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
async def begin_retrieve_continuous_backup_information(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
location: IO,
*,
content_type: str = "application/json",
**kwargs: Any
) -> AsyncLROPoller[_models.BackupInformation]:
"""Retrieves continuous backup information for a Mongodb collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param location: The name of the continuous backup restore location. Required.
:type location: IO
:keyword content_type: Body Parameter content-type. Content type parameter for binary body.
Default value is "application/json".
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either BackupInformation or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
@distributed_trace_async
async def begin_retrieve_continuous_backup_information(
self,
resource_group_name: str,
account_name: str,
database_name: str,
collection_name: str,
location: Union[_models.ContinuousBackupRestoreLocation, IO],
**kwargs: Any
) -> AsyncLROPoller[_models.BackupInformation]:
"""Retrieves continuous backup information for a Mongodb collection.
:param resource_group_name: The name of the resource group. The name is case insensitive.
Required.
:type resource_group_name: str
:param account_name: Cosmos DB database account name. Required.
:type account_name: str
:param database_name: Cosmos DB database name. Required.
:type database_name: str
:param collection_name: Cosmos DB collection name. Required.
:type collection_name: str
:param location: The name of the continuous backup restore location. Is either a
ContinuousBackupRestoreLocation type or a IO type. Required.
:type location: ~azure.mgmt.cosmosdb.models.ContinuousBackupRestoreLocation or IO
:keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
Default value is None.
:paramtype content_type: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either BackupInformation or the result of
cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.cosmosdb.models.BackupInformation]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
cls: ClsType[_models.BackupInformation] = kwargs.pop("cls", None)
polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token: Optional[str] = kwargs.pop("continuation_token", None)
if cont_token is None:
raw_result = await self._retrieve_continuous_backup_information_initial(
resource_group_name=resource_group_name,
account_name=account_name,
database_name=database_name,
collection_name=collection_name,
location=location,
api_version=api_version,
content_type=content_type,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize("BackupInformation", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
if polling is True:
polling_method: AsyncPollingMethod = cast(
AsyncPollingMethod, AsyncARMPolling(lro_delay, lro_options={"final-state-via": "location"}, **kwargs)
)
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) # type: ignore
begin_retrieve_continuous_backup_information.metadata = {
"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/mongodbDatabases/{databaseName}/collections/{collectionName}/retrieveContinuousBackupInformation"
}
|
c5d3232ed7041ff3c788ca10b93847c907a0164b
|
9edbe7b1ec03b557aa8f5b8fc6b7623bdb9151b3
|
/sf_examples/atari/enjoy_atari.py
|
eb60019fe10c7536ab6fb5971d6daa08f43860a3
|
[
"MIT"
] |
permissive
|
alex-petrenko/sample-factory
|
77c0370ef73902c5530acec7cb49cc1eff224173
|
7e1e69550f4de4cdc003d8db5bb39e186803aee9
|
refs/heads/master
| 2023-07-24T17:27:10.924055
| 2023-06-30T12:09:31
| 2023-06-30T12:09:31
| 192,824,415
| 644
| 99
|
MIT
| 2023-07-17T08:50:05
| 2019-06-20T00:59:01
|
Python
|
UTF-8
|
Python
| false
| false
| 350
|
py
|
enjoy_atari.py
|
import sys
from sample_factory.enjoy import enjoy
from sf_examples.atari.train_atari import parse_atari_args, register_atari_components
def main():
"""Script entry point."""
register_atari_components()
cfg = parse_atari_args(evaluation=True)
status = enjoy(cfg)
return status
if __name__ == "__main__":
sys.exit(main())
|
89d2f87f977d1b967c77798512bec44b6678ee98
|
6212eced0deaf6fc921627cd85ae59f1ff414ce5
|
/tests/file/test_get_file.py
|
5c0cb68f11ccb698b752fce8ef902dac5ba54103
|
[
"MIT",
"LGPL-2.0-or-later"
] |
permissive
|
Azure/azure-storage-python
|
eae1b1b49f5ddf9d7ef75568a7dd00a077d3d5b6
|
21c232e6bd6528bbf9e93b103f78ccc921384168
|
refs/heads/master
| 2023-08-16T17:05:37.740248
| 2023-01-24T17:24:33
| 2023-01-24T17:24:33
| 39,039,065
| 370
| 291
|
MIT
| 2023-01-24T17:24:35
| 2015-07-13T21:45:05
|
Python
|
UTF-8
|
Python
| false
| false
| 37,161
|
py
|
test_get_file.py
|
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import base64
import os
import unittest
from azure.common import AzureHttpError
from azure.storage.file import (
File,
FileService,
DeleteSnapshot,
)
from tests.testcase import (
StorageTestCase,
TestMode,
record,
)
# ------------------------------------------------------------------------------
TEST_FILE_PREFIX = 'file'
FILE_PATH = 'file_output.temp.dat'
# ------------------------------------------------------------------------------
class StorageGetFileTest(StorageTestCase):
def setUp(self):
super(StorageGetFileTest, self).setUp()
self.fs = self._create_storage_service(FileService, self.settings)
self.share_name = self.get_resource_name('utshare')
self.directory_name = self.get_resource_name('utdir')
if not self.is_playback():
self.fs.create_share(self.share_name)
self.fs.create_directory(self.share_name, self.directory_name)
self.byte_file = self.get_resource_name('bytefile')
self.byte_data = self.get_random_bytes(64 * 1024 + 5)
if not self.is_playback():
self.fs.create_file_from_bytes(self.share_name, self.directory_name, self.byte_file, self.byte_data)
# test chunking functionality by reducing the threshold
# for chunking and the size of each chunk, otherwise
# the tests would take too long to execute
self.fs.MAX_SINGLE_GET_SIZE = 32 * 1024
self.fs.MAX_CHUNK_GET_SIZE = 4 * 1024
def tearDown(self):
if not self.is_playback():
try:
self.fs.delete_share(self.share_name, delete_snapshots=DeleteSnapshot.Include)
except:
pass
if os.path.isfile(FILE_PATH):
try:
os.remove(FILE_PATH)
except:
pass
return super(StorageGetFileTest, self).tearDown()
# --Helpers-----------------------------------------------------------------
def _get_file_reference(self):
return self.get_resource_name(TEST_FILE_PREFIX)
class NonSeekableFile(object):
def __init__(self, wrapped_file):
self.wrapped_file = wrapped_file
def write(self, data):
self.wrapped_file.write(data)
def read(self, count):
return self.wrapped_file.read(count)
# -- Get test cases for files ----------------------------------------------
@record
def test_unicode_get_file_unicode_data(self):
# Arrange
file_data = u'hello world啊齄丂狛狜'.encode('utf-8')
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, file_data)
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, file_name)
# Assert
self.assertIsInstance(file, File)
self.assertEqual(file.content, file_data)
@record
def test_unicode_get_file_binary_data(self):
# Arrange
base64_data = 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/wABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=='
binary_data = base64.b64decode(base64_data)
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, binary_data)
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, file_name)
# Assert
self.assertIsInstance(file, File)
self.assertEqual(file.content, binary_data)
@record
def test_get_file_no_content(self):
# Arrange
file_data = b''
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, file_data)
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, file_name)
# Assert
self.assertEqual(file_data, file.content)
self.assertEqual(0, file.properties.content_length)
def test_get_file_to_bytes(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, self.byte_file)
# Assert
self.assertEqual(self.byte_data, file.content)
def test_get_file_to_bytes_with_progress(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, self.byte_file,
progress_callback=callback)
# Assert
self.assertEqual(self.byte_data, file.content)
self.assert_download_progress(len(self.byte_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE,
progress)
@record
def test_get_file_to_bytes_non_parallel(self):
# Arrange
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, self.byte_file, max_connections=1,
progress_callback=callback)
# Assert
self.assertEqual(self.byte_data, file.content)
self.assert_download_progress(len(self.byte_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE,
progress)
@record
def test_get_file_to_bytes_small(self):
# Arrange
file_data = self.get_random_bytes(1024)
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, file_data)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, file_name, progress_callback=callback)
# Assert
self.assertEqual(file_data, file.content)
self.assert_download_progress(len(file_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE, progress)
def test_get_file_to_stream(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
# Act
with open(FILE_PATH, 'wb') as stream:
file = self.fs.get_file_to_stream(self.share_name, self.directory_name, self.byte_file, stream)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
def test_get_file_to_stream_with_progress(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
progress = []
def callback(current, total):
progress.append((current, total))
# Act
with open(FILE_PATH, 'wb') as stream:
file = self.fs.get_file_to_stream(
self.share_name, self.directory_name, self.byte_file, stream, progress_callback=callback)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
self.assert_download_progress(len(self.byte_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE,
progress)
@record
def test_get_file_to_stream_non_parallel(self):
# Arrange
progress = []
def callback(current, total):
progress.append((current, total))
# Act
with open(FILE_PATH, 'wb') as stream:
file = self.fs.get_file_to_stream(
self.share_name, self.directory_name, self.byte_file, stream, max_connections=1,
progress_callback=callback)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
self.assert_download_progress(len(self.byte_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE,
progress)
@record
def test_get_file_to_stream_small(self):
# Arrange
file_data = self.get_random_bytes(1024)
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, file_data)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
with open(FILE_PATH, 'wb') as stream:
file = self.fs.get_file_to_stream(self.share_name, self.directory_name, file_name, stream,
progress_callback=callback)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(file_data, actual)
self.assert_download_progress(len(file_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE, progress)
def test_get_file_to_stream_from_snapshot(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
# Create a snapshot of the share and delete the file
share_snapshot = self.fs.snapshot_share(self.share_name)
self.fs.delete_file(self.share_name, self.directory_name, self.byte_file)
# Act
with open(FILE_PATH, 'wb') as stream:
file = self.fs.get_file_to_stream(self.share_name, self.directory_name,
self.byte_file, stream, snapshot=share_snapshot.snapshot)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
def test_get_file_to_stream_with_progress_from_snapshot(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
# Create a snapshot of the share and delete the file
share_snapshot = self.fs.snapshot_share(self.share_name)
self.fs.delete_file(self.share_name, self.directory_name, self.byte_file)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
with open(FILE_PATH, 'wb') as stream:
file = self.fs.get_file_to_stream(
self.share_name, self.directory_name,
self.byte_file, stream, progress_callback=callback, snapshot=share_snapshot.snapshot)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
self.assert_download_progress(len(self.byte_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE,
progress)
@record
def test_get_file_to_stream_non_parallel_from_snapshot(self):
# Arrange
# Create a snapshot of the share and delete the file
share_snapshot = self.fs.snapshot_share(self.share_name)
self.fs.delete_file(self.share_name, self.directory_name, self.byte_file)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
with open(FILE_PATH, 'wb') as stream:
file = self.fs.get_file_to_stream(
self.share_name, self.directory_name, self.byte_file, stream, max_connections=1,
progress_callback=callback, snapshot=share_snapshot.snapshot)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
self.assert_download_progress(len(self.byte_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE,
progress)
@record
def test_get_file_to_stream_small_from_snapshot(self):
# Arrange
file_data = self.get_random_bytes(1024)
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, file_data)
# Create a snapshot of the share and delete the file
share_snapshot = self.fs.snapshot_share(self.share_name)
self.fs.delete_file(self.share_name, self.directory_name, file_name)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
with open(FILE_PATH, 'wb') as stream:
file = self.fs.get_file_to_stream(self.share_name, self.directory_name, file_name, stream,
progress_callback=callback, snapshot=share_snapshot.snapshot)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(file_data, actual)
self.assert_download_progress(len(file_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE, progress)
def test_get_file_to_path(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
# Act
file = self.fs.get_file_to_path(self.share_name, self.directory_name, self.byte_file, FILE_PATH)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
def test_get_file_to_path_with_progress(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_path(
self.share_name, self.directory_name, self.byte_file, FILE_PATH, progress_callback=callback)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
self.assert_download_progress(len(self.byte_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE,
progress)
@record
def test_get_file_to_path_non_parallel(self):
# Arrange
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_path(
self.share_name, self.directory_name, self.byte_file, FILE_PATH,
progress_callback=callback, max_connections=1)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
self.assert_download_progress(len(self.byte_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE,
progress)
@record
def test_get_file_to_path_small(self):
# Arrange
file_data = self.get_random_bytes(1024)
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, file_data)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_path(self.share_name, self.directory_name, file_name, FILE_PATH,
progress_callback=callback)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(file_data, actual)
self.assert_download_progress(len(file_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE, progress)
def test_ranged_get_file_to_path(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
# Act
end_range = self.fs.MAX_SINGLE_GET_SIZE + 1024
file = self.fs.get_file_to_path(self.share_name, self.directory_name, self.byte_file, FILE_PATH,
start_range=1, end_range=end_range)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data[1:end_range + 1], actual)
def test_ranged_get_file_to_path_with_single_byte(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
# Act
end_range = self.fs.MAX_SINGLE_GET_SIZE + 1024
file = self.fs.get_file_to_path(self.share_name, self.directory_name, self.byte_file, FILE_PATH,
start_range=0, end_range=0)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(1, len(actual))
self.assertEqual(self.byte_data[0], actual[0])
@record
def test_ranged_get_file_to_bytes_with_zero_byte(self):
# Arrange
file_data = b''
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, file_data)
# Act
# the get request should fail in this case since the blob is empty and yet there is a range specified
with self.assertRaises(AzureHttpError):
self.fs.get_file_to_bytes(self.share_name, self.directory_name, file_name, start_range=0, end_range=5)
with self.assertRaises(AzureHttpError):
self.fs.get_file_to_bytes(self.share_name, self.directory_name, file_name, start_range=3, end_range=5)
def test_ranged_get_file_to_path_with_progress(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
progress = []
def callback(current, total):
progress.append((current, total))
# Act
start_range = 3
end_range = self.fs.MAX_SINGLE_GET_SIZE + 1024
file = self.fs.get_file_to_path(self.share_name, self.directory_name, self.byte_file, FILE_PATH,
start_range=start_range, end_range=end_range,
progress_callback=callback)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data[start_range:end_range + 1], actual)
self.assert_download_progress(end_range - start_range + 1, self.fs.MAX_CHUNK_GET_SIZE,
self.fs.MAX_SINGLE_GET_SIZE, progress)
@record
def test_ranged_get_file_to_path_small(self):
# Arrange
# Act
file = self.fs.get_file_to_path(self.share_name, self.directory_name, self.byte_file, FILE_PATH,
start_range=1, end_range=4)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data[1:5], actual)
@record
def test_ranged_get_file_to_path_non_parallel(self):
# Arrange
# Act
file = self.fs.get_file_to_path(self.share_name, self.directory_name, self.byte_file, FILE_PATH,
start_range=1, end_range=3, max_connections=1)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data[1:4], actual)
@record
def test_ranged_get_file_to_path_invalid_range_parallel(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
file_size = self.fs.MAX_SINGLE_GET_SIZE + 1
file_data = self.get_random_bytes(file_size)
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, file_data)
# Act
end_range = 2 * self.fs.MAX_SINGLE_GET_SIZE
file = self.fs.get_file_to_path(self.share_name, self.directory_name, file_name, FILE_PATH,
start_range=1, end_range=end_range)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(file_data[1:file_size], actual)
@record
def test_ranged_get_file_to_path_invalid_range_non_parallel(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
file_size = 1024
file_data = self.get_random_bytes(file_size)
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, file_data)
# Act
end_range = 2 * self.fs.MAX_SINGLE_GET_SIZE
file = self.fs.get_file_to_path(self.share_name, self.directory_name, file_name, FILE_PATH,
start_range=1, end_range=end_range)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(file_data[1:file_size], actual)
def test_get_file_to_path_with_mode(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
with open(FILE_PATH, 'wb') as stream:
stream.write(b'abcdef')
# Act
# Assert
with self.assertRaises(BaseException):
file = self.fs.get_file_to_path(self.share_name, self.directory_name, self.byte_file, FILE_PATH, 'a+b')
def test_get_file_to_path_with_mode_non_parallel(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
with open(FILE_PATH, 'wb') as stream:
stream.write(b'abcdef')
# Act
file = self.fs.get_file_to_path(
self.share_name, self.directory_name, self.byte_file, FILE_PATH, 'a+b', max_connections=1)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(b'abcdef' + self.byte_data, actual)
def test_get_file_to_text(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
text_file = self.get_resource_name('textfile')
text_data = self.get_random_text_data(self.fs.MAX_SINGLE_GET_SIZE + 1)
self.fs.create_file_from_text(self.share_name, self.directory_name, text_file, text_data)
# Act
file = self.fs.get_file_to_text(self.share_name, self.directory_name, text_file)
# Assert
self.assertEqual(text_data, file.content)
def test_get_file_to_text_with_progress(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
text_file = self.get_resource_name('textfile')
text_data = self.get_random_text_data(self.fs.MAX_SINGLE_GET_SIZE + 1)
self.fs.create_file_from_text(self.share_name, self.directory_name, text_file, text_data)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_text(self.share_name, self.directory_name, text_file, progress_callback=callback)
# Assert
self.assertEqual(text_data, file.content)
self.assert_download_progress(len(text_data.encode('utf-8')), self.fs.MAX_CHUNK_GET_SIZE,
self.fs.MAX_SINGLE_GET_SIZE, progress)
@record
def test_get_file_to_text_non_parallel(self):
# Arrange
text_file = self._get_file_reference()
text_data = self.get_random_text_data(self.fs.MAX_SINGLE_GET_SIZE + 1)
self.fs.create_file_from_text(self.share_name, self.directory_name, text_file, text_data)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_text(self.share_name, self.directory_name, text_file, max_connections=1,
progress_callback=callback)
# Assert
self.assertEqual(text_data, file.content)
self.assert_download_progress(len(text_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE,
progress)
@record
def test_get_file_to_text_small(self):
# Arrange
file_data = self.get_random_text_data(1024)
file_name = self._get_file_reference()
self.fs.create_file_from_text(self.share_name, self.directory_name, file_name, file_data)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_text(self.share_name, self.directory_name, file_name, progress_callback=callback)
# Assert
self.assertEqual(file_data, file.content)
self.assert_download_progress(len(file_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE, progress)
@record
def test_get_file_to_text_with_encoding(self):
# Arrange
text = u'hello 啊齄丂狛狜 world'
data = text.encode('utf-16')
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, data)
# Act
file = self.fs.get_file_to_text(self.share_name, self.directory_name, file_name, 'utf-16')
# Assert
self.assertEqual(text, file.content)
@record
def test_get_file_to_text_with_encoding_and_progress(self):
# Arrange
text = u'hello 啊齄丂狛狜 world'
data = text.encode('utf-16')
file_name = self._get_file_reference()
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, data)
# Act
progress = []
def callback(current, total):
progress.append((current, total))
file = self.fs.get_file_to_text(
self.share_name, self.directory_name, file_name, 'utf-16', progress_callback=callback)
# Assert
self.assertEqual(text, file.content)
self.assert_download_progress(len(data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE, progress)
@record
def test_get_file_non_seekable(self):
# Arrange
# Act
with open(FILE_PATH, 'wb') as stream:
non_seekable_stream = StorageGetFileTest.NonSeekableFile(stream)
file = self.fs.get_file_to_stream(self.share_name, self.directory_name, self.byte_file, non_seekable_stream,
max_connections=1)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
def test_get_file_non_seekable_parallel(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
# Act
with open(FILE_PATH, 'wb') as stream:
non_seekable_stream = StorageGetFileTest.NonSeekableFile(stream)
with self.assertRaises(BaseException):
file = self.fs.get_file_to_stream(
self.share_name, self.directory_name, self.byte_file, non_seekable_stream)
# Assert
@record
def test_get_file_non_seekable_from_snapshot(self):
# Arrange
# Create a snapshot of the share and delete the file
share_snapshot = self.fs.snapshot_share(self.share_name)
self.fs.delete_file(self.share_name, self.directory_name, self.byte_file)
# Act
with open(FILE_PATH, 'wb') as stream:
non_seekable_stream = StorageGetFileTest.NonSeekableFile(stream)
file = self.fs.get_file_to_stream(self.share_name, self.directory_name, self.byte_file, non_seekable_stream,
max_connections=1, snapshot=share_snapshot.snapshot)
# Assert
self.assertIsInstance(file, File)
with open(FILE_PATH, 'rb') as stream:
actual = stream.read()
self.assertEqual(self.byte_data, actual)
def test_get_file_non_seekable_parallel_from_snapshot(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
# Create a snapshot of the share and delete the file
share_snapshot = self.fs.snapshot_share(self.share_name)
self.fs.delete_file(self.share_name, self.directory_name, self.byte_file)
# Act
with open(FILE_PATH, 'wb') as stream:
non_seekable_stream = StorageGetFileTest.NonSeekableFile(stream)
with self.assertRaises(BaseException):
self.fs.get_file_to_stream(
self.share_name, self.directory_name,
self.byte_file, non_seekable_stream, snapshot=share_snapshot.snapshot)
@record
def test_get_file_exact_get_size(self):
# Arrange
file_name = self._get_file_reference()
byte_data = self.get_random_bytes(self.fs.MAX_SINGLE_GET_SIZE)
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, byte_data)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, file_name, progress_callback=callback)
# Assert
self.assertEqual(byte_data, file.content)
self.assert_download_progress(len(byte_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE, progress)
def test_get_file_exact_chunk_size(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
file_name = self._get_file_reference()
byte_data = self.get_random_bytes(self.fs.MAX_SINGLE_GET_SIZE + self.fs.MAX_CHUNK_GET_SIZE)
self.fs.create_file_from_bytes(self.share_name, self.directory_name, file_name, byte_data)
progress = []
def callback(current, total):
progress.append((current, total))
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, file_name, progress_callback=callback)
# Assert
self.assertEqual(byte_data, file.content)
self.assert_download_progress(len(byte_data), self.fs.MAX_CHUNK_GET_SIZE, self.fs.MAX_SINGLE_GET_SIZE, progress)
def test_get_file_with_md5(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
# Arrange
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, self.byte_file, validate_content=True)
# Assert
self.assertEqual(self.byte_data, file.content)
def test_get_file_range_with_md5(self):
# parallel tests introduce random order of requests, can only run live
if TestMode.need_recording_file(self.test_mode):
return
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, self.byte_file, start_range=0,
end_range=1024, validate_content=True)
# Assert
self.assertFalse(hasattr(file.properties.content_settings, 'content_md5'))
# Arrange
props = self.fs.get_file_properties(self.share_name, self.directory_name, self.byte_file)
props.properties.content_settings.content_md5 = 'MDAwMDAwMDA='
self.fs.set_file_properties(self.share_name, self.directory_name, self.byte_file,
props.properties.content_settings)
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, self.byte_file, start_range=0,
end_range=1024, validate_content=True)
# Assert
self.assertEqual('MDAwMDAwMDA=', file.properties.content_settings.content_md5)
@record
def test_get_file_server_encryption(self):
# Act
file = self.fs.get_file_to_bytes(self.share_name, self.directory_name, self.byte_file, start_range=0,
end_range=1024, validate_content=True)
# Assert
if self.is_file_encryption_enabled():
self.assertTrue(file.properties.server_encrypted)
else:
self.assertFalse(file.properties.server_encrypted)
@record
def test_get_file_properties_server_encryption(self):
# Act
props = self.fs.get_file_properties(self.share_name, self.directory_name, self.byte_file)
# Assert
if self.is_file_encryption_enabled():
self.assertTrue(props.properties.server_encrypted)
else:
self.assertFalse(props.properties.server_encrypted)
# ------------------------------------------------------------------------------
if __name__ == '__main__':
unittest.main()
|
06826d1b8460d254da39f6ab42f62f209f05443e
|
62a65e9d151396b1ca640bd5c65f325fe99d1e12
|
/tests/syntax/test_properties.py
|
f7366303418c895207d6a810b82ae172b5ed073f
|
[
"BSD-3-Clause"
] |
permissive
|
BerkeleyLearnVerify/Scenic
|
a4266c49c419a97bb9802ec5e4a535c251e83061
|
b397042601218ee77c82e3e835fa26820184245e
|
refs/heads/main
| 2023-08-31T17:44:34.774326
| 2023-08-30T23:55:22
| 2023-08-30T23:55:22
| 170,370,724
| 207
| 73
|
NOASSERTION
| 2023-09-13T20:03:20
| 2019-02-12T18:38:02
|
Python
|
UTF-8
|
Python
| false
| false
| 3,055
|
py
|
test_properties.py
|
import numpy as np
import pytest
from scenic.core.errors import SpecifierError
from tests.utils import compileScenic, sampleEgoFrom
def test_position_wrong_type():
with pytest.raises(TypeError):
compileScenic("ego = new Object with position 4")
def test_position_oriented_point():
sampleEgoFrom(
"""
a = new OrientedPoint at 1@0
b = new OrientedPoint at 0@1
ego = new Object with position Uniform(a, b)
"""
)
def test_position_numpy_types():
ego = sampleEgoFrom(
"""
import numpy as np
ego = new Object with position np.single(3.4) @ np.single(7)
"""
)
assert tuple(ego.position) == pytest.approx((3.4, 7, 0))
def test_yaw_wrong_type():
with pytest.raises(TypeError):
compileScenic("ego = new Object with yaw 4 @ 1")
def test_yaw_numpy_types():
ego = sampleEgoFrom(
"""
import numpy as np
ego = new Object with yaw np.single(3.1)
"""
)
assert ego.yaw == pytest.approx(3.1)
def test_left():
ego = sampleEgoFrom(
"""
other = new Object with width 4
ego = new Object at other.left offset by 0@5
"""
)
assert tuple(ego.position) == pytest.approx((-2, 5, 0))
def test_right():
ego = sampleEgoFrom(
"""
other = new Object with width 4
ego = new Object at other.right offset by 0@5
"""
)
assert tuple(ego.position) == pytest.approx((2, 5, 0))
def test_front():
ego = sampleEgoFrom(
"""
other = new Object with length 4
ego = new Object at other.front offset by 0@5
"""
)
assert tuple(ego.position) == pytest.approx((0, 7, 0))
def test_back():
ego = sampleEgoFrom(
"""
other = new Object with length 4
ego = new Object at other.back offset by 0@-5
"""
)
assert tuple(ego.position) == pytest.approx((0, -7, 0))
def test_frontLeft():
ego = sampleEgoFrom(
"""
other = new Object with length 4, with width 2
ego = new Object at other.frontLeft offset by 0@5
"""
)
assert tuple(ego.position) == pytest.approx((-1, 7, 0))
def test_frontRight():
ego = sampleEgoFrom(
"""
other = new Object with length 4, with width 2
ego = new Object at other.frontRight offset by 0@5
"""
)
assert tuple(ego.position) == pytest.approx((1, 7, 0))
def test_backLeft():
ego = sampleEgoFrom(
"""
other = new Object with length 4, with width 2
ego = new Object at other.backLeft offset by 0@-5
"""
)
assert tuple(ego.position) == pytest.approx((-1, -7, 0))
def test_backRight():
ego = sampleEgoFrom(
"""
other = new Object with length 4, with width 2
ego = new Object at other.backRight offset by 0@-5
"""
)
assert tuple(ego.position) == pytest.approx((1, -7, 0))
def test_heading_set_directly():
with pytest.raises(SpecifierError):
compileScenic("ego = new Object with heading 4")
|
1546728203793a028134ad4cc6e2589b9591eb01
|
3be1b10269c9d976c1141f3017936782b8d024a9
|
/suod/test/test_model_save_load.py
|
f744687e3116b71ddfbc43033b36516a67d8703d
|
[
"BSD-2-Clause"
] |
permissive
|
yzhao062/SUOD
|
a723c923024980b2bfad5a007ae40e0ceb1c2642
|
a733f2b704fbc98059a35760ce820c93eed55a77
|
refs/heads/master
| 2023-07-20T12:00:34.403125
| 2023-07-16T11:29:26
| 2023-07-16T11:29:26
| 222,815,883
| 376
| 51
|
BSD-2-Clause
| 2023-04-07T01:12:52
| 2019-11-20T00:23:54
|
Python
|
UTF-8
|
Python
| false
| false
| 4,063
|
py
|
test_model_save_load.py
|
# -*- coding: utf-8 -*-
import os
import sys
import unittest
import numpy as np
# temporary solution for relative imports in case pyod is not installed
# if suod
# is installed, no need to use the following line
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from suod.models.base import SUOD
from pyod.utils.data import generate_data
from pyod.models.lof import LOF
from pyod.models.pca import PCA
from pyod.models.hbos import HBOS
from pyod.models.lscp import LSCP
from joblib import dump, load
from ..utils.utility import _get_sklearn_version
class TestModelSaveLoad(unittest.TestCase):
def setUp(self):
self.n_train = 1000
self.n_test = 500
self.contamination = 0.1
self.roc_floor = 0.6
self.random_state = 42
self.X_train, self.X_test, self.y_train, self.y_test = generate_data(
n_train=self.n_train, n_test=self.n_test, behaviour='new',
contamination=self.contamination, random_state=self.random_state)
self.base_estimators = [
LOF(n_neighbors=5, contamination=self.contamination),
LOF(n_neighbors=15, contamination=self.contamination),
LOF(n_neighbors=25, contamination=self.contamination),
LOF(n_neighbors=35, contamination=self.contamination),
LOF(n_neighbors=45, contamination=self.contamination),
HBOS(contamination=self.contamination),
PCA(contamination=self.contamination),
LSCP(detector_list=[
LOF(n_neighbors=5, contamination=self.contamination),
LOF(n_neighbors=15, contamination=self.contamination)],
random_state=self.random_state)
]
this_directory = os.path.abspath(os.path.dirname(__file__))
sklearn_version = _get_sklearn_version()
if sklearn_version[:3] >= '1.3':
self.cost_forecast_loc_fit_ = os.path.join(this_directory,
'bps_train.joblib')
self.cost_forecast_loc_pred_ = os.path.join(this_directory,
'bps_prediction.joblib')
else:
self.cost_forecast_loc_fit_ = os.path.join(this_directory,
'bps_train_old.joblib')
self.cost_forecast_loc_pred_ = os.path.join(this_directory,
'bps_prediction_old.joblib')
self.model = SUOD(base_estimators=self.base_estimators, n_jobs=2,
rp_flag_global=True, bps_flag=True,
contamination=self.contamination,
approx_flag_global=True,
cost_forecast_loc_fit=self.cost_forecast_loc_fit_,
cost_forecast_loc_pred=self.cost_forecast_loc_pred_,
verbose=True)
def test_save(self):
self.model.fit(self.X_train) # fit all models with X
self.model.approximate(
self.X_train) # conduct model approximation if it is enabled
# save the model
dump(self.model, 'model.joblib')
assert (os.path.exists('model.joblib'))
os.remove('model.joblib')
def test_load(self):
self.model.fit(self.X_train) # fit all models with X
self.model.approximate(
self.X_train) # conduct model approximation if it is enabled
# save the model
dump(self.model, 'model.joblib')
model = load('model.joblib')
predicted_labels = model.predict(self.X_test) # predict labels
predicted_scores = model.decision_function(
self.X_test) # predict scores
predicted_probs = model.predict_proba(self.X_test) # predict scores
assert (len(predicted_labels) != 0)
# assert (predicted_scores)
# assert (predicted_probs)
def tearDown(self):
if os.path.exists('model.joblib'):
os.remove('model.joblib')
|
45695760c59c6298e43b1f0119ba2928b521bda2
|
e7f2a8c466c14b9821e59740ed0407107e1254a4
|
/tests/cli/test_rasa_evaluate_markers.py
|
f9610ef23725f184b77922cf7af26d8fca9ae292
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"MIT"
] |
permissive
|
RasaHQ/rasa
|
4a31134308a9a4d8824fe7faef02526accdd0f19
|
50857610bdf0c26dc61f3203a6cbb4bcf193768c
|
refs/heads/main
| 2023-08-28T01:53:56.981600
| 2023-08-25T10:20:49
| 2023-08-25T10:20:49
| 70,908,208
| 13,167
| 3,739
|
Apache-2.0
| 2023-09-14T09:54:40
| 2016-10-14T12:27:49
|
Python
|
UTF-8
|
Python
| false
| false
| 5,715
|
py
|
test_rasa_evaluate_markers.py
|
from pathlib import Path
from typing import Callable, Text, Tuple, Dict, Any
import csv
import pytest
from _pytest.pytester import RunResult
import rasa.cli.evaluate
from rasa.shared.core.events import ActionExecuted, SlotSet, UserUttered
from rasa.shared.core.trackers import DialogueStateTracker
from rasa.shared.core.constants import ACTION_SESSION_START_NAME
from rasa.shared.core.domain import Domain
from rasa.core.tracker_store import SQLTrackerStore
from rasa.cli.evaluate import STATS_SESSION_SUFFIX, STATS_OVERALL_SUFFIX
from tests.conftest import write_endpoint_config_to_yaml
from tests.cli.conftest import RASA_EXE
@pytest.fixture
def marker_sqlite_tracker(tmp_path: Path) -> Tuple[SQLTrackerStore, Text]:
domain = Domain.empty()
db_path = str(tmp_path / "rasa.db")
tracker_store = SQLTrackerStore(dialect="sqlite", db=db_path)
for i in range(5):
tracker = DialogueStateTracker(str(i), None)
tracker.update_with_events([SlotSet(str(j), "slot") for j in range(5)], domain)
tracker.update(ActionExecuted(ACTION_SESSION_START_NAME))
tracker.update(UserUttered("hello"))
tracker.update_with_events(
[SlotSet(str(5 + j), "slot") for j in range(5)], domain
)
tracker_store.save(tracker)
return tracker_store, db_path
def write_markers_config_to_yaml(
path: Path, data: Dict[Text, Any], markers_filename: Text = "markers.yml"
) -> Path:
markers_path = path / markers_filename
# write markers config to file
rasa.shared.utils.io.write_yaml(data, markers_path)
return markers_path
def test_evaluate_markers_help(run: Callable[..., RunResult]):
output = run("evaluate", "markers", "--help")
help_text = f"""usage: {RASA_EXE} evaluate markers [-h] [-v] [-vv] [--quiet]
[--logging-config-file LOGGING_CONFIG_FILE]
{{first_n,sample_n,all}} ..."""
lines = [line.strip() for line in help_text.split("\n")]
# expected help text lines should appear somewhere in the output
printed_help = set([line.strip() for line in output.outlines])
for line in lines:
assert line in printed_help
def test_evaluate_markers_first_n_help(run: Callable[..., RunResult]):
# We need to specify an output_filename as that's the first positional parameter
output = run("evaluate", "markers", "first_n", "--help")
help_text = f"""usage: {RASA_EXE} evaluate markers first_n [-h] [-v] [-vv] [--quiet]
[--logging-config-file LOGGING_CONFIG_FILE]
[--config CONFIG]
[--no-stats | --stats-file-prefix [STATS_FILE_PREFIX]]
[--endpoints ENDPOINTS] [-d DOMAIN]
count output_filename"""
lines = [line.strip() for line in help_text.split("\n")]
# expected help text lines should appear somewhere in the output
printed_help = set([line.strip() for line in output.outlines])
for line in lines:
assert line in printed_help
def test_evaluate_markers_sample_n_help(run: Callable[..., RunResult]):
# We need to specify an output_filename as that's the first positional parameter
output = run("evaluate", "markers", "sample_n", "--help")
help_text = f"""usage: {RASA_EXE} evaluate markers sample_n [-h] [-v] [-vv] [--quiet]
[--logging-config-file LOGGING_CONFIG_FILE]
[--seed SEED] [--config CONFIG]
[--no-stats | --stats-file-prefix [STATS_FILE_PREFIX]]
[--endpoints ENDPOINTS] [-d DOMAIN]
count output_filename""" # noqa: E501
lines = [line.strip() for line in help_text.split("\n")]
# expected help text lines should appear somewhere in the output
printed_help = set([line.strip() for line in output.outlines])
for line in lines:
assert line in printed_help
def test_evaluate_markers_all_help(run: Callable[..., RunResult]):
# We need to specify an output_filename as that's the first positional parameter
output = run("evaluate", "markers", "all", "--help")
help_text = f"""usage: {RASA_EXE} evaluate markers all [-h] [-v] [-vv] [--quiet]
[--logging-config-file LOGGING_CONFIG_FILE]
[--config CONFIG]
[--no-stats | --stats-file-prefix [STATS_FILE_PREFIX]]
[--endpoints ENDPOINTS] [-d DOMAIN]
output_filename"""
lines = [line.strip() for line in help_text.split("\n")]
# expected help text lines should appear somewhere in the output
printed_help = set([line.strip() for line in output.outlines])
for line in lines:
assert line in printed_help
def test_markers_cli_results_save_correctly(
marker_sqlite_tracker: Tuple[SQLTrackerStore, Text], tmp_path: Path
):
_, db_path = marker_sqlite_tracker
endpoints_path = write_endpoint_config_to_yaml(
tmp_path,
{"tracker_store": {"type": "sql", "db": db_path.replace("\\", "\\\\")}},
)
markers_path = write_markers_config_to_yaml(
tmp_path, {"marker1": {"slot_was_set": "2"}, "marker2": {"slot_was_set": "7"}}
)
results_path = tmp_path / "results.csv"
stats_file_prefix = tmp_path / "statistics"
rasa.cli.evaluate._run_markers(
seed=None,
count=10,
endpoint_config=endpoints_path,
strategy="first_n",
domain_path=None,
config=markers_path,
output_filename=results_path,
stats_file_prefix=stats_file_prefix,
)
for expected_output in [
results_path,
tmp_path / ("statistics" + STATS_SESSION_SUFFIX),
tmp_path / ("statistics" + STATS_OVERALL_SUFFIX),
]:
with expected_output.open(mode="r") as results:
result_reader = csv.DictReader(results)
# Loop over entire file to ensure nothing in the file causes any errors
for _ in result_reader:
continue
|
f764682b3efead2e1f6d91aad584c2020a488653
|
f305f84ea6f721c2391300f0a60e21d2ce14f2a5
|
/22_专题/小值域搜答案/1906. 查询差绝对值的最小值-个数前缀和.py
|
3804494f5404aae1c0915fed2b0077ef92db84a9
|
[] |
no_license
|
981377660LMT/algorithm-study
|
f2ada3e6959338ae1bc21934a84f7314a8ecff82
|
7e79e26bb8f641868561b186e34c1127ed63c9e0
|
refs/heads/master
| 2023-09-01T18:26:16.525579
| 2023-09-01T12:21:58
| 2023-09-01T12:21:58
| 385,861,235
| 225
| 24
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,866
|
py
|
1906. 查询差绝对值的最小值-个数前缀和.py
|
# 1 <= nums[i] <= 100
# 2 <= nums.length <= 105
# 1 <= queries.length <= 2 * 104
# 看到 100 这个数据,就知道可以暴力枚举了,直接开数组
# 我们需要知道不同区间之间有哪些数,所以前缀统计每个区间不同的数的个数(1-100)
from typing import List
INF = int(1e20)
class Solution:
def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:
max_ = max(nums)
# n = len(nums)
# preSum = [[0] * (max_ + 1) for _ in range(n + 1)]
# for i in range(1, n + 1):
# preSum[i][nums[i - 1]] += 1
# for j in range((max_ + 1)):
# preSum[i][j] += preSum[i - 1][j]
preSum = [[0] * (max_ + 1)]
for num in nums:
cur = preSum[-1][:]
cur[num] += 1
preSum.append(cur)
res = []
for left, right in queries:
minDiff = INF
pre = -INF
for cur in range(1, (max_ + 1)):
# 我们通过`个数前缀和数组求得l到r之间有哪些数存在`
if preSum[right + 1][cur] - preSum[left][cur] > 0:
minDiff = min(minDiff, cur - pre)
pre = cur
res.append(minDiff if minDiff != INF else -1)
return res
print(Solution().minDifference(nums=[1, 3, 4, 8], queries=[[0, 1], [1, 2], [2, 3], [0, 3]]))
# 输出:[2,1,4,1]
# 解释:查询结果如下:
# - queries[0] = [0,1]:子数组是 [1,3] ,差绝对值的最小值为 |1-3| = 2 。
# - queries[1] = [1,2]:子数组是 [3,4] ,差绝对值的最小值为 |3-4| = 1 。
# - queries[2] = [2,3]:子数组是 [4,8] ,差绝对值的最小值为 |4-8| = 4 。
# - queries[3] = [0,3]:子数组是 [1,3,4,8] ,差的绝对值的最小值为 |3-4| = 1 。
|
181be2b42309d898128a39e82aaa3b8adfde628c
|
93713f46f16f1e29b725f263da164fed24ebf8a8
|
/Library/lib/python3.7/site-packages/networkx/algorithms/centrality/tests/test_load_centrality.py
|
880ab27983d8994dfbedd88c69ea2d13a3f5dbc0
|
[
"BSD-3-Clause"
] |
permissive
|
holzschu/Carnets
|
b83d15136d25db640cea023abb5c280b26a9620e
|
1ad7ec05fb1e3676ac879585296c513c3ee50ef9
|
refs/heads/master
| 2023-02-20T12:05:14.980685
| 2023-02-13T15:59:23
| 2023-02-13T15:59:23
| 167,671,526
| 541
| 36
|
BSD-3-Clause
| 2022-11-29T03:08:22
| 2019-01-26T09:26:46
|
Python
|
UTF-8
|
Python
| false
| false
| 11,515
|
py
|
test_load_centrality.py
|
#!/usr/bin/env python
from nose.tools import *
import networkx as nx
class TestLoadCentrality:
def setUp(self):
G = nx.Graph()
G.add_edge(0, 1, weight=3)
G.add_edge(0, 2, weight=2)
G.add_edge(0, 3, weight=6)
G.add_edge(0, 4, weight=4)
G.add_edge(1, 3, weight=5)
G.add_edge(1, 5, weight=5)
G.add_edge(2, 4, weight=1)
G.add_edge(3, 4, weight=2)
G.add_edge(3, 5, weight=1)
G.add_edge(4, 5, weight=4)
self.G = G
self.exact_weighted = {0: 4.0, 1: 0.0, 2: 8.0, 3: 6.0, 4: 8.0, 5: 0.0}
self.K = nx.krackhardt_kite_graph()
self.P3 = nx.path_graph(3)
self.P4 = nx.path_graph(4)
self.K5 = nx.complete_graph(5)
self.C4 = nx.cycle_graph(4)
self.T = nx.balanced_tree(r=2, h=2)
self.Gb = nx.Graph()
self.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3),
(2, 4), (4, 5), (3, 5)])
self.F = nx.florentine_families_graph()
self.LM = nx.les_miserables_graph()
self.D = nx.cycle_graph(3, create_using=nx.DiGraph())
self.D.add_edges_from([(3, 0), (4, 3)])
def test_not_strongly_connected(self):
b = nx.load_centrality(self.D)
result = {0: 5. / 12,
1: 1. / 4,
2: 1. / 12,
3: 1. / 4,
4: 0.000}
for n in sorted(self.D):
assert_almost_equal(result[n], b[n], places=3)
assert_almost_equal(result[n], nx.load_centrality(self.D, n), places=3)
def test_weighted_load(self):
b = nx.load_centrality(self.G, weight='weight', normalized=False)
for n in sorted(self.G):
assert_equal(b[n], self.exact_weighted[n])
def test_k5_load(self):
G = self.K5
c = nx.load_centrality(G)
d = {0: 0.000,
1: 0.000,
2: 0.000,
3: 0.000,
4: 0.000}
for n in sorted(G):
assert_almost_equal(c[n], d[n], places=3)
def test_p3_load(self):
G = self.P3
c = nx.load_centrality(G)
d = {0: 0.000,
1: 1.000,
2: 0.000}
for n in sorted(G):
assert_almost_equal(c[n], d[n], places=3)
c = nx.load_centrality(G, v=1)
assert_almost_equal(c, 1.0)
c = nx.load_centrality(G, v=1, normalized=True)
assert_almost_equal(c, 1.0)
def test_p2_load(self):
G = nx.path_graph(2)
c = nx.load_centrality(G)
d = {0: 0.000,
1: 0.000}
for n in sorted(G):
assert_almost_equal(c[n], d[n], places=3)
def test_krackhardt_load(self):
G = self.K
c = nx.load_centrality(G)
d = {0: 0.023,
1: 0.023,
2: 0.000,
3: 0.102,
4: 0.000,
5: 0.231,
6: 0.231,
7: 0.389,
8: 0.222,
9: 0.000}
for n in sorted(G):
assert_almost_equal(c[n], d[n], places=3)
def test_florentine_families_load(self):
G = self.F
c = nx.load_centrality(G)
d = {'Acciaiuoli': 0.000,
'Albizzi': 0.211,
'Barbadori': 0.093,
'Bischeri': 0.104,
'Castellani': 0.055,
'Ginori': 0.000,
'Guadagni': 0.251,
'Lamberteschi': 0.000,
'Medici': 0.522,
'Pazzi': 0.000,
'Peruzzi': 0.022,
'Ridolfi': 0.117,
'Salviati': 0.143,
'Strozzi': 0.106,
'Tornabuoni': 0.090}
for n in sorted(G):
assert_almost_equal(c[n], d[n], places=3)
def test_les_miserables_load(self):
G = self.LM
c = nx.load_centrality(G)
d = {'Napoleon': 0.000,
'Myriel': 0.177,
'MlleBaptistine': 0.000,
'MmeMagloire': 0.000,
'CountessDeLo': 0.000,
'Geborand': 0.000,
'Champtercier': 0.000,
'Cravatte': 0.000,
'Count': 0.000,
'OldMan': 0.000,
'Valjean': 0.567,
'Labarre': 0.000,
'Marguerite': 0.000,
'MmeDeR': 0.000,
'Isabeau': 0.000,
'Gervais': 0.000,
'Listolier': 0.000,
'Tholomyes': 0.043,
'Fameuil': 0.000,
'Blacheville': 0.000,
'Favourite': 0.000,
'Dahlia': 0.000,
'Zephine': 0.000,
'Fantine': 0.128,
'MmeThenardier': 0.029,
'Thenardier': 0.075,
'Cosette': 0.024,
'Javert': 0.054,
'Fauchelevent': 0.026,
'Bamatabois': 0.008,
'Perpetue': 0.000,
'Simplice': 0.009,
'Scaufflaire': 0.000,
'Woman1': 0.000,
'Judge': 0.000,
'Champmathieu': 0.000,
'Brevet': 0.000,
'Chenildieu': 0.000,
'Cochepaille': 0.000,
'Pontmercy': 0.007,
'Boulatruelle': 0.000,
'Eponine': 0.012,
'Anzelma': 0.000,
'Woman2': 0.000,
'MotherInnocent': 0.000,
'Gribier': 0.000,
'MmeBurgon': 0.026,
'Jondrette': 0.000,
'Gavroche': 0.164,
'Gillenormand': 0.021,
'Magnon': 0.000,
'MlleGillenormand': 0.047,
'MmePontmercy': 0.000,
'MlleVaubois': 0.000,
'LtGillenormand': 0.000,
'Marius': 0.133,
'BaronessT': 0.000,
'Mabeuf': 0.028,
'Enjolras': 0.041,
'Combeferre': 0.001,
'Prouvaire': 0.000,
'Feuilly': 0.001,
'Courfeyrac': 0.006,
'Bahorel': 0.002,
'Bossuet': 0.032,
'Joly': 0.002,
'Grantaire': 0.000,
'MotherPlutarch': 0.000,
'Gueulemer': 0.005,
'Babet': 0.005,
'Claquesous': 0.005,
'Montparnasse': 0.004,
'Toussaint': 0.000,
'Child1': 0.000,
'Child2': 0.000,
'Brujon': 0.000,
'MmeHucheloup': 0.000}
for n in sorted(G):
assert_almost_equal(c[n], d[n], places=3)
def test_unnormalized_k5_load(self):
G = self.K5
c = nx.load_centrality(G, normalized=False)
d = {0: 0.000,
1: 0.000,
2: 0.000,
3: 0.000,
4: 0.000}
for n in sorted(G):
assert_almost_equal(c[n], d[n], places=3)
def test_unnormalized_p3_load(self):
G = self.P3
c = nx.load_centrality(G, normalized=False)
d = {0: 0.000,
1: 2.000,
2: 0.000}
for n in sorted(G):
assert_almost_equal(c[n], d[n], places=3)
def test_unnormalized_krackhardt_load(self):
G = self.K
c = nx.load_centrality(G, normalized=False)
d = {0: 1.667,
1: 1.667,
2: 0.000,
3: 7.333,
4: 0.000,
5: 16.667,
6: 16.667,
7: 28.000,
8: 16.000,
9: 0.000}
for n in sorted(G):
assert_almost_equal(c[n], d[n], places=3)
def test_unnormalized_florentine_families_load(self):
G = self.F
c = nx.load_centrality(G, normalized=False)
d = {'Acciaiuoli': 0.000,
'Albizzi': 38.333,
'Barbadori': 17.000,
'Bischeri': 19.000,
'Castellani': 10.000,
'Ginori': 0.000,
'Guadagni': 45.667,
'Lamberteschi': 0.000,
'Medici': 95.000,
'Pazzi': 0.000,
'Peruzzi': 4.000,
'Ridolfi': 21.333,
'Salviati': 26.000,
'Strozzi': 19.333,
'Tornabuoni': 16.333}
for n in sorted(G):
assert_almost_equal(c[n], d[n], places=3)
def test_load_betweenness_difference(self):
# Difference Between Load and Betweenness
# --------------------------------------- The smallest graph
# that shows the difference between load and betweenness is
# G=ladder_graph(3) (Graph B below)
# Graph A and B are from Tao Zhou, Jian-Guo Liu, Bing-Hong
# Wang: Comment on "Scientific collaboration
# networks. II. Shortest paths, weighted networks, and
# centrality". https://arxiv.org/pdf/physics/0511084
# Notice that unlike here, their calculation adds to 1 to the
# betweennes of every node i for every path from i to every
# other node. This is exactly what it should be, based on
# Eqn. (1) in their paper: the eqn is B(v) = \sum_{s\neq t,
# s\neq v}{\frac{\sigma_{st}(v)}{\sigma_{st}}}, therefore,
# they allow v to be the target node.
# We follow Brandes 2001, who follows Freeman 1977 that make
# the sum for betweenness of v exclude paths where v is either
# the source or target node. To agree with their numbers, we
# must additionally, remove edge (4,8) from the graph, see AC
# example following (there is a mistake in the figure in their
# paper - personal communication).
# A = nx.Graph()
# A.add_edges_from([(0,1), (1,2), (1,3), (2,4),
# (3,5), (4,6), (4,7), (4,8),
# (5,8), (6,9), (7,9), (8,9)])
B = nx.Graph() # ladder_graph(3)
B.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)])
c = nx.load_centrality(B, normalized=False)
d = {0: 1.750,
1: 1.750,
2: 6.500,
3: 6.500,
4: 1.750,
5: 1.750}
for n in sorted(B):
assert_almost_equal(c[n], d[n], places=3)
def test_c4_edge_load(self):
G = self.C4
c = nx.edge_load_centrality(G)
d = {(0, 1): 6.000,
(0, 3): 6.000,
(1, 2): 6.000,
(2, 3): 6.000}
for n in G.edges():
assert_almost_equal(c[n], d[n], places=3)
def test_p4_edge_load(self):
G = self.P4
c = nx.edge_load_centrality(G)
d = {(0, 1): 6.000,
(1, 2): 8.000,
(2, 3): 6.000}
for n in G.edges():
assert_almost_equal(c[n], d[n], places=3)
def test_k5_edge_load(self):
G = self.K5
c = nx.edge_load_centrality(G)
d = {(0, 1): 5.000,
(0, 2): 5.000,
(0, 3): 5.000,
(0, 4): 5.000,
(1, 2): 5.000,
(1, 3): 5.000,
(1, 4): 5.000,
(2, 3): 5.000,
(2, 4): 5.000,
(3, 4): 5.000}
for n in G.edges():
assert_almost_equal(c[n], d[n], places=3)
def test_tree_edge_load(self):
G = self.T
c = nx.edge_load_centrality(G)
d = {(0, 1): 24.000,
(0, 2): 24.000,
(1, 3): 12.000,
(1, 4): 12.000,
(2, 5): 12.000,
(2, 6): 12.000}
for n in G.edges():
assert_almost_equal(c[n], d[n], places=3)
|
4aeb7fa1ded77ff883fdf3e4087026c99c528b09
|
0194827522f5226ee1b50daeefd500df69fff173
|
/Bot/Trade.py
|
9c19731e35dc5d425904a6cced470253dd4a956f
|
[
"Apache-2.0"
] |
permissive
|
iilunin/crypto-bot
|
99fc85904c18e0ea2e9ebd8bc469e1b26ff6b23d
|
0944641e9b2defb88d80dea03dd47c126f1c0b64
|
refs/heads/master
| 2023-03-08T21:07:39.016579
| 2022-04-24T04:01:44
| 2022-04-24T04:01:44
| 128,092,587
| 251
| 54
|
Apache-2.0
| 2023-03-02T10:47:38
| 2018-04-04T16:51:54
|
Python
|
UTF-8
|
Python
| false
| false
| 4,696
|
py
|
Trade.py
|
from collections import OrderedDict
import uuid
from typing import List
from Bot.EntryExitSettings import EntryExitSettings
from Bot.TradeEnums import Side
from Bot.StopLossSettings import StopLossSettings
from Bot.Target import *
class Trade(CustomSerializable):
# def __init__(self, symbol, side, asset, status=None, sl_settings=None, entry=None, exit=None):
def __init__(self, symbol, side, asset, status=None, *args, **kvargs):
self.side = Side(side.lower())
self.symbol = symbol.upper()
self.asset = asset.upper()
self.entry: EntryExitSettings = None
self.exit: EntryExitSettings = None
self._init_entry_exit(True, kvargs.get('entry'), self.side)
self._init_entry_exit(False, kvargs.get('exit'), self.side)
sl_settings = kvargs.get('stoploss', kvargs.get('sl_settings'))
# self.sl_settings: StopLossSettings = StopLossSettings(**sl_settings) if sl_settings else None
self.sl_settings: StopLossSettings = StopLossSettings(**sl_settings) if sl_settings else StopLossSettings({})
if status:
self.status = OrderStatus(status.lower())
else:
self.status = OrderStatus.ACTIVE if not kvargs.get('entry') else OrderStatus.NEW
self.cap = float(kvargs.get('cap')) if kvargs.get('cap') else None
self.id = kvargs.get('id', None)
if not self.id:
self.id = str(uuid.uuid4())
def _init_entry_exit(self, is_entry, data, side: Side):
if data:
if 'side' not in data:
data['side'] = (side.reverse() if is_entry else side).value
# TODO: right now there is only Smart Entry option allowed
if is_entry:
data['smart'] = True
self.entry = EntryExitSettings(is_entry=is_entry, **data)
else:
self.exit = EntryExitSettings(is_entry=is_entry, **data)
def get_cap(self, available_balance):
return min(self.cap if self.cap else available_balance, available_balance)
def is_sell(self):
return self.side.is_sell()
def has_entry(self):
return self.entry is not None
def has_exit(self):
return self.exit is not None
def has_stoploss(self):
return self.sl_settings is not None and self.sl_settings.initial_target
def has_stoploss_in_last_completed_target(self):
completed_targets = self.get_completed_exit_targets()
has_completed_targets = len(completed_targets) > 0
return has_completed_targets and completed_targets[-1].has_custom_stop()
def get_completed_exit_targets(self) -> List[Target]:
if not self.exit:
return []
return self.exit.get_completed_targets()
def get_initial_stop(self) -> Target:
if self.sl_settings:
return self.sl_settings.initial_target
return None
def serializable_dict(self):
d = OrderedDict()
d['id'] = self.id
d['asset'] = self.asset
d['symbol'] = self.symbol
d['side'] = self.side
d['status'] = self.status
if self.cap:
d['cap'] = self.format_float(self.cap)
if self.entry:
d['entry'] = self.entry
if self.exit:
d['exit'] = self.exit
if self.sl_settings:
d['stoploss'] = self.sl_settings
return d
def get_all_active_placed_targets(self) -> List[Target]:
tgt = []
if self.has_exit():
tgt.extend(self.exit.targets)
if self.has_entry():
tgt.extend(self.entry.targets)
if self.has_stoploss():
tgt.append(self.sl_settings.initial_target)
return [t for t in tgt if not t.is_completed() and t.has_id()]
def is_completed(self):
return self.status.is_completed()
def is_active(self):
return self.status.is_active()
def is_new(self):
return self.status.is_new()
def is_removed(self):
return self.status.is_removed()
def set_active(self):
self.status = OrderStatus.ACTIVE
def set_completed(self):
self.status = OrderStatus.COMPLETED
def set_removed(self):
self.status = OrderStatus.REMOVED
def __str__(self):
return '{}({}): {}'.format(self.symbol, self.id, self.side)
def describe(self):
description = self.__str__()
if self.has_entry():
description += '\n'+self.entry.describe()
if self.has_exit():
description +='\n'+self.exit.describe()
if self.has_stoploss():
description += '\n'+self.sl_settings.describe()
return description
|
dc35b82754983d62714aebd2edb3ee99928d9210
|
36437b397a855f3986325f1bfe41d7ced00b703a
|
/tests/reactor/conftest.py
|
99adc261386b2f40241b5067fc111f91d138e9fc
|
[
"MIT"
] |
permissive
|
nolar/kopf
|
090cd21550e3a86e512a4c9150dfcf5f59ac14e4
|
538df59b88d1aab7b985d703483497f73c6c4783
|
refs/heads/main
| 2023-08-29T20:39:07.128912
| 2023-08-24T15:47:40
| 2023-08-24T15:47:40
| 288,234,242
| 1,627
| 154
|
MIT
| 2023-09-14T12:31:33
| 2020-08-17T16:45:35
|
Python
|
UTF-8
|
Python
| false
| false
| 2,016
|
py
|
conftest.py
|
import asyncio
import functools
import pytest
from mock import AsyncMock
from kopf._cogs.clients.watching import infinite_watch
from kopf._core.reactor.queueing import watcher, worker as original_worker
@pytest.fixture(autouse=True)
def _autouse_resp_mocker(resp_mocker):
pass
@pytest.fixture()
def processor():
""" A mock for processor -- to be checked if the handler has been called. """
return AsyncMock()
@pytest.fixture()
def worker_spy(mocker):
""" Spy on the watcher: actually call it, but provide the mock-fields. """
spy = AsyncMock(spec=original_worker, wraps=original_worker)
return mocker.patch('kopf._core.reactor.queueing.worker', spy)
@pytest.fixture()
def worker_mock(mocker):
""" Prevent the queue consumption, so that the queues could be checked. """
return mocker.patch('kopf._core.reactor.queueing.worker')
@pytest.fixture()
def watcher_limited(mocker, settings):
""" Make event streaming finite, watcher exits after depletion. """
settings.watching.reconnect_backoff = 0
mocker.patch('kopf._cogs.clients.watching.infinite_watch',
new=functools.partial(infinite_watch, _iterations=1))
@pytest.fixture()
def watcher_in_background(settings, resource, event_loop, worker_spy, stream):
# Prevent remembering the streaming objects in the mocks.
async def do_nothing(*args, **kwargs):
pass
# Prevent any real streaming for the very beginning, before it even starts.
stream.feed([])
# Spawn a watcher in the background.
coro = watcher(
namespace=None,
resource=resource,
settings=settings,
processor=do_nothing,
)
task = event_loop.create_task(coro)
try:
# Go for a test.
yield task
finally:
# Terminate the watcher to cleanup the loop.
task.cancel()
try:
event_loop.run_until_complete(task)
except asyncio.CancelledError:
pass # cancellations are expected at this point
|
e9fe6a445e309502a9797c39db331a0cab403ab6
|
17e7ce051b02669eba49d775775c16581f66f1d5
|
/server/libs/audio_info.py
|
ef3edef74464865ad1b59437745a83ac90367d69
|
[
"MIT"
] |
permissive
|
TobKra96/music_led_strip_control
|
576d27fa592c8df7e1fee5fdf0c6a8136280b422
|
ff1b9fc41fa68e2dd70ae1a1db90b8cc13e927ca
|
refs/heads/master
| 2023-08-30T12:56:55.012671
| 2022-07-06T23:54:19
| 2022-07-06T23:54:19
| 203,447,717
| 281
| 73
|
MIT
| 2023-08-27T05:45:49
| 2019-08-20T20:14:26
|
CSS
|
UTF-8
|
Python
| false
| false
| 2,094
|
py
|
audio_info.py
|
from libs.audio_device import AudioDevice # pylint: disable=E0611, E0401
import logging
class AudioInfo:
def get_audio_devices(py_audio):
logger = logging.getLogger(__name__)
logger.debug("Get audio devices.")
audio_devices = []
try:
audio_device_count = py_audio.get_device_count()
logger.debug(f"Available audio devices (input and output): {audio_device_count}")
for i in range(0, audio_device_count):
try:
raw_audio_device = py_audio.get_device_info_by_host_api_device_index(0, i)
if raw_audio_device["maxInputChannels"] >= 1:
audio_device = AudioInfo.parse_raw_audio_device_to_audio_device(raw_audio_device)
logger.debug(f"Found audio Device: {audio_device.to_string()}")
audio_devices.append(audio_device)
except Exception as e:
logger.debug("Could not get device infos.")
logger.exception(f"Unexpected error in AudioInfo: {e}")
except Exception as e:
logger.exception(f"Unexpected error in AudioInfo: {e}")
logger.debug(f"Found {len(audio_devices)} audio devices.")
return audio_devices
def get_default_audio_device(py_audio):
logger = logging.getLogger(__name__)
default_device = AudioDevice(0, "Error", 44100)
try:
raw_default_device = py_audio.get_default_input_device_info()
default_device = AudioInfo.parse_raw_audio_device_to_audio_device(raw_default_device)
except Exception as e:
logger.exception(f"Unexpected error in AudioInfo get_default_audio_device: {e}")
return default_device
def parse_raw_audio_device_to_audio_device(raw_audio_device):
logger = logging.getLogger(__name__)
id = raw_audio_device["index"]
name = raw_audio_device["name"]
defaultSampleRate = raw_audio_device["defaultSampleRate"]
return AudioDevice(id, name, defaultSampleRate)
|
ab27d1430b9e3099b741596d4e2ea3983351b6c2
|
2d05050d0ada29f7680b4df20c10bb85b0530e45
|
/python/tvm/contrib/torch/module.py
|
cfa3ad264c3a78b39e3e54a5b09e2b619b456337
|
[
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"Zlib",
"LLVM-exception",
"BSD-2-Clause"
] |
permissive
|
apache/tvm
|
87cb617f9a131fa44e1693303aaddf70e7a4c403
|
d75083cd97ede706338ab413dbc964009456d01b
|
refs/heads/main
| 2023-09-04T11:24:26.263032
| 2023-09-04T07:26:00
| 2023-09-04T07:26:00
| 70,746,484
| 4,575
| 1,903
|
Apache-2.0
| 2023-09-14T19:06:33
| 2016-10-12T22:20:28
|
Python
|
UTF-8
|
Python
| false
| false
| 4,823
|
py
|
module.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=invalid-name
"""Module container of PyTorch custom class"""
import warnings
from typing import List
import torch
class GraphModule(torch.nn.Module):
r"""Module container of Pytorch class which wraps exported
TVM op implementation library to be called on Pytorch side"""
@classmethod
def shape_repr(cls, input_shapes):
return torch.ops.tvm_dsoop.tvm_shape_repr(input_shapes)
def __init__(self, num_inputs, num_outputs, device=None):
warnings.warn(
"This module will be removed at TVM version 0.11",
DeprecationWarning,
stacklevel=2,
)
super().__init__()
self.dummy_param = torch.nn.Parameter(torch.empty(0))
self.engine = None
if device is not None:
self.to(device)
self.engine = torch.classes.tvm_dsoop.TvmGraphModule(num_inputs, num_outputs, self.device)
def init(self, input_shapes, lib_path, graph_path, params_path):
r"""Load tvm module"""
self.engine.load_tvm_module(input_shapes, lib_path, graph_path, params_path)
def forward(self, inputs: List[torch.Tensor]):
r"""Call tvm module to forward"""
return self.engine.forward(inputs)
@property
def device(self):
r"""Get the device string"""
return str(self.dummy_param.device)
def _apply(self, fn):
r"""Override to device function, manually move tvm module to desired device"""
super()._apply(fn)
if self.engine is not None:
self.engine.to(self.device)
return self
class VMModule(torch.nn.Module):
r"""Module container of Pytorch class which wraps exported
TVM op implementation library to be called on Pytorch side"""
@classmethod
def shape_repr(cls, input_shapes):
return torch.ops.tvm_dsoop.tvm_shape_repr(input_shapes)
def __init__(self, num_inputs, num_outputs, device=None):
warnings.warn(
"This module will be removed at TVM version 0.11",
DeprecationWarning,
stacklevel=2,
)
super().__init__()
self.dummy_param = torch.nn.Parameter(torch.empty(0))
self.engine = None
if device is not None:
self.to(device)
self.engine = torch.classes.tvm_dsoop.TvmVMModule(num_inputs, num_outputs, self.device)
def init(self, input_shapes, lib_path, code_path):
r"""Load tvm module"""
self.engine.load_tvm_module(input_shapes, lib_path, code_path)
def forward(self, inputs: List[torch.Tensor]):
r"""Call tvm module to forward"""
return self.engine.forward(inputs)
@property
def device(self):
r"""Get the device string"""
return str(self.dummy_param.device)
def _apply(self, fn):
r"""Override to device function, manually move tvm module to desired device"""
super()._apply(fn)
if self.engine is not None:
self.engine.to(self.device)
return self
class TraceTvmModule(torch.nn.Module):
r"""Wrapper for trace GraphModule
GraphModule and VMModule only supports List[Tensor] inputs and cannot be traced.
This is a wrapper class for trace GraphModule or VMModule in order to support
arbitrary number of inputs
Example:
import tvm.contrib.torch
tvm_module = tvm.contrib.torch.GraphModule(1, 1, 'cuda:0')
tvm_module.init(input_shapes, lib_path, graph_path, params_path)
trace_wrapper = tvm.contrib.torch.TraceGraphModule(torch.jit.script(tvm_module))
traced = torch.jit.trace(trace_wrapper, example_inputs)
"""
def __init__(self, tvm_module):
warnings.warn(
"This module will be removed at TVM version 0.11",
DeprecationWarning,
stacklevel=2,
)
super().__init__()
self.tvm_module = tvm_module
def forward(self, *inputs):
outputs = self.tvm_module(inputs)
return outputs[0] if len(outputs) == 1 else tuple(outputs)
|
b4e60ef65a119dfe651f7f41a0b6ed2212fd5ba2
|
11e227cc06dfce171fe521591909e347b67220ff
|
/build/create_simulated_single_header_file.py
|
36fba3f2b58ec9a67dcd775bc2e91a3cc2806170
|
[
"Apache-2.0"
] |
permissive
|
approvals/ApprovalTests.cpp
|
45638b954cd84d2c154c250111c60b46d8efc5d0
|
d49cbcbd8a83ad8be12ad647e84162d6b2fe69b0
|
refs/heads/master
| 2023-08-17T17:13:51.713763
| 2023-08-05T17:38:09
| 2023-08-05T17:38:09
| 9,286,563
| 298
| 61
|
Apache-2.0
| 2023-09-04T17:23:47
| 2013-04-08T01:53:54
|
C++
|
UTF-8
|
Python
| false
| false
| 274
|
py
|
create_simulated_single_header_file.py
|
#! /usr/bin/env python3
import os
from scripts.project_details import ProjectDetails
from scripts.single_header_file import SingleHeaderFile
if __name__ == '__main__':
os.chdir("../ApprovalTests")
SingleHeaderFile.create('.', ProjectDetails(), include_cpps=False)
|
556119ae18b97ac8b59ad7c16a929cabc59001f9
|
f80ef3a3cf859b13e8af8433af549b6b1043bf6e
|
/pyobjc-framework-Photos/PyObjCTest/test_phassetresourcemanager.py
|
66a689fc1e81f2da15dad9961d942c45c34e0ccb
|
[
"MIT"
] |
permissive
|
ronaldoussoren/pyobjc
|
29dc9ca0af838a56105a9ddd62fb38ec415f0b86
|
77b98382e52818690449111cd2e23cd469b53cf5
|
refs/heads/master
| 2023-09-01T05:15:21.814504
| 2023-06-13T20:00:17
| 2023-06-13T20:00:17
| 243,933,900
| 439
| 49
| null | 2023-06-25T02:49:07
| 2020-02-29T08:43:12
|
Python
|
UTF-8
|
Python
| false
| false
| 1,024
|
py
|
test_phassetresourcemanager.py
|
from PyObjCTools.TestSupport import TestCase, min_os_level
import Photos
PHAssetResourceProgressHandler = b"vd"
class TestPHAssetResourceManager(TestCase):
@min_os_level("10.15")
def testMethods(self):
self.assertResultIsBOOL(
Photos.PHContentEditingInputRequestOptions.isNetworkAccessAllowed
)
self.assertArgIsBOOL(
Photos.PHContentEditingInputRequestOptions.setNetworkAccessAllowed_, 0
)
self.assertArgIsBlock(
Photos.PHAssetResourceManager.requestDataForAssetResource_options_dataReceivedHandler_completionHandler_,
2,
b"v@",
)
self.assertArgIsBlock(
Photos.PHAssetResourceManager.requestDataForAssetResource_options_dataReceivedHandler_completionHandler_,
3,
b"v@",
)
self.assertArgIsBlock(
Photos.PHAssetResourceManager.writeDataForAssetResource_toFile_options_completionHandler_,
3,
b"v@",
)
|
64a7c6f0684c3dc9d0c32c01dd71777e9e5c024d
|
e9ef3cd143478660d098668a10e67544a42b5878
|
/Lib/corpuscrawler/crawl_my_t_d0_zawgyi.py
|
a686b0d4b9f89718fd9e73e8d7c4bb05cf103a71
|
[
"Apache-2.0"
] |
permissive
|
google/corpuscrawler
|
a5c790c19b26e6397b768ce26cf12bbcb641eb90
|
10adaecf4ed5a7d0557c8e692c186023746eb001
|
refs/heads/master
| 2023-08-26T04:15:59.036883
| 2022-04-20T08:18:11
| 2022-04-20T08:18:11
| 102,909,145
| 119
| 40
|
NOASSERTION
| 2022-04-20T08:18:12
| 2017-09-08T22:21:03
|
Python
|
UTF-8
|
Python
| false
| false
| 1,986
|
py
|
crawl_my_t_d0_zawgyi.py
|
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, print_function, unicode_literals
import os.path
import re
from corpuscrawler.util import clean_paragraphs, extract, find_wordpress_urls
def crawl(crawler):
out = crawler.get_output(language='my-t-d0-zawgyi')
_crawl_than_lwin_times(crawler, out)
def _crawl_than_lwin_times(crawler, out):
urls = find_wordpress_urls(crawler, 'http://thanlwintimes.com/')
for url in sorted(urls):
if not url.endswith('/'):
continue
doc = crawler.fetch(url)
if doc.status != 200:
continue
html = doc.content.decode('utf-8')
pubdate = re.search(
r'<time class="entry-date updated td-module-date" '
r'datetime="([^"]+)"', html)
pubdate = pubdate.group(1) if pubdate else ''
title = (extract('<title>', '</title>', html) or '').split('|')[0]
body = extract('<div class="td-post-content">',
"<div class='sfsi_Sicons'", html) or ''
body = body.split('Please follow and like us')[0]
paragraphs = clean_paragraphs('%s<br/>%s' % (title, body))
if len(paragraphs) > 0:
out.write('# Location: %s\n' % url)
out.write('# Genre: News\n')
if pubdate:
out.write('# Publication-Date: %s\n' % pubdate)
out.write('\n'.join(paragraphs) + '\n')
|
a689404d7d5a77c0186e7fab227bd4602eea3f39
|
d1c2d00078520cd556f60b7213c27856f8b3460d
|
/sdks/python/apache_beam/io/snowflake.py
|
d789a72001df20b1e9f44b1ce764f5f42b620983
|
[
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-protobuf",
"Apache-2.0",
"Python-2.0"
] |
permissive
|
apache/beam
|
ed11b9e043465c720659eac20ac71b5b171bfa88
|
6d5048e05087ea54abc889ce402ae2a0abb9252b
|
refs/heads/master
| 2023-09-04T07:41:07.002653
| 2023-09-01T23:01:05
| 2023-09-01T23:01:05
| 50,904,245
| 7,061
| 4,522
|
Apache-2.0
| 2023-09-14T21:43:38
| 2016-02-02T08:00:06
|
Java
|
UTF-8
|
Python
| false
| false
| 18,521
|
py
|
snowflake.py
|
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Snowflake transforms tested against Flink portable runner.
**Setup**
Transforms provided in this module are cross-language transforms
implemented in the Beam Java SDK. During the pipeline construction, Python SDK
will connect to a Java expansion service to expand these transforms.
To facilitate this, a small amount of setup is needed before using these
transforms in a Beam Python pipeline.
There are several ways to setup cross-language Snowflake transforms.
* Option 1: use the default expansion service
* Option 2: specify a custom expansion service
See below for details regarding each of these options.
*Option 1: Use the default expansion service*
This is the recommended and easiest setup option for using Python Snowflake
transforms.This option requires following pre-requisites
before running the Beam pipeline.
* Install Java runtime in the computer from where the pipeline is constructed
and make sure that 'java' command is available.
In this option, Python SDK will either download (for released Beam version) or
build (when running from a Beam Git clone) a expansion service jar and use
that to expand transforms. Currently Snowflake transforms use the
'beam-sdks-java-io-snowflake-expansion-service' jar for this purpose.
*Option 2: specify a custom expansion service*
In this option, you startup your own expansion service and provide that as
a parameter when using the transforms provided in this module.
This option requires following pre-requisites before running the Beam
pipeline.
* Startup your own expansion service.
* Update your pipeline to provide the expansion service address when
initiating Snowflake transforms provided in this module.
Flink Users can use the built-in Expansion Service of the Flink Runner's
Job Server. If you start Flink's Job Server, the expansion service will be
started on port 8097. For a different address, please set the
expansion_service parameter.
**More information**
For more information regarding cross-language transforms see:
- https://beam.apache.org/roadmap/portability/
For more information specific to Flink runner see:
- https://beam.apache.org/documentation/runners/flink/
"""
# pytype: skip-file
from typing import Iterable
from typing import NamedTuple
from typing import Optional
import apache_beam as beam
from apache_beam.transforms.external import BeamJarExpansionService
from apache_beam.transforms.external import ExternalTransform
from apache_beam.transforms.external import NamedTupleBasedPayloadBuilder
__all__ = [
'ReadFromSnowflake',
'WriteToSnowflake',
'WriteDisposition',
'CreateDisposition',
]
def default_io_expansion_service():
return BeamJarExpansionService(
'sdks:java:io:snowflake:expansion-service:shadowJar')
ReadFromSnowflakeSchema = NamedTuple(
'ReadFromSnowflakeSchema',
[
('server_name', str),
('schema', str),
('database', str),
('staging_bucket_name', str),
('storage_integration_name', str),
('username', Optional[str]),
('password', Optional[str]),
('private_key_path', Optional[str]),
('raw_private_key', Optional[str]),
('private_key_passphrase', Optional[str]),
('o_auth_token', Optional[str]),
('table', Optional[str]),
('query', Optional[str]),
('role', Optional[str]),
('warehouse', Optional[str]),
])
class ReadFromSnowflake(beam.PTransform):
"""
An external PTransform which reads from Snowflake.
"""
URN = 'beam:transform:org.apache.beam:snowflake_read:v1'
def __init__(
self,
server_name,
schema,
database,
staging_bucket_name,
storage_integration_name,
csv_mapper,
username=None,
password=None,
private_key_path=None,
raw_private_key=None,
private_key_passphrase=None,
o_auth_token=None,
table=None,
query=None,
role=None,
warehouse=None,
expansion_service=None):
"""
Initializes a read operation from Snowflake.
Required parameters:
:param server_name: full Snowflake server name with the following format
https://account.region.gcp.snowflakecomputing.com.
:param schema: name of the Snowflake schema in the database to use.
:param database: name of the Snowflake database to use.
:param staging_bucket_name: name of the Google Cloud Storage bucket.
Bucket will be used as a temporary location for storing CSV files.
Those temporary directories will be named
'sf_copy_csv_DATE_TIME_RANDOMSUFFIX'
and they will be removed automatically once Read operation finishes.
:param storage_integration_name: is the name of storage integration
object created according to Snowflake documentation.
:param csv_mapper: specifies a function which must translate
user-defined object to array of strings.
SnowflakeIO uses a COPY INTO <location> statement to move data from
a Snowflake table to Google Cloud Storage as CSV files.These files
are then downloaded via FileIO and processed line by line.
Each line is split into an array of Strings using the OpenCSV
The csv_mapper function job is to give the user the possibility to
convert the array of Strings to a user-defined type,
ie. GenericRecord for Avro or Parquet files, or custom objects.
Example:
def csv_mapper(strings_array)
return User(strings_array[0], int(strings_array[1])))
:param table: specifies a Snowflake table name.
:param query: specifies a Snowflake custom SQL query.
:param role: specifies a Snowflake role.
:param warehouse: specifies a Snowflake warehouse name.
:param expansion_service: specifies URL of expansion service.
Authentication parameters:
:param username: specifies username for
username/password authentication method.
:param password: specifies password for
username/password authentication method.
:param private_key_path: specifies a private key file for
key/ pair authentication method.
:param raw_private_key: specifies a private key for
key/ pair authentication method.
:param private_key_passphrase: specifies password for
key/ pair authentication method.
:param o_auth_token: specifies access token for
OAuth authentication method.
"""
verify_credentials(
username=username,
password=password,
private_key_path=private_key_path,
raw_private_key=raw_private_key,
o_auth_token=o_auth_token,
)
self.params = ReadFromSnowflakeSchema(
server_name=server_name,
schema=schema,
database=database,
staging_bucket_name=staging_bucket_name,
storage_integration_name=storage_integration_name,
username=username,
password=password,
private_key_path=private_key_path,
raw_private_key=raw_private_key,
private_key_passphrase=private_key_passphrase,
o_auth_token=o_auth_token,
table=table,
query=query,
role=role,
warehouse=warehouse,
)
self.csv_mapper = csv_mapper
self.expansion_service = expansion_service or default_io_expansion_service()
def expand(self, pbegin):
return (
pbegin
| ExternalTransform(
self.URN,
NamedTupleBasedPayloadBuilder(self.params),
self.expansion_service,
)
| 'CSV to array mapper' >> beam.Map(lambda csv: csv.split(b','))
| 'CSV mapper' >> beam.Map(self.csv_mapper))
WriteToSnowflakeSchema = NamedTuple(
'WriteToSnowflakeSchema',
[
('server_name', str),
('schema', str),
('database', str),
('staging_bucket_name', str),
('storage_integration_name', str),
('create_disposition', str),
('write_disposition', str),
('table_schema', str),
('username', Optional[str]),
('password', Optional[str]),
('private_key_path', Optional[str]),
('raw_private_key', Optional[str]),
('private_key_passphrase', Optional[str]),
('o_auth_token', Optional[str]),
('table', Optional[str]),
('query', Optional[str]),
('role', Optional[str]),
('warehouse', Optional[str]),
],
)
class WriteToSnowflake(beam.PTransform):
"""
An external PTransform which writes to Snowflake.
"""
URN = 'beam:transform:org.apache.beam:snowflake_write:v1'
def __init__(
self,
server_name,
schema,
database,
staging_bucket_name,
storage_integration_name,
create_disposition,
write_disposition,
table_schema,
user_data_mapper,
username=None,
password=None,
private_key_path=None,
raw_private_key=None,
private_key_passphrase=None,
o_auth_token=None,
table=None,
query=None,
role=None,
warehouse=None,
expansion_service=None,
):
# pylint: disable=line-too-long
"""
Initializes a write operation to Snowflake.
Required parameters:
:param server_name: full Snowflake server name with the following format
https://account.region.gcp.snowflakecomputing.com.
:param schema: name of the Snowflake schema in the database to use.
:param database: name of the Snowflake database to use.
:param staging_bucket_name: name of the Google Cloud Storage bucket.
Bucket will be used as a temporary location for storing CSV files.
:param storage_integration_name: is the name of a Snowflake storage
integration object created according to Snowflake documentation for the
GCS bucket.
:param user_data_mapper: specifies a function which maps data from
a PCollection to an array of String values before the write operation
saves the data to temporary .csv files.
Example:
def user_data_mapper(user):
return [user.name, str(user.age)]
:param table: specifies a Snowflake table name
:param query: specifies a custom SQL query
:param role: specifies a Snowflake role.
:param warehouse: specifies a Snowflake warehouse name.
:param expansion_service: specifies URL of expansion service.
Authentication parameters:
:param username: specifies username for
username/password authentication method.
:param password: specifies password for
username/password authentication method.
:param private_key_path: specifies a private key file for
key/ pair authentication method.
:param raw_private_key: specifies a private key for
key/ pair authentication method.
:param private_key_passphrase: specifies password for
key/ pair authentication method.
:param o_auth_token: specifies access token for
OAuth authentication method.
Additional parameters:
:param create_disposition: Defines the behaviour of the write operation if
the target table does not exist. The following values are supported:
CREATE_IF_NEEDED - default behaviour. The write operation checks whether
the specified target table exists; if it does not, the write operation
attempts to create the table Specify the schema for the target table
using the table_schema parameter.
CREATE_NEVER - The write operation fails if the target table does not
exist.
:param write_disposition: Defines the write behaviour based on the table
where data will be written to. The following values are supported:
APPEND - Default behaviour. Written data is added to the existing rows
in the table,
EMPTY - The target table must be empty; otherwise, the write operation
fails,
TRUNCATE - The write operation deletes all rows from the target table
before writing to it.
:param table_schema: When the create_disposition parameter is set to
CREATE_IF_NEEDED, the table_schema parameter enables specifying the
schema for the created target table. A table schema is as JSON with the
following structure:
.. code-block:: none
{"schema":[
{
"dataType":{"type":"<COLUMN DATA TYPE>"},
"name":"<COLUMN NAME>",
"nullable": <NULLABLE>
},
]}
All supported data types:
.. code-block:: json
{"schema":[
{"dataType":{"type":"date"},"name":"","nullable":false},
{"dataType":{"type":"datetime"},"name":"","nullable":false},
{"dataType":{"type":"time"},"name":"","nullable":false},
{"dataType":{"type":"timestamp"},"name":"","nullable":false},
{"dataType":{"type":"timestamp_ltz"},"name":"","nullable":false},
{"dataType":{"type":"timestamp_ntz"},"name":"","nullable":false},
{"dataType":{"type":"timestamp_tz"},"name":"","nullable":false},
{"dataType":{"type":"boolean"},"name":"","nullable":false},
{"dataType":{"type":"decimal","precision":38,"scale":1},"name":"","nullable":true},
{"dataType":{"type":"double"},"name":"","nullable":false},
{"dataType":{"type":"float"},"name":"","nullable":false},
{"dataType":{"type":"integer","precision":38,"scale":0},"name":"","nullable":false},
{"dataType":{"type":"number","precision":38,"scale":1},"name":"","nullable":false},
{"dataType":{"type":"numeric","precision":38,"scale":2},"name":"","nullable":false},
{"dataType":{"type":"real"},"name":"","nullable":false},
{"dataType":{"type":"array"},"name":"","nullable":false},
{"dataType":{"type":"object"},"name":"","nullable":false},
{"dataType":{"type":"variant"},"name":"","nullable":true},
{"dataType":{"type":"binary","size":null},"name":"","nullable":false},
{"dataType":{"type":"char","length":1},"name":"","nullable":false},
{"dataType":{"type":"string","length":null},"name":"","nullable":false},
{"dataType":{"type":"text","length":null},"name":"","nullable":false},
{"dataType":{"type":"varbinary","size":null},"name":"","nullable":false},
{"dataType":{"type":"varchar","length":100},"name":"","nullable":false},
{"dataType":{"type":"geography"},"name":"","nullable":true}]
}
"""
verify_credentials(
username=username,
password=password,
private_key_path=private_key_path,
raw_private_key=raw_private_key,
o_auth_token=o_auth_token,
)
WriteDisposition.VerifyParam(write_disposition)
CreateDisposition.VerifyParam(create_disposition)
self.params = WriteToSnowflakeSchema(
server_name=server_name,
schema=schema,
database=database,
staging_bucket_name=staging_bucket_name,
storage_integration_name=storage_integration_name,
create_disposition=create_disposition,
write_disposition=write_disposition,
table_schema=table_schema,
username=username,
password=password,
private_key_path=private_key_path,
raw_private_key=raw_private_key,
private_key_passphrase=private_key_passphrase,
o_auth_token=o_auth_token,
table=table,
query=query,
role=role,
warehouse=warehouse,
)
self.user_data_mapper = user_data_mapper
self.expansion_service = expansion_service or default_io_expansion_service()
def expand(self, pbegin):
return (
pbegin
| 'User data mapper' >> beam.Map(
self.user_data_mapper).with_output_types(Iterable[bytes])
| ExternalTransform(
self.URN,
NamedTupleBasedPayloadBuilder(self.params),
self.expansion_service))
class CreateDisposition:
"""
Enum class for possible values of create dispositions:
CREATE_IF_NEEDED: default behaviour. The write operation checks whether
the specified target table exists; if it does not, the write operation
attempts to create the table Specify the schema for the target table
using the table_schema parameter.
CREATE_NEVER: The write operation fails if the target table does not exist.
"""
CREATE_IF_NEEDED = 'CREATE_IF_NEEDED'
CREATE_NEVER = 'CREATE_NEVER'
@staticmethod
def VerifyParam(field):
if field and not hasattr(CreateDisposition, field):
raise RuntimeError(
'Create disposition has to be one of the following values:'
'CREATE_IF_NEEDED, CREATE_NEVER. Got: {}'.format(field))
class WriteDisposition:
"""
Enum class for possible values of write dispositions:
APPEND: Default behaviour. Written data is added to the existing rows
in the table,
EMPTY: The target table must be empty; otherwise, the write operation fails,
TRUNCATE: The write operation deletes all rows from the target table
before writing to it.
"""
APPEND = 'APPEND'
EMPTY = 'EMPTY'
TRUNCATE = 'TRUNCATE'
@staticmethod
def VerifyParam(field):
if field and not hasattr(WriteDisposition, field):
raise RuntimeError(
'Write disposition has to be one of the following values:'
'APPEND, EMPTY, TRUNCATE. Got: {}'.format(field))
def verify_credentials(
username, password, private_key_path, raw_private_key, o_auth_token):
if not (o_auth_token or (username and password) or
(username and (private_key_path or raw_private_key))):
raise RuntimeError('Snowflake credentials are not set correctly.')
|
65e920845a4c637d8d12e3f96b48779e2396fe7d
|
a641c7b07e91024f166ee25ee2d07874a704f40c
|
/data/WikiCS.py
|
7c1dadf3060d8c1f201f33d49be72cfe6742f791
|
[
"MIT"
] |
permissive
|
graphdeeplearning/benchmarking-gnns
|
c901c87bf9441ff6a8f7427b2d0e3f5bcfd9489b
|
b6c407712fa576e9699555e1e035d1e327ccae6c
|
refs/heads/master
| 2023-07-31T21:35:04.971051
| 2022-05-10T13:22:20
| 2022-05-10T13:22:20
| 244,534,808
| 2,340
| 468
|
MIT
| 2023-06-22T04:03:54
| 2020-03-03T03:42:50
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 2,788
|
py
|
WikiCS.py
|
import torch
import pickle
import torch.utils.data
import time
import os
import numpy as np
import dgl
import json
import networkx as nx
from scipy import sparse as sp
import itertools
class WikiCSDataset(torch.utils.data.Dataset):
"""
Wiki-CS Dataset
Adapted from
https://github.com/pmernyei/wiki-cs-dataset/
"""
def __init__(self, DATASET_NAME='WikiCS', path="data/WikiCS/"):
self.name = DATASET_NAME
self.data = json.load(open(os.path.join(path, 'data.json')))
self.g, self.labels = None, None
self.train_masks, self.stopping_masks, self.val_masks, self.test_mask = None, None, None, None
self.num_classes, self.n_feats = None, None
self._load()
def _load(self):
t0 = time.time()
print("[I] Loading WikiCS ...")
features = torch.FloatTensor(np.array(self.data['features']))
self.labels = torch.LongTensor(np.array(self.data['labels']))
self.train_masks = [torch.BoolTensor(tr) for tr in self.data['train_masks']]
self.val_masks = [torch.BoolTensor(val) for val in self.data['val_masks']]
self.stopping_masks = [torch.BoolTensor(st) for st in self.data['stopping_masks']]
self.test_mask = torch.BoolTensor(self.data['test_mask'])
self.n_feats = features.shape[1]
self.num_classes = len(set(self.data['labels']))
self.g = dgl.DGLGraph()
self.g.add_nodes(len(self.data['features']))
edge_list = list(itertools.chain(*[[(i, nb) for nb in nbs] for i,nbs in enumerate(self.data['links'])]))
# add edges two lists of nodes: src and dst
src, dst = tuple(zip(*edge_list))
self.g.add_edges(src, dst)
# edges are directional in DGL; make them bi-directional
self.g.add_edges(dst, src)
self.g.ndata['feat'] = features # available features
self.g.edata['feat'] = torch.zeros(self.g.number_of_edges(), 1)
print("[I] Finished loading after {:.4f}s".format(time.time()-t0))
def _add_positional_encodings(self, pos_enc_dim):
# Graph positional encoding v/ Laplacian eigenvectors
g = self.g
# Laplacian
A = g.adjacency_matrix_scipy(return_edge_ids=False).astype(float)
N = sp.diags(dgl.backend.asnumpy(g.in_degrees()).clip(1) ** -0.5, dtype=float)
L = sp.eye(g.number_of_nodes()) - N * A * N
# Eigenvectors with numpy
EigVal, EigVec = np.linalg.eig(L.toarray())
idx = EigVal.argsort() # increasing order
EigVal, EigVec = EigVal[idx], np.real(EigVec[:,idx])
g.ndata['pos_enc'] = torch.from_numpy(EigVec[:,1:pos_enc_dim+1]).float()
self.g = g
|
23dd79b201882ce1112f5c9ab678ef779f693178
|
686177a1034cee76ad040c62e3d3e49d44a9ee7a
|
/src/collectors/cpuacct_cgroup/test/testcpuacct_cgroup.py
|
4e2430262aa4f7fe28422822b5fd80f5a2f371c6
|
[
"MIT"
] |
permissive
|
python-diamond/Diamond
|
8fce83a3d883dfa05b664fdd5cb6064f34c4ac41
|
461caf29e84db8cbf46f9fc4c895f56353e10c61
|
refs/heads/master
| 2023-07-20T01:44:18.504408
| 2023-01-29T19:46:36
| 2023-01-29T19:46:36
| 13,512,018
| 1,874
| 824
|
MIT
| 2023-07-10T11:06:38
| 2013-10-11T23:32:13
|
Python
|
UTF-8
|
Python
| false
| false
| 1,908
|
py
|
testcpuacct_cgroup.py
|
#!/usr/bin/python
# coding=utf-8
##########################################################################
import os
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import patch
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from diamond.collector import Collector
from cpuacct_cgroup import CpuAcctCgroupCollector
class TestCpuAcctCgroupCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('CpuAcctCgroupCollector', {
'interval': 10
})
self.collector = CpuAcctCgroupCollector(config, None)
def test_import(self):
self.assertTrue(CpuAcctCgroupCollector)
@patch('__builtin__.open')
@patch.object(Collector, 'publish')
def test_should_open_all_cpuacct_stat(self, publish_mock, open_mock):
return
self.collector.config['path'] = self.getFixtureDirPath()
open_mock.side_effect = lambda x: StringIO('')
self.collector.collect()
# All the fixtures we should be opening
paths = [
'lxc/testcontainer/cpuacct.stat',
'lxc/cpuacct.stat',
'cpuacct.stat',
]
for path in paths:
open_mock.assert_any_call(os.path.join(
self.getFixtureDirPath(), path))
@patch.object(Collector, 'publish')
def test_should_work_with_real_data(self, publish_mock):
self.collector.config['path'] = self.getFixtureDirPath()
self.collector.collect()
self.assertPublishedMany(publish_mock, {
'lxc.testcontainer.user': 1318,
'lxc.testcontainer.system': 332,
'lxc.user': 36891,
'lxc.system': 88927,
'system.user': 3781253,
'system.system': 4784004,
})
if __name__ == "__main__":
unittest.main()
|
f07d425b17d25a52baa89c9335fc286dc2ee4bee
|
66333a96a8806181228a860085ee5d01888c7b2f
|
/depth_estimation/fast-depth/fast_depth_utils.py
|
f931f368f80da34467ebb8eb7375fea1dad80ea1
|
[
"MIT"
] |
permissive
|
axinc-ai/ailia-models
|
7c5c15d813a58fcae678a8107ebc9c39ee9912f2
|
da1c277b602606586cd83943ef6b23eb705ec604
|
refs/heads/master
| 2023-08-31T07:43:39.848448
| 2023-08-29T05:06:27
| 2023-08-29T05:06:27
| 206,917,330
| 1,554
| 286
| null | 2023-09-14T19:56:14
| 2019-09-07T04:50:59
|
Python
|
UTF-8
|
Python
| false
| false
| 950
|
py
|
fast_depth_utils.py
|
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import transforms.transforms as transforms
IHEIGHT, IWIDTH = 480, 640 # raw image size
cmap = plt.cm.viridis
def colored_depthmap(depth, d_min=None, d_max=None):
if d_min is None:
d_min = np.min(depth)
if d_max is None:
d_max = np.max(depth)
depth_relative = (depth - d_min) / (d_max - d_min)
return 255 * cmap(depth_relative)[:, :, :3] # H, W, C
def save_image(img_merge, filename):
img_merge = Image.fromarray(img_merge.astype("uint8"))
img_merge.save(filename)
def transform(rgb, output_size):
transformer = transforms.Compose(
[
transforms.Resize((int(IWIDTH * (250.0 / IHEIGHT)), 250)),
transforms.CenterCrop((228, 304)),
transforms.Resize(output_size),
]
)
rgb_np = transformer(rgb)
rgb_np = np.asfarray(rgb_np, dtype="float") / 255
return rgb_np
|
45aabfed34e96c8383e185776082c777da38c06e
|
bec0383f2afd255a72afeb9049a898615e547327
|
/electrum/electrumabc/tests/test_bip44_derivation_path.py
|
043ceb42491bd9a536594dfc6f39c5835f5b86e7
|
[
"MIT"
] |
permissive
|
Bitcoin-ABC/bitcoin-abc
|
a73024a513be2c9c419f8bece06dbadde2af3fb7
|
57176a00e4d660487c41b92207da4bf27e5c0026
|
refs/heads/master
| 2023-09-04T11:26:24.295624
| 2023-09-01T14:24:40
| 2023-09-04T05:20:03
| 89,913,655
| 1,359
| 768
|
MIT
| 2023-07-19T16:41:26
| 2017-05-01T09:58:15
|
C++
|
UTF-8
|
Python
| false
| false
| 1,458
|
py
|
test_bip44_derivation_path.py
|
import unittest
from .. import keystore, networks
class TestBip44Derivations(unittest.TestCase):
def setUp(self):
self.initial_net = networks.net
def tearDown(self):
# make sure we restore the network settings, in case it affects other tests
if self.initial_net == networks.MainNet:
networks.set_mainnet()
else:
networks.set_testnet()
def test_mainnet(self):
networks.set_mainnet()
self.assertEqual(keystore.bip44_derivation_xec(1337), "m/44'/899'/1337'")
self.assertEqual(keystore.bip44_derivation_bch(1337), "m/44'/145'/1337'")
self.assertEqual(keystore.bip44_derivation_btc(1337), "m/44'/0'/1337'")
self.assertEqual(
keystore.bip44_derivation_xec_tokens(1337), "m/44'/1899'/1337'"
)
self.assertEqual(keystore.bip44_derivation_bch_tokens(1337), "m/44'/245'/1337'")
def test_testnet(self):
networks.set_testnet()
self.assertEqual(keystore.bip44_derivation_xec(1337), "m/44'/1'/1337'")
self.assertEqual(keystore.bip44_derivation_bch(1337), "m/44'/1'/1337'")
self.assertEqual(keystore.bip44_derivation_btc(1337), "m/44'/1'/1337'")
self.assertEqual(
keystore.bip44_derivation_xec_tokens(1337), "m/44'/1899'/1337'"
)
self.assertEqual(keystore.bip44_derivation_bch_tokens(1337), "m/44'/245'/1337'")
if __name__ == "__main__":
unittest.main()
|
6a763a27787b3b80f604c595bd384623a0401e09
|
8fa191cd4a67431a04eff62d35122ee83cc7b0af
|
/bookwyrm/tests/views/landing/test_login.py
|
eab08260929188ec0165f0b04ed724f3ab039f94
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
bookwyrm-social/bookwyrm
|
24678676a7a58dba96641194dfae3fffbf01574d
|
0f8da5b738047f3c34d60d93f59bdedd8f797224
|
refs/heads/main
| 2023-08-20T21:45:30.957277
| 2023-08-19T23:41:50
| 2023-08-19T23:41:50
| 236,415,735
| 1,398
| 216
|
NOASSERTION
| 2023-09-08T20:43:06
| 2020-01-27T03:51:54
|
Python
|
UTF-8
|
Python
| false
| false
| 6,207
|
py
|
test_login.py
|
""" test for app action functionality """
from unittest.mock import patch
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.middleware import SessionMiddleware
from django.template.response import TemplateResponse
from django.test import TestCase
from django.test.client import RequestFactory
from bookwyrm import forms, models, views
from bookwyrm.tests.validate_html import validate_html
# pylint: disable=too-many-public-methods
@patch("bookwyrm.suggested_users.rerank_suggestions_task.delay")
@patch("bookwyrm.activitystreams.populate_stream_task.delay")
class LoginViews(TestCase):
"""login and password management"""
# pylint: disable=invalid-name
def setUp(self):
"""we need basic test data and mocks"""
self.factory = RequestFactory()
with patch("bookwyrm.suggested_users.rerank_suggestions_task.delay"), patch(
"bookwyrm.activitystreams.populate_stream_task.delay"
), patch("bookwyrm.lists_stream.populate_lists_task.delay"):
self.local_user = models.User.objects.create_user(
"mouse@your.domain.here",
"mouse@mouse.com",
"password",
local=True,
localname="mouse",
two_factor_auth=False,
)
self.rat = models.User.objects.create_user(
"rat@your.domain.here",
"rat@rat.com",
"password",
local=True,
localname="rat",
)
self.badger = models.User.objects.create_user(
"badger@your.domain.here",
"badger@badger.com",
"password",
local=True,
localname="badger",
two_factor_auth=True,
)
self.anonymous_user = AnonymousUser
self.anonymous_user.is_authenticated = False
models.SiteSettings.objects.create(id=1, require_confirm_email=False)
def test_login_get(self, *_):
"""there are so many views, this just makes sure it LOADS"""
login = views.Login.as_view()
request = self.factory.get("")
request.user = self.anonymous_user
result = login(request)
self.assertIsInstance(result, TemplateResponse)
validate_html(result.render())
self.assertEqual(result.status_code, 200)
request.user = self.local_user
result = login(request)
self.assertEqual(result.url, "/")
self.assertEqual(result.status_code, 302)
def test_login_post_localname(self, *_):
"""there are so many views, this just makes sure it LOADS"""
view = views.Login.as_view()
form = forms.LoginForm()
form.data["localname"] = "mouse@mouse.com"
form.data["password"] = "password"
request = self.factory.post("", form.data)
request.user = self.anonymous_user
with patch("bookwyrm.views.landing.login.login"):
result = view(request)
self.assertEqual(result.url, "/")
self.assertEqual(result.status_code, 302)
def test_login_post_username(self, *_):
"""valid login where the user provides their user@domain.com username"""
view = views.Login.as_view()
form = forms.LoginForm()
form.data["localname"] = "mouse@your.domain.here"
form.data["password"] = "password"
request = self.factory.post("", form.data)
request.user = self.anonymous_user
with patch("bookwyrm.views.landing.login.login"):
result = view(request)
self.assertEqual(result.url, "/")
self.assertEqual(result.status_code, 302)
def test_login_post_email(self, *_):
"""there are so many views, this just makes sure it LOADS"""
view = views.Login.as_view()
form = forms.LoginForm()
form.data["localname"] = "mouse"
form.data["password"] = "password"
request = self.factory.post("", form.data)
request.user = self.anonymous_user
with patch("bookwyrm.views.landing.login.login"):
result = view(request)
self.assertEqual(result.url, "/")
self.assertEqual(result.status_code, 302)
def test_login_post_invalid_credentials(self, *_):
"""there are so many views, this just makes sure it LOADS"""
view = views.Login.as_view()
form = forms.LoginForm()
form.data["localname"] = "mouse"
form.data["password"] = "password1"
request = self.factory.post("", form.data)
request.user = self.anonymous_user
with patch("bookwyrm.views.landing.login.login"):
result = view(request)
validate_html(result.render())
self.assertEqual(result.status_code, 200)
self.assertEqual(
result.context_data["login_form"].non_field_errors,
"Username or password are incorrect",
)
def test_login_post_no_2fa_set(self, *_):
"""test user with 2FA null value is redirected to 2FA prompt page"""
view = views.Login.as_view()
form = forms.LoginForm()
form.data["localname"] = "rat"
form.data["password"] = "password"
request = self.factory.post("", form.data)
request.user = self.anonymous_user
with patch("bookwyrm.views.landing.login.login"):
result = view(request)
self.assertEqual(result.url, "/2fa-prompt")
self.assertEqual(result.status_code, 302)
def test_login_post_with_2fa(self, *_):
"""test user with 2FA turned on is redirected to 2FA login page"""
view = views.Login.as_view()
form = forms.LoginForm()
form.data["localname"] = "badger"
form.data["password"] = "password"
request = self.factory.post("", form.data)
request.user = self.anonymous_user
middleware = SessionMiddleware(request)
middleware.process_request(request)
request.session.save()
with patch("bookwyrm.views.landing.login.login"):
result = view(request)
self.assertEqual(result.url, "/2fa-check")
self.assertEqual(result.status_code, 302)
|
293819f556aab8273370d60899aa0477e4f411e4
|
d0f1472c167339f1e5267f404a5b73e0c180b754
|
/local-sync.py
|
64232ff7eacb66b4313674f4c6d0d2ce1748fffb
|
[
"MIT"
] |
permissive
|
DQinYuan/chinese_province_city_area_mapper
|
a756670401ac648b4b82991ee77651262790aca6
|
9bdfd6e8694b44ca3de0730bd9122c6df5916133
|
refs/heads/master
| 2023-09-01T13:48:16.396552
| 2021-12-12T09:20:04
| 2021-12-12T09:20:04
| 123,792,414
| 1,558
| 366
|
MIT
| 2022-12-08T11:46:07
| 2018-03-04T13:43:06
|
Python
|
UTF-8
|
Python
| false
| false
| 1,215
|
py
|
local-sync.py
|
import sys
import os
import csv
from progress.bar import Bar
if len(sys.argv) != 2:
print("python local-sync.py <directory>")
sys.exit(1)
adcodes_root = sys.argv[1]
# 代表整个中国 adcode
china_base_adcode = "100000000000"
with open("./cpca/resources/adcodes.csv", "w") as f:
csv_writer = csv.writer(f)
csv_writer.writerow(["adcode", "name", "longitude", "latitude"])
for root, dirs, files in os.walk(adcodes_root):
bar = Bar('Syncing', max=len(files))
for file_name in files:
full_path = os.path.join(root, file_name)
with open(full_path) as csv_file:
csv_reader = csv.reader(csv_file)
for csv_record in csv_reader:
adcode = csv_record[0]
standard_name = csv_record[2]
longitude = csv_record[12]
latitude = csv_record[13]
# 只选取省市区三级的 adcode 并且排除代表整个中国的 adcode
if adcode[6:] == "000000" and adcode != china_base_adcode:
csv_writer.writerow([adcode, standard_name, longitude, latitude])
bar.next()
bar.finish()
|
c1b9cb88eaee77b9f1261e482d17782d0a0f98ba
|
807b63a4dda1e4bcf33a9b456cb9535eb69625fc
|
/python/stencila/types/product.py
|
3768e715e92dba13520920fb041d736840d0a693
|
[
"Apache-2.0"
] |
permissive
|
stencila/stencila
|
4d63a5653adb67a45dd5eb11c7a27d569f57a49e
|
eac602910d009d7db7048b28b4049ecc952ecd32
|
refs/heads/main
| 2023-08-30T18:34:19.055238
| 2023-08-30T07:14:02
| 2023-08-30T07:14:02
| 4,503,128
| 719
| 51
|
Apache-2.0
| 2023-09-14T21:35:38
| 2012-05-31T02:43:31
|
Rust
|
UTF-8
|
Python
| false
| false
| 711
|
py
|
product.py
|
# Generated file; do not edit. See the Rust `schema-gen` crate.
from .prelude import *
from .brand import Brand
from .image_object_or_str import ImageObjectOrStr
from .thing import Thing
@dataclass(kw_only=True, frozen=True)
class Product(Thing):
"""
Any offered product or service. For example, a pair of shoes; a haircut; or an episode of a TV show streamed online.
"""
type: Literal["Product"] = field(default="Product", init=False)
brands: Optional[List[Brand]] = None
"""Brands that the product is labelled with."""
logo: Optional[ImageObjectOrStr] = None
"""The logo of the product."""
product_id: Optional[str] = None
"""Product identification code."""
|
95111879e3fb34bb7af1bd6192f0e54736109206
|
86f3973554eb61b12528835851cbdc96aba9ccc0
|
/io_scene_xray/formats/obj/exp/main.py
|
6e0bbd35a4cde33959a2bf2c5c24dc90468d6790
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
PavelBlend/blender-xray
|
02d68e424ae9088221bafc1d0d9019690323d9da
|
a3abb9eb805182eec8ed8de4058dd744aee0e291
|
refs/heads/develop
| 2023-09-03T15:10:56.022070
| 2023-08-22T17:50:23
| 2023-08-22T17:50:23
| 20,459,902
| 150
| 40
|
BSD-2-Clause
| 2023-08-10T15:01:24
| 2014-06-03T21:12:53
|
Python
|
UTF-8
|
Python
| false
| false
| 19,138
|
py
|
main.py
|
# blender modules
import bpy
import mathutils
# addon modules
from . import mesh
from . import bone
from .. import fmt
from ... import motions
from .... import rw
from .... import text
from .... import utils
from .... import log
def export_version(chunked_writer):
packed_writer = rw.write.PackedWriter()
packed_writer.putf('<H', fmt.CURRENT_OBJECT_VERSION)
chunked_writer.put(fmt.Chunks.Object.VERSION, packed_writer)
def export_flags(chunked_writer, xray, some_arm):
flags = xray.flags
if some_arm:
# 1 - Dynamic
# 3 - Progressive Dynamic
if flags & ~0x40 not in (1, 3):
# set Dynamic flag
# so that it is possible to export to ogf from ActorEditor
flags = 1 | (flags & 0x40)
log.warn(
text.warn.object_set_dynamic,
object=xray.id_data.name,
has_type=fmt.type_names[xray.flags_simple],
save_as=fmt.type_names[fmt.DY]
)
packed_writer = rw.write.PackedWriter()
packed_writer.putf('<I', flags)
chunked_writer.put(fmt.Chunks.Object.FLAGS, packed_writer)
def validate_vertex_weights(bpy_obj, arm_obj):
exportable_bones_names = [
bpy_bone.name
for bpy_bone in arm_obj.data.bones
if bpy_bone.xray.exportable
]
exportable_groups_indices = [
group.index
for group in bpy_obj.vertex_groups
if group.name in exportable_bones_names
]
has_ungrouped_verts = None
ungrouped_verts_count = 0
has_nonexp_vert_groups = None
nonexp_group_verts_count = 0
for vertex in bpy_obj.data.vertices:
if len(vertex.groups):
exportable_groups_count = 0
for vertex_group in vertex.groups:
if vertex_group.group in exportable_groups_indices:
exportable_groups_count += 1
if not exportable_groups_count:
has_nonexp_vert_groups = True
nonexp_group_verts_count += 1
else:
has_ungrouped_verts = True
ungrouped_verts_count += 1
if has_ungrouped_verts:
raise log.AppError(
text.error.object_ungroupped_verts,
log.props(
object=bpy_obj.name,
vertices_count=ungrouped_verts_count
)
)
if has_nonexp_vert_groups:
raise log.AppError(
text.error.object_nonexp_group_verts,
log.props(
object=bpy_obj.name,
vertices_count=nonexp_group_verts_count
)
)
@log.with_context('armature')
def _check_bone_names(armature_object):
bone_names = {}
bone_duplicates = {}
for bpy_bone in armature_object.data.bones:
name = bpy_bone.name
name_lower = name.lower()
if bone_names.get(name_lower, None):
if not bone_duplicates.get(name_lower, None):
bone_duplicates[name_lower] = [bone_names.get(name_lower), ]
bone_duplicates[name_lower].append(name)
else:
bone_names[name_lower] = name
if bone_duplicates:
log.update(object=armature_object.name)
raise log.AppError(
text.error.object_duplicate_bones,
log.props(bones=tuple(bone_duplicates.values()))
)
def merge_meshes(mesh_objects):
objects = []
override = bpy.context.copy()
for obj in mesh_objects:
if not len(obj.data.uv_layers):
raise log.AppError(
text.error.no_uv,
log.props(object=obj.name)
)
if len(obj.data.uv_layers) > 1:
log.warn(
text.warn.obj_many_uv,
exported_uv=obj.data.uv_layers.active.name,
mesh_object=obj.name
)
copy_obj = obj.copy()
copy_mesh = obj.data.copy()
copy_obj.data = copy_mesh
# rename uv layers
active_uv_name = copy_mesh.uv_layers.active.name
index = 0
for uv_layer in copy_mesh.uv_layers:
if uv_layer.name == active_uv_name:
continue
uv_layer.name = str(index)
index += 1
copy_mesh.uv_layers.active.name = 'Texture'
utils.version.link_object(copy_obj)
# apply modifiers
override['active_object'] = copy_obj
override['object'] = copy_obj
for mod in copy_obj.modifiers:
if mod.type == 'ARMATURE':
continue
if not mod.show_viewport:
continue
override['modifier'] = mod
utils.obj.apply_obj_modifier(mod, context=override)
objects.append(copy_obj)
# apply shape keys
if copy_mesh.shape_keys:
copy_obj.shape_key_add(name='last_shape_key', from_mix=True)
for shape_key in copy_mesh.shape_keys.key_blocks:
copy_obj.shape_key_remove(shape_key)
active_object = objects[0]
override['active_object'] = active_object
override['selected_objects'] = objects
if utils.version.IS_28:
override['object'] = active_object
override['selected_editable_objects'] = objects
else:
scene = bpy.context.scene
override['selected_editable_bases'] = [
scene.object_bases[ob.name]
for ob in objects
]
bpy.ops.object.join(override)
# remove uvs
uv_layers = [uv_layer.name for uv_layer in active_object.data.uv_layers]
for uv_name in uv_layers:
if uv_name == 'Texture':
continue
uv_layer = active_object.data.uv_layers[uv_name]
active_object.data.uv_layers.remove(uv_layer)
return active_object
def export_meshes(chunked_writer, bpy_root, context, obj_xray):
armatures = set()
materials = set()
meshes = set()
armature_meshes = set()
meshes_without_arms = set()
mesh_writers = []
uv_maps_names = {}
merged_obj = None
loc_space, rot_space, scl_space = utils.ie.get_object_world_matrix(bpy_root)
def write_mesh(bpy_obj):
# write mesh chunk
mesh_writer = rw.write.ChunkedWriter()
used_material_names = mesh.export_mesh(
bpy_obj,
bpy_root,
mesh_writer,
context,
loc_space,
rot_space,
scl_space
)
mesh_writers.append(mesh_writer)
meshes.add(bpy_obj)
# collect materials and uv-map names
uv_layers = bpy_obj.data.uv_layers
for material in bpy_obj.data.materials:
if material:
if material.name in used_material_names:
materials.add(material)
uv_maps_names[material.name] = uv_layers.active.name
if len(uv_layers) > 1:
log.warn(
text.warn.obj_many_uv,
exported_uv=uv_layers.active.name,
mesh_object=bpy_obj.name
)
def scan_root_obj(bpy_obj):
# scan bone shape helper object
if utils.obj.is_helper_object(bpy_obj):
return
# scan mesh object
if bpy_obj.type == 'MESH':
arm_obj = utils.obj.get_armature_object(bpy_obj)
if arm_obj:
armature_meshes.add(bpy_obj)
armatures.add(arm_obj)
elif armatures:
armature_meshes.add(bpy_obj)
meshes_without_arms.add(bpy_obj)
else:
write_mesh(bpy_obj)
# scan children
for child in bpy_obj.children:
scan_root_obj(child)
def search_armatures(bpy_obj):
if bpy_obj.type == 'ARMATURE':
armatures.add(bpy_obj)
for child in bpy_obj.children:
search_armatures(child)
search_armatures(bpy_root)
scan_root_obj(bpy_root)
# find armature object
if len(armatures) == 1:
bpy_arm_obj = list(armatures)[0]
if meshes_without_arms:
for obj in meshes_without_arms:
log.warn(
text.warn.obj_used_arm,
used_armature=bpy_arm_obj.name,
mesh_object=obj.name
)
elif len(armatures) > 1:
raise log.AppError(
text.error.object_many_arms,
log.props(
root_object=bpy_root.name,
armature_objects=[obj.name for obj in armatures]
)
)
else:
bpy_arm_obj = None
# write armature meshes
if armature_meshes:
# one mesh
if len(armature_meshes) == 1:
mesh_object = list(armature_meshes)[0]
write_mesh(mesh_object)
# many meshes
else:
merged_obj = merge_meshes(armature_meshes)
write_mesh(merged_obj)
mesh_names = [mesh.name for mesh in armature_meshes]
log.warn(
text.warn.object_merged,
objects=mesh_names
)
if not mesh_writers:
raise log.AppError(
text.error.object_no_meshes,
log.props(object=bpy_root.name)
)
if len(mesh_writers) > 1 and bpy_arm_obj:
raise log.AppError(
text.error.object_skel_many_meshes,
log.props(object=bpy_root.name)
)
if bpy_arm_obj:
for mesh_obj in meshes:
validate_vertex_weights(mesh_obj, bpy_arm_obj)
bone_writers = []
root_bones = []
if bpy_arm_obj:
_check_bone_names(bpy_arm_obj)
bonemap = {}
arm_mat, scale = utils.ie.get_obj_scale_matrix(bpy_root, bpy_arm_obj)
utils.ie.check_armature_scale(scale, bpy_root, bpy_arm_obj)
edit_mode_matrices = {}
with utils.version.using_active_object(bpy_arm_obj), utils.version.using_mode('EDIT'):
for edit_bone in bpy_arm_obj.data.edit_bones:
bone_mat = utils.version.multiply(arm_mat, edit_bone.matrix)
bone_mat[0][3] *= scale.x
bone_mat[1][3] *= scale.y
bone_mat[2][3] *= scale.z
edit_mode_matrices[edit_bone.name] = bone_mat
for bpy_bone in bpy_arm_obj.data.bones:
if not utils.bone.is_exportable_bone(bpy_bone):
continue
real_parent = utils.bone.find_bone_exportable_parent(bpy_bone)
if not real_parent:
root_bones.append(bpy_bone.name)
bone.export_bone(
bpy_arm_obj,
bpy_bone,
bone_writers,
bonemap,
edit_mode_matrices,
context.multiply,
scale
)
invalid_bones = []
has_bone_groups = False
if len(bpy_arm_obj.pose.bone_groups):
for bone_ in bpy_arm_obj.pose.bones:
xray = bpy_arm_obj.data.bones[bone_.name].xray
if xray.exportable:
if bone_.bone_group is None:
invalid_bones.append(bone_.name)
else:
has_bone_groups = True
if invalid_bones and has_bone_groups:
raise log.AppError(
text.error.object_bad_boneparts,
log.props(
object=bpy_arm_obj.name,
bones=invalid_bones
)
)
if len(root_bones) > 1:
raise log.AppError(
text.error.object_many_parents,
log.props(
object=bpy_arm_obj.name,
root_bones=root_bones
)
)
export_flags(chunked_writer, obj_xray, bpy_arm_obj)
meshes_writer = rw.write.ChunkedWriter()
mesh_index = 0
for mesh_writer in mesh_writers:
meshes_writer.put(mesh_index, mesh_writer)
mesh_index += 1
chunked_writer.put(fmt.Chunks.Object.MESHES, meshes_writer)
if merged_obj:
merged_mesh = merged_obj.data
if not utils.version.IS_277:
bpy.data.objects.remove(merged_obj, do_unlink=True)
else:
bpy.context.scene.objects.unlink(merged_obj)
merged_obj.user_clear()
bpy.data.objects.remove(merged_obj)
bpy.data.meshes.remove(merged_mesh)
return materials, bone_writers, bpy_arm_obj, bpy_root, uv_maps_names
def export_surfaces(chunked_writer, context, materials, uv_map_names):
writer = rw.write.PackedWriter()
surface_count = len(materials)
writer.putf('<I', surface_count)
for material in materials:
tex_name = utils.material.get_image_relative_path(material, context)
if utils.version.IS_28:
uv_name = uv_map_names[material.name]
else:
slot = material.texture_slots[material.active_texture_index]
uv_name = slot.uv_layer if slot else ''
# write
writer.puts(material.name)
writer.puts(material.xray.eshader)
writer.puts(material.xray.cshader)
writer.puts(material.xray.gamemtl)
writer.puts(tex_name)
writer.puts(uv_name)
writer.putf('<I', material.xray.flags)
writer.putf('<I', fmt.VERTEX_FORMAT)
writer.putf('<I', fmt.UV_COUNT)
chunked_writer.put(fmt.Chunks.Object.SURFACES2, writer)
def export_bones(chunked_writer, bone_writers):
if bone_writers:
writer = rw.write.ChunkedWriter()
for bone_index, bone_writer in enumerate(bone_writers):
writer.put(bone_index, bone_writer)
chunked_writer.put(fmt.Chunks.Object.BONES1, writer)
def export_user_data(chunked_writer, xray):
if xray.userdata:
user_data = '\r\n'.join(xray.userdata.splitlines())
packed_writer = rw.write.PackedWriter()
packed_writer.puts(user_data)
chunked_writer.put(fmt.Chunks.Object.USERDATA, packed_writer)
def export_lod_ref(chunked_writer, xray):
if xray.lodref:
packed_writer = rw.write.PackedWriter()
packed_writer.puts(xray.lodref)
chunked_writer.put(fmt.Chunks.Object.LOD_REF, packed_writer)
def export_motions(chunked_writer, some_arm, context, root_obj):
if some_arm and context.export_motions:
motions_names = [
motion.name
for motion in root_obj.xray.motions_collection
]
motions_names = set(motions_names)
motions_names = list(motions_names)
motions_names.sort()
acts = []
for act_name in motions_names:
act = bpy.data.actions.get(act_name, None)
if act:
acts.append(act)
else:
log.warn(
text.warn.object_no_action,
action=act_name,
object=root_obj.name
)
if not acts:
return
writer = rw.write.PackedWriter()
motions.exp.export_motions(writer, acts, some_arm, root_obj)
if writer.data:
chunked_writer.put(fmt.Chunks.Object.MOTIONS, writer)
def export_partitions(chunked_writer, some_arm):
if some_arm and some_arm.pose.bone_groups:
exportable_bones = tuple(
bone_
for bone_ in some_arm.pose.bones
if utils.bone.is_exportable_bone(
some_arm.data.bones[bone_.name]
)
)
all_groups = (
(group.name, tuple(
bone_.name
for bone_ in exportable_bones
if bone_.bone_group == group
))
for group in some_arm.pose.bone_groups
)
non_empty_groups = tuple(
group
for group in all_groups
if group[1]
)
if non_empty_groups:
writer = rw.write.PackedWriter()
writer.putf('<I', len(non_empty_groups))
for name, bones in non_empty_groups:
writer.puts(name)
writer.putf('<I', len(bones))
for bone_ in bones:
writer.puts(bone_.lower())
chunked_writer.put(fmt.Chunks.Object.PARTITIONS1, writer)
def export_motion_refs(chunked_writer, xray, context):
motionrefs = xray.motionrefs_collection
if motionrefs:
if xray.motionrefs:
log.warn(
text.warn.object_legacy_motionrefs,
data=xray.motionrefs
)
if context.soc_sgroups:
refs = ','.join(ref.name for ref in motionrefs)
packed_writer = rw.write.PackedWriter()
packed_writer.puts(refs)
chunked_writer.put(fmt.Chunks.Object.MOTION_REFS, packed_writer)
else:
writer = rw.write.PackedWriter()
writer.putf('<I', len(motionrefs))
for ref in motionrefs:
writer.puts(ref.name)
chunked_writer.put(fmt.Chunks.Object.SMOTIONS3, writer)
elif xray.motionrefs:
packed_writer = rw.write.PackedWriter()
packed_writer.puts(xray.motionrefs)
chunked_writer.put(fmt.Chunks.Object.MOTION_REFS, packed_writer)
def export_transform(chunked_writer, bpy_root):
root_matrix = bpy_root.matrix_world
if root_matrix != mathutils.Matrix.Identity(4):
loc_mat, rot_mat = utils.ie.get_object_transform_matrix(bpy_root)
writer = rw.write.PackedWriter()
writer.putv3f(loc_mat.to_translation())
writer.putv3f(rot_mat.to_euler('YXZ'))
chunked_writer.put(fmt.Chunks.Object.TRANSFORM, writer)
def export_revision(chunked_writer, xray):
owner, ctime, moder, mtime = utils.obj.get_revision_data(xray.revision)
writer = rw.write.PackedWriter()
writer.puts(owner)
writer.putf('<I', ctime)
writer.puts(moder)
writer.putf('<I', mtime)
chunked_writer.put(fmt.Chunks.Object.REVISION, writer)
def export_main(bpy_obj, chunked_writer, context):
xray = bpy_obj.xray
export_version(chunked_writer)
export_user_data(chunked_writer, xray)
export_lod_ref(chunked_writer, xray)
materials, bone_writers, some_arm, bpy_root, uv_map_names = export_meshes(
chunked_writer,
bpy_obj,
context,
xray
)
export_surfaces(chunked_writer, context, materials, uv_map_names)
export_bones(chunked_writer, bone_writers)
export_motions(chunked_writer, some_arm, context, bpy_root)
export_motion_refs(chunked_writer, xray, context)
export_partitions(chunked_writer, some_arm)
export_transform(chunked_writer, bpy_root)
export_revision(chunked_writer, xray)
def export_body(bpy_obj, chunked_writer, context):
writer = rw.write.ChunkedWriter()
export_main(bpy_obj, writer, context)
chunked_writer.put(fmt.Chunks.Object.MAIN, writer)
@log.with_context('export-object')
@utils.stats.timer
def export_file(bpy_obj, file_path, context):
utils.stats.status('Export File', file_path)
log.update(object=bpy_obj.name)
writer = rw.write.ChunkedWriter()
export_body(bpy_obj, writer, context)
rw.utils.save_file(file_path, writer)
|
86d82af5c6c64998371ee8246207a7926851ab3d
|
bbd69601912a3361d788efd03a47f9d4e3bac09e
|
/demo/ContextHelp.py
|
f13f218c9f56bbe3b11c202bac275d0323a247c0
|
[] |
no_license
|
wxWidgets/Phoenix
|
56929484460a0399a8f1d9582bc77c20aa14748d
|
a1184286703cf24c4b88e5bc14cf2979c1b1ea00
|
refs/heads/master
| 2023-09-01T07:10:17.437093
| 2023-08-31T05:38:01
| 2023-08-31T05:38:01
| 5,078,061
| 2,268
| 677
| null | 2023-09-09T17:06:59
| 2012-07-17T06:22:25
|
Python
|
UTF-8
|
Python
| false
| false
| 4,032
|
py
|
ContextHelp.py
|
#!/usr/bin/env python
import wx
#----------------------------------------------------------------------
# We first have to set an application-wide help provider. Normally you
# would do this in your app's OnInit or in other startup code...
provider = wx.SimpleHelpProvider()
wx.HelpProvider.Set(provider)
# This panel is chock full of controls about which we can demonstrate the
# help system.
class TestPanel(wx.Panel):
def __init__(self, parent, log):
wx.Panel.__init__(self, parent, -1)
self.log = log
# This help text, set for the panel itself, will be used if context
# sensitive help cannot be found for any particular control.
self.SetHelpText("This is a wx.Panel.")
sizer = wx.BoxSizer(wx.VERTICAL)
# Init the context help button.
# And even include help text about the help button :-)
cBtn = wx.ContextHelpButton(self)
cBtn.SetHelpText("wx.ContextHelpButton")
cBtnText = wx.StaticText(self, -1,
"This is a wx.ContextHelpButton. Clicking it puts the\n"
"app into context sensitive help mode."
)
# Yes, even static text can have help text associated with it :-)
cBtnText.SetHelpText("Some helpful text...")
s = wx.BoxSizer(wx.HORIZONTAL)
s.Add(cBtn, 0, wx.ALL, 5)
s.Add(cBtnText, 0, wx.ALL, 5)
sizer.Add((20,20))
sizer.Add(s)
# A text control with help text.
text = wx.TextCtrl(self, -1, "Each sub-window can have its own help message",
size=(240, 60), style=wx.TE_MULTILINE)
text.SetHelpText("This is my very own help message. This is a really long long long long long long long long long long long long long long long long long long long long message!")
sizer.Add((20,20))
sizer.Add(text)
# Same thing, but this time to demonstrate how the help event can be
# intercepted.
text = wx.TextCtrl(self, -1, "You can also intercept the help event if you like. Watch the log window when you click here...",
size=(240, 60), style = wx.TE_MULTILINE)
text.SetHelpText("Yet another context help message.")
sizer.Add((20,20))
sizer.Add(text)
text.Bind(wx.EVT_HELP, self.OnCtxHelp, text)
text = wx.TextCtrl(self, -1, "This one displays the tip itself...",
size=(240, 60), style = wx.TE_MULTILINE)
sizer.Add((20,20))
sizer.Add(text)
text.Bind(wx.EVT_HELP, self.OnCtxHelp2, text)
border = wx.BoxSizer(wx.VERTICAL)
border.Add(sizer, 0, wx.ALL, 25)
self.SetAutoLayout(True)
self.SetSizer(border)
self.Layout()
# On the second text control above, we intercept the help event. This is where
# we process it. Anything could happen here. In this case we're just printing
# some stuff about it, then passing it on with Skip(), at which point we
# see the help tip.
def OnCtxHelp(self, evt):
self.log.write("OnCtxHelp: %s" % evt)
evt.Skip()
# On the third text control above, we intercept the help event.
# Here, we print a note about it, generate our own tip window, and,
# unlike last time, we don't pass it on to the underlying provider.
def OnCtxHelp2(self, evt):
self.log.write("OnCtxHelp2: %s\n" % evt)
tip = wx.TipWindow(self, "This is a wx.TipWindow")
#----------------------------------------------------------------------
def runTest(frame, nb, log):
win = TestPanel(nb, log)
return win
#----------------------------------------------------------------------
overview = """
This demo shows how to incorporate Context Sensitive
help into your application using the wx.SimpleHelpProvider class.
"""
#----------------------------------------------------------------------
if __name__ == '__main__':
import sys,os
import run
run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])
|
902f0a2022a3618051135774b82caf234e17cf89
|
9ee89ea711a14565d8664f180b213c0e0bd423ac
|
/pywinauto/unittests/test_common_controls.py
|
630c44ebbf033842a42d79933a99318d4d35c050
|
[
"BSD-3-Clause",
"LGPL-2.1-or-later",
"LGPL-2.1-only"
] |
permissive
|
pywinauto/pywinauto
|
c55b3f42d0b9d5b18b005527edd791f4da05f805
|
bf7f789d01b7c66ccd0c213db0a029da7e588c9e
|
refs/heads/atspi
| 2023-08-30T21:05:31.992955
| 2022-12-29T15:23:40
| 2022-12-30T10:52:06
| 36,223,210
| 4,466
| 819
|
BSD-3-Clause
| 2023-09-12T02:26:23
| 2015-05-25T09:50:40
|
Python
|
UTF-8
|
Python
| false
| false
| 62,825
|
py
|
test_common_controls.py
|
# GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of pywinauto nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests for classes in controls\common_controls.py"""
from __future__ import print_function
import sys
#import ctypes
import unittest
import time
from datetime import datetime
#import pdb
import os
import win32api
import win32gui
import six
sys.path.append(".")
from pywinauto.windows.application import Application # noqa: E402
from pywinauto.windows.win32structures import RECT # noqa: E402
from pywinauto.windows import win32defines
from pywinauto import findbestmatch # noqa: E402
from pywinauto.sysinfo import is_x64_Python # noqa: E402
from pywinauto.windows.remote_memory_block import RemoteMemoryBlock # noqa: E402
from pywinauto.actionlogger import ActionLogger # noqa: E402
from pywinauto.timings import Timings # noqa: E402
from pywinauto.timings import wait_until # noqa: E402
from pywinauto import mouse # noqa: E402
controlspy_folder = os.path.join(
os.path.dirname(__file__), r"..\..\apps\controlspy0998")
controlspy_folder_32 = controlspy_folder
mfc_samples_folder = os.path.join(
os.path.dirname(__file__), r"..\..\apps\MFC_samples")
mfc_samples_folder_32 = mfc_samples_folder
winforms_folder = os.path.join(
os.path.dirname(__file__), r"..\..\apps\WinForms_samples")
winforms_folder_32 = winforms_folder
if is_x64_Python():
controlspy_folder = os.path.join(controlspy_folder, 'x64')
mfc_samples_folder = os.path.join(mfc_samples_folder, 'x64')
winforms_folder = os.path.join(winforms_folder, 'x64')
class RemoteMemoryBlockTestCases(unittest.TestCase):
def test__init__fail(self):
self.assertRaises(AttributeError, RemoteMemoryBlock, 0)
class ListViewTestCases32(unittest.TestCase):
"""Unit tests for the ListViewWrapper class"""
path = os.path.join(mfc_samples_folder_32, u"RowList.exe")
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.fast()
app = Application()
app.start(self.path)
self.texts = [
(u"Yellow", u"255", u"255", u"0", u"40", u"240", u"120", u"Neutral"),
(u"Red", u"255", u"0", u"0", u"0", u"240", u"120", u"Warm"),
(u"Green", u"0", u"255", u"0", u"80", u"240", u"120", u"Cool"),
(u"Magenta", u"255", u"0", u"255", u"200", u"240", u"120", u"Warm"),
(u"Cyan", u"0", u"255", u"255", u"120", u"240", u"120", u"Cool"),
(u"Blue", u"0", u"0", u"255", u"160", u"240", u"120", u"Cool"),
(u"Gray", u"192", u"192", u"192", u"160", u"0", u"181", u"Neutral")
]
self.app = app
self.dlg = app.RowListSampleApplication
self.ctrl = app.RowListSampleApplication.ListView.find()
self.dlg.Toolbar.button(0).click() # switch to icon view
self.dlg.Toolbar.button(6).click() # switch off states
def tearDown(self):
"""Close the application after tests"""
self.dlg.send_message(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"""Make sure the ListView friendly class is set correctly"""
self.assertEqual(self.ctrl.friendly_class_name(), u"ListView")
def testColumnCount(self):
"""Test the ListView ColumnCount method"""
self.assertEqual(self.ctrl.column_count(), 8)
def testItemCount(self):
"""Test the ListView ItemCount method"""
self.assertEqual(self.ctrl.item_count(), 7)
def testItemText(self):
"""Test the ListView item.Text property"""
item = self.ctrl.get_item(1)
self.assertEqual(item.text(), u"Red")
def testItems(self):
"""Test the ListView Items method"""
flat_texts = []
for row in self.texts:
flat_texts.extend(row)
items = self.ctrl.items()
for i, item in enumerate(items):
self.assertEqual(item.text(), flat_texts[i])
self.assertEqual(len(items), len(flat_texts))
def testTexts(self):
"""Test the ListView texts method"""
flat_texts = []
for row in self.texts:
flat_texts.extend(row)
self.assertEqual(flat_texts, self.ctrl.texts()[1:])
def testGetItem(self):
"""Test the ListView get_item method"""
for row in range(self.ctrl.item_count()):
for col in range(self.ctrl.column_count()):
self.assertEqual(
self.ctrl.get_item(row, col).text(), self.texts[row][col])
def testGetItemText(self):
"""Test the ListView get_item method - with text this time"""
for text in [row[0] for row in self.texts]:
self.assertEqual(
self.ctrl.get_item(text).text(), text)
self.assertRaises(ValueError, self.ctrl.get_item, "Item not in this list")
def testColumn(self):
"""Test the ListView columns method"""
cols = self.ctrl.columns()
self.assertEqual(len(cols), self.ctrl.column_count())
# TODO: add more checking of column values
#for col in cols:
# print(col)
def testGetSelectionCount(self):
"""Test the ListView get_selected_count method"""
self.assertEqual(self.ctrl.get_selected_count(), 0)
self.ctrl.get_item(1).select()
self.ctrl.get_item(6).select()
self.assertEqual(self.ctrl.get_selected_count(), 2)
# def testGetSelectionCount(self):
# "Test the ListView get_selected_count method"
#
# self.assertEqual(self.ctrl.get_selected_count(), 0)
#
# self.ctrl.select(1)
# self.ctrl.select(7)
#
# self.assertEqual(self.ctrl.get_selected_count(), 2)
def testIsSelected(self):
"""Test ListView IsSelected for some items"""
# ensure that the item is not selected
self.assertEqual(self.ctrl.get_item(1).is_selected(), False)
# select an item
self.ctrl.get_item(1).select()
# now ensure that the item is selected
self.assertEqual(self.ctrl.get_item(1).is_selected(), True)
def _testFocused(self):
"""Test checking the focus of some ListView items"""
print("Select something quick!!")
time.sleep(3)
#self.ctrl.select(1)
print(self.ctrl.is_focused(0))
print(self.ctrl.is_focused(1))
print(self.ctrl.is_focused(2))
print(self.ctrl.is_focused(3))
print(self.ctrl.is_focused(4))
print(self.ctrl.is_focused(5))
#for col in cols:
# print(col)
def testSelect(self):
"""Test ListView Selecting some items"""
self.ctrl.get_item(1).select()
self.ctrl.get_item(3).select()
self.ctrl.get_item(4).select()
self.assertRaises(IndexError, self.ctrl.get_item(23).select)
self.assertEqual(self.ctrl.get_selected_count(), 3)
def testSelectText(self):
"""Test ListView Selecting some items"""
self.ctrl.get_item(u"Green").select()
self.ctrl.get_item(u"Yellow").select()
self.ctrl.get_item(u"Gray").select()
self.assertRaises(ValueError, self.ctrl.get_item, u"Item not in list")
self.assertEqual(self.ctrl.get_selected_count(), 3)
def testDeselect(self):
"""Test ListView Selecting some items"""
self.ctrl.get_item(1).select()
self.ctrl.get_item(4).select()
self.ctrl.get_item(3).deselect()
self.ctrl.get_item(4).deselect()
self.assertRaises(IndexError, self.ctrl.get_item(23).deselect)
self.assertEqual(self.ctrl.get_selected_count(), 1)
def testGetProperties(self):
"""Test getting the properties for the listview control"""
props = self.ctrl.get_properties()
self.assertEqual(
"ListView", props['friendly_class_name'])
self.assertEqual(
self.ctrl.texts(), props['texts'])
for prop_name in props.keys():
self.assertEqual(getattr(self.ctrl, prop_name)(), props[prop_name])
self.assertEqual(props['column_count'], 8)
self.assertEqual(props['item_count'], 7)
def testGetColumnTexts(self):
"""Test columns titles text"""
self.assertEqual(self.ctrl.get_column(0)['text'], u"Color")
self.assertEqual(self.ctrl.get_column(1)['text'], u"Red")
self.assertEqual(self.ctrl.get_column(2)['text'], u"Green")
self.assertEqual(self.ctrl.get_column(3)['text'], u"Blue")
def testItemRectangles(self):
"""Test getting item rectangles"""
yellow_rect = self.ctrl.get_item_rect('Yellow')
gold_rect = RECT(13, 0, 61, 53)
self.assertEqual(yellow_rect.left, gold_rect.left)
self.assertEqual(yellow_rect.top, gold_rect.top)
self.assertEqual(yellow_rect.right, gold_rect.right)
if yellow_rect.bottom < 53 or yellow_rect.bottom > 55:
self.assertEqual(yellow_rect.bottom, gold_rect.bottom)
self.ctrl.get_item('Green').click(where='text')
self.assertEqual(self.ctrl.get_item('Green').is_selected(), True)
self.ctrl.get_item('Magenta').click(where='icon')
self.assertEqual(self.ctrl.get_item('Magenta').is_selected(), True)
self.assertEqual(self.ctrl.get_item('Green').is_selected(), False)
self.ctrl.get_item('Green').click(where='all')
self.assertEqual(self.ctrl.get_item('Green').is_selected(), True)
self.assertEqual(self.ctrl.get_item('Magenta').is_selected(), False)
def testItemCheck(self):
"""Test checking/unchecking item"""
if not self.dlg.Toolbar.button(6).is_checked():
self.dlg.Toolbar.button(6).click()
yellow = self.ctrl.get_item('Yellow')
yellow.check()
self.assertEqual(yellow.is_checked(), True)
yellow.uncheck()
self.assertEqual(yellow.is_checked(), False)
# test legacy deprecated methods (TODO: remove later)
self.ctrl.get_item('Yellow').check()
self.assertEqual(self.ctrl.get_item('Yellow').is_checked(), True)
self.ctrl.get_item('Yellow').uncheck()
self.assertEqual(self.ctrl.get_item('Yellow').is_checked(), False)
def testItemClick(self):
"""Test clicking item rectangles by click() method"""
self.ctrl.get_item('Green').click(where='select')
self.assertEqual(self.ctrl.get_item('Green').is_selected(), True)
self.ctrl.get_item('Magenta').click(where='select')
self.assertEqual(self.ctrl.get_item('Magenta').is_selected(), True)
self.assertEqual(self.ctrl.get_item('Green').is_selected(), False)
self.assertEqual(self.ctrl.get_item('Green').is_focused(), False)
self.assertEqual(self.ctrl.get_item('Green').state() & win32defines.LVIS_FOCUSED, 0)
self.ctrl.get_item('Green').click(where='select')
self.assertEqual(self.ctrl.get_item('Green').is_selected(), True)
self.assertEqual(self.ctrl.is_selected('Green'), True) # TODO: deprecated method
self.assertEqual(self.ctrl.get_item('Green').is_focused(), True)
self.assertEqual(self.ctrl.is_focused('Green'), True) # TODO: deprecated method
self.assertEqual(self.ctrl.get_item('Magenta').is_selected(), False)
# Test click on checkboxes
if not self.dlg.Toolbar.button(6).is_checked(): # switch on states
self.dlg.Toolbar.button(6).click()
for i in range(1, 6):
self.dlg.Toolbar.button(i - 1).click()
self.ctrl.get_item(i).click(where='check') # check item
time.sleep(0.5)
self.assertEqual(self.ctrl.get_item(i).is_checked(), True)
self.assertEqual(self.ctrl.get_item(i - 1).is_checked(), False)
self.ctrl.get_item(i).click(where='check') # uncheck item
time.sleep(0.5)
self.assertEqual(self.ctrl.get_item(i).is_checked(), False)
self.ctrl.get_item(i).click(where='check') # recheck item
time.sleep(0.5)
self.assertEqual(self.ctrl.get_item(i).is_checked(), True)
self.dlg.Toolbar.button(6).click() # switch off states
self.assertRaises(RuntimeError, self.ctrl.get_item(6).click, where="check")
def testItemClickInput(self):
"""Test clicking item rectangles by click_input() method"""
Timings.defaults()
self.ctrl.get_item('Green').click_input(where='select')
self.assertEqual(self.ctrl.get_item('Green').is_selected(), True)
self.ctrl.get_item('Magenta').click_input(where='select')
self.assertEqual(self.ctrl.get_item('Magenta').is_selected(), True)
self.assertEqual(self.ctrl.get_item('Green').is_selected(), False)
self.assertEqual(self.ctrl.get_item('Green').is_focused(), False)
self.assertEqual(self.ctrl.get_item('Green').state() & win32defines.LVIS_FOCUSED, 0)
self.ctrl.get_item('Green').click_input(where='select')
self.assertEqual(self.ctrl.get_item('Green').is_selected(), True)
self.assertEqual(self.ctrl.is_selected('Green'), True) # TODO: deprecated method
self.assertEqual(self.ctrl.get_item('Green').is_focused(), True)
self.assertEqual(self.ctrl.is_focused('Green'), True) # TODO: deprecated method
self.assertEqual(self.ctrl.get_item('Magenta').is_selected(), False)
# Test click on checkboxes
if not self.dlg.Toolbar.button(6).is_checked(): # switch on states
self.dlg.Toolbar.button(6).click()
for i in range(1, 6):
self.dlg.Toolbar.button(i - 1).click()
self.ctrl.get_item(i).click_input(where='check') # check item
time.sleep(0.5)
self.assertEqual(self.ctrl.get_item(i).is_checked(), True)
self.assertEqual(self.ctrl.get_item(i - 1).is_checked(), False)
self.ctrl.get_item(i).click_input(where='check') # uncheck item
time.sleep(0.5)
self.assertEqual(self.ctrl.get_item(i).is_checked(), False)
self.ctrl.get_item(i).click_input(where='check') # recheck item
time.sleep(0.5)
self.assertEqual(self.ctrl.get_item(i).is_checked(), True)
self.dlg.Toolbar.button(6).click() # switch off states
self.assertRaises(RuntimeError, self.ctrl.get_item(6).click_input, where="check")
def testItemMethods(self):
"""Test short item methods like Text(), State() etc"""
self.assertEqual(self.ctrl.get_item('Green').text(), 'Green')
self.assertEqual(self.ctrl.get_item('Green').image(), 2)
self.assertEqual(self.ctrl.get_item('Green').indent(), 0)
def test_ensure_visible(self):
self.dlg.move_window(width=300)
# Gray is selected by click because ensure_visible() is called inside
self.ctrl.get_item('Gray').click()
self.assertEqual(self.ctrl.get_item('Gray').is_selected(), True)
self.dlg.set_focus() # just in case
self.ctrl.get_item('Green').ensure_visible()
self.ctrl.get_item('Red').click()
self.assertEqual(self.ctrl.get_item('Gray').is_selected(), False)
self.assertEqual(self.ctrl.get_item('Red').is_selected(), True)
#
# def testSubItems(self):
#
# for row in range(self.ctrl.item_count())
#
# for i in self.ctrl.items():
#
# #self.assertEqual(item.Text, texts[i])
def testEqualsItems(self):
"""
Test __eq__ and __ne__ cases for _listview_item.
"""
item1 = self.ctrl.get_item(0, 0)
item1_copy = self.ctrl.get_item(0, 0)
item2 = self.ctrl.get_item(1, 0)
self.assertEqual(item1, item1_copy)
self.assertNotEqual(item1, "Not _listview_item")
self.assertNotEqual(item1, item2)
def test_cells_rectangles(self):
"""Test the ListView get_item rectangle method for cells"""
if not self.dlg.Toolbar.button(4).is_checked():
self.dlg.Toolbar.button(4).click()
for row in range(self.ctrl.item_count() - 1):
for col in range(self.ctrl.column_count() - 1):
self.assertEqual(
self.ctrl.get_item(row, col).rectangle(area="text").right,
self.ctrl.get_item(row, col + 1).rectangle(area="text").left)
self.assertEqual(
self.ctrl.get_item(row, col).rectangle(area="text").bottom,
self.ctrl.get_item(row + 1, col).rectangle(area="text").top)
self.assertEqual(self.ctrl.get_item(1, 2).rectangle(area="text"),
RECT(200, 36, 250, 53))
self.assertEqual(self.ctrl.get_item(3, 4).rectangle(area="text"),
RECT(300, 70, 400, 87))
def test_inplace_control(self):
"""Test the ListView inplace_control method for item"""
# Item is not editable so it will raise timeout error
with self.assertRaises(Exception) as context:
self.ctrl.get_item(0).inplace_control()
self.assertTrue('In-place-edit control for item' in str(context.exception))
if is_x64_Python():
class ListViewTestCases64(ListViewTestCases32):
"""Unit tests for the 64-bit ListViewWrapper on a 32-bit sample"""
path = os.path.join(mfc_samples_folder, u"RowList.exe")
class ListViewWinFormTestCases32(unittest.TestCase):
"""Unit tests for the ListViewWrapper class with WinForm applications"""
path = os.path.join(winforms_folder_32, u"ListView_TestApp.exe")
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.defaults()
app = Application()
app.start(self.path)
self.dlg = app.ListViewEx
self.ctrl = self.dlg.ListView.find()
def tearDown(self):
"""Close the application after tests"""
self.dlg.send_message(win32defines.WM_CLOSE)
def test_cell_click_input(self):
"""Test the ListView get_item click_input method"""
self.ctrl.get_item(0,2).click_input(double=True, where="text")
self.dlg.type_keys("{ENTER}")
# For make sure the input is finished, click to another place
self.ctrl.get_item(0,3).click_input(double=False, where="text")
self.assertEqual(str(self.ctrl.get_item(0,2).text()), u"Clicked!")
def test_get_editor_of_datetimepicker(self):
"""Test the ListView inplace_control method using DateTimePicker"""
dt_picker = self.ctrl.get_item(2,0).inplace_control("DateTimePicker")
dt_picker.set_time(year=2017, month=5, day=23)
cur_time = dt_picker.get_time();
self.assertEqual(cur_time.wYear, 2017)
self.assertEqual(cur_time.wMonth, 5)
self.assertEqual(cur_time.wDay, 23)
def test_get_editor_of_combobox(self):
"""Test the ListView inplace_control method using ComboBox"""
combo_box = self.ctrl.get_item(1,1).inplace_control("ComboBox")
combo_box.select(combo_box.selected_index() - 1)
self.assertEqual(combo_box.selected_index(), 2)
def test_get_editor_of_editwrapper(self):
"""Test the ListView inplace_control method using EditWrapper"""
dt_picker = self.ctrl.get_item(3,4).inplace_control("Edit")
dt_picker.set_text("201")
self.assertEqual(dt_picker.text_block(), u"201")
def test_get_editor_wrong_args(self):
"""Test the ListView inplace_control case when used wrong friendly class name"""
with self.assertRaises(Exception) as context:
self.ctrl.get_item(1,1).inplace_control("Edit")
self.assertTrue('In-place-edit control "Edit"' in str(context.exception))
def test_automation_id_by_win32(self):
list_view = self.dlg.by(auto_id="listViewEx1").wait('visible')
self.assertEqual(list_view.automation_id(), "listViewEx1")
check_box = self.dlg.by(auto_id="checkBoxDoubleClickActivation").wait('visible')
self.assertEqual(check_box.automation_id(), "checkBoxDoubleClickActivation")
check_box = self.dlg.checkBoxDoubleClickActivation.wait('visible')
self.assertEqual(check_box.automation_id(), "checkBoxDoubleClickActivation")
def test_win32_control_type(self):
list_view = self.dlg.by(control_type="ListViewEx.ListViewEx").wait('visible')
self.assertEqual(list_view.control_type(), "ListViewEx.ListViewEx")
self.assertEqual(list_view.full_control_type(),
"ListViewEx.ListViewEx, ListViewEx, Version=1.0.6520.42612, " \
"Culture=neutral, PublicKeyToken=null")
check_box = self.dlg.by(control_type="System.Windows.Forms.CheckBox").wait('visible')
self.assertEqual(check_box.control_type(), "System.Windows.Forms.CheckBox")
self.assertEqual(check_box.full_control_type(),
"System.Windows.Forms.CheckBox, System.Windows.Forms, " \
"Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
if is_x64_Python():
class ListViewWinFormTestCases64(ListViewWinFormTestCases32):
"""Unit tests for the 64-bit ListViewWrapper on a 32-bit sample"""
path = os.path.join(winforms_folder, u"ListView_TestApp.exe")
class TreeViewTestCases32(unittest.TestCase):
"""Unit tests for the TreeViewWrapper class"""
path = os.path.join(controlspy_folder_32, "Tree View.exe")
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.fast()
self.root_text = "The Planets"
self.texts = [
("Mercury", '57,910,000', '4,880', '3.30e23'),
("Venus", '108,200,000', '12,103.6', '4.869e24'),
("Earth", '149,600,000', '12,756.3', '5.9736e24'),
("Mars", '227,940,000', '6,794', '6.4219e23'),
("Jupiter", '778,330,000', '142,984', '1.900e27'),
("Saturn", '1,429,400,000', '120,536', '5.68e26'),
("Uranus", '2,870,990,000', '51,118', '8.683e25'),
("Neptune", '4,504,000,000', '49,532', '1.0247e26'),
("Pluto", '5,913,520,000', '2,274', '1.27e22'),
]
self.app = Application()
self.app.start(self.path)
self.dlg = self.app.MicrosoftControlSpy
self.ctrl = self.app.MicrosoftControlSpy.TreeView.find()
def tearDown(self):
"""Close the application after tests"""
self.dlg.send_message(win32defines.WM_CLOSE)
def test_friendly_class_name(self):
"""Make sure the friendly class name is set correctly (TreeView)"""
self.assertEqual(self.ctrl.friendly_class_name(), "TreeView")
def testItemCount(self):
"""Test the TreeView ItemCount method"""
self.assertEqual(self.ctrl.item_count(), 37)
def testGetItem(self):
"""Test the get_item method"""
self.assertRaises(RuntimeError, self.ctrl.get_item, "test\here\please")
self.assertRaises(IndexError, self.ctrl.get_item, r"\test\here\please")
self.assertEqual(
self.ctrl.get_item((0, 1, 2)).text(), self.texts[1][3] + " kg")
self.assertEqual(
self.ctrl.get_item(r"\The Planets\Venus\4.869e24 kg", exact=True).text(), self.texts[1][3] + " kg")
self.assertEqual(
self.ctrl.get_item(["The Planets", "Venus", "4.869"]).text(),
self.texts[1][3] + " kg"
)
def testItemText(self):
"""Test the TreeView item Text() method"""
self.assertEqual(self.ctrl.tree_root().text(), self.root_text)
self.assertEqual(
self.ctrl.get_item((0, 1, 2)).text(), self.texts[1][3] + " kg")
def testSelect(self):
"""Test selecting an item"""
self.ctrl.select((0, 1, 2))
self.ctrl.get_item((0, 1, 2)).state()
self.assertEqual(True, self.ctrl.is_selected((0, 1, 2)))
def testEnsureVisible(self):
"""make sure that the item is visible"""
# TODO: note this is partially a fake test at the moment because
# just by getting an item - we usually make it visible
self.ctrl.ensure_visible((0, 8, 2))
# make sure that the item is not hidden
self.assertNotEqual(None, self.ctrl.get_item((0, 8, 2)).client_rect())
def testGetProperties(self):
"""Test getting the properties for the treeview control"""
props = self.ctrl.get_properties()
self.assertEqual(
"TreeView", props['friendly_class_name'])
self.assertEqual(
self.ctrl.texts(), props['texts'])
for prop_name in props:
self.assertEqual(getattr(self.ctrl, prop_name)(), props[prop_name])
def testItemsClick(self):
"""Test clicking of items and sub-items in the treeview control"""
planets_item_path = (0, 0)
mercury_diam_item_path = (0, 0, 1)
mars_dist_item_path = (0, 3, 0)
itm = self.ctrl.get_item(planets_item_path)
itm.ensure_visible()
time.sleep(1)
itm.click(button='left')
self.assertEqual(True, self.ctrl.is_selected(planets_item_path))
itm = self.ctrl.get_item(mars_dist_item_path)
itm.ensure_visible()
time.sleep(1)
itm.click(button='left')
self.assertEqual(True, self.ctrl.is_selected(mars_dist_item_path))
itm = self.ctrl.get_item(mercury_diam_item_path)
itm.ensure_visible()
time.sleep(1)
itm.click(button='left')
self.assertEqual(True, self.ctrl.is_selected(mercury_diam_item_path))
self.assertEqual(False, self.ctrl.is_selected(mars_dist_item_path))
itm = self.ctrl.get_item(planets_item_path)
itm.ensure_visible()
time.sleep(1)
itm.click(button='left')
self.assertEqual(True, self.ctrl.is_selected(planets_item_path))
self.assertEqual(False, self.ctrl.is_selected(mercury_diam_item_path))
if is_x64_Python():
class TreeViewTestCases64(TreeViewTestCases32):
"""Unit tests for the 64-bit TreeViewWrapper on a 32-bit sample"""
path = os.path.join(controlspy_folder, "Tree View.exe")
class TreeViewAdditionalTestCases(unittest.TestCase):
"""More unit tests for the TreeViewWrapper class (CmnCtrl1.exe)"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.fast()
self.app = Application().start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe"))
self.dlg = self.app.CommonControlsSample
self.ctrl = self.app.CommonControlsSample.TreeView.find()
self.app.wait_cpu_usage_lower(threshold=1.5, timeout=30, usage_interval=1)
def tearDown(self):
"""Close the application after tests"""
self.dlg.send_message(win32defines.WM_CLOSE)
self.app.kill()
def testCheckBoxes(self):
"""Make sure tree view item method is_checked() works as expected"""
self.dlg.set_focus()
self.dlg.TVS_CHECKBOXES.uncheck_by_click()
self.dlg.TVS_CHECKBOXES.check_by_click()
birds = self.ctrl.get_item(r'\Birds')
self.ctrl.set_focus() # to make sure focus is not lost by any accident event
birds.click(where='check')
self.assertEqual(birds.is_checked(), True)
birds.click_input(where='check')
wait_until(3, 0.4, birds.is_checked, value=False)
def testPrintItems(self):
"""Test TreeView method print_items()"""
birds = self.ctrl.get_item(r'\Birds')
birds.expand()
items_str = self.ctrl.print_items()
self.assertEqual(items_str, "Treeview1\nBirds\n Eagle\n Hummingbird\n Pigeon\n" +
"Dogs\n Dalmatian\n German Shepherd\n Great Dane\n" +
"Fish\n Salmon\n Snapper\n Sole\n")
def testIsSelected(self):
"""Make sure tree view item method IsSelected() works as expected"""
birds = self.ctrl.get_item(r'\Birds')
birds.expand()
eagle = self.ctrl.get_item(r'\Birds\Eagle')
eagle.select()
self.assertEqual(eagle.is_selected(), True)
def test_expand_collapse(self):
"""Make sure tree view item methods Expand() and Collapse() work as expected"""
birds = self.ctrl.get_item(r'\Birds')
birds.expand()
self.assertEqual(birds.is_expanded(), True)
birds.collapse()
self.assertEqual(birds.is_expanded(), False)
def test_expand_collapse_buttons(self):
"""Make sure correct area is clicked"""
self.dlg.TVS_HASBUTTONS.click_input()
self.dlg.TVS_HASLINES.click_input()
self.dlg.TVS_LINESATROOT.click_input()
birds = self.ctrl.get_item(r'\Birds')
birds.click(where='button')
self.assertEqual(birds.is_expanded(), True)
birds.click(double=True, where='icon')
self.assertEqual(birds.is_expanded(), False)
birds.click_input(where='button')
self.assertEqual(birds.is_expanded(), True)
time.sleep(win32gui.GetDoubleClickTime() * 2.0 / 1000)
birds.click_input(double=True, where='icon')
self.assertEqual(birds.is_expanded(), False)
def testIncorrectAreas(self):
"""Make sure incorrect area raises an exception"""
birds = self.ctrl.get_item(r'\Birds')
self.assertRaises(RuntimeError, birds.click, where='radiob')
self.assertRaises(RuntimeError, birds.click_input, where='radiob')
def testStartDraggingAndDrop(self):
"""Make sure tree view item methods StartDragging() and drop() work as expected"""
birds = self.ctrl.get_item(r'\Birds')
birds.expand()
pigeon = self.ctrl.get_item(r'\Birds\Pigeon')
pigeon.start_dragging()
eagle = self.ctrl.get_item(r'\Birds\Eagle')
eagle.drop()
self.assertRaises(IndexError, birds.get_child, 'Pigeon')
self.assertRaises(IndexError, self.ctrl.get_item, r'\Birds\Pigeon')
self.assertRaises(IndexError, self.ctrl.get_item, [0, 2])
self.assertRaises(IndexError, self.ctrl.get_item, r'\Bread', exact=True)
new_pigeon = self.ctrl.get_item(r'\Birds\Eagle\Pigeon')
self.assertEqual(len(birds.children()), 2)
self.assertEqual(new_pigeon.children(), [])
class HeaderTestCases(unittest.TestCase):
"""Unit tests for the Header class"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.fast()
app = Application()
app.start(os.path.join(mfc_samples_folder, "RowList.exe"), timeout=20)
self.texts = [u'Color', u'Red', u'Green', u'Blue', u'Hue', u'Sat', u'Lum', u'Type']
self.item_rects = [
RECT(000, 0, 150, 19),
RECT(150, 0, 200, 19),
RECT(200, 0, 250, 19),
RECT(250, 0, 300, 19),
RECT(300, 0, 400, 19),
RECT(400, 0, 450, 19),
RECT(450, 0, 500, 19),
RECT(500, 0, 650, 19)]
self.app = app
self.dlg = app.RowListSampleApplication
self.ctrl = app.RowListSampleApplication.Header.find()
def tearDown(self):
"""Close the application after tests"""
# close the application
self.dlg.send_message(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"""Make sure the friendly class is set correctly (Header)"""
self.assertEqual(self.ctrl.friendly_class_name(), "Header")
def testTexts(self):
"""Make sure the texts are set correctly"""
self.assertEqual(self.ctrl.texts()[1:], self.texts)
def testGetProperties(self):
"""Test getting the properties for the header control"""
props = self.ctrl.get_properties()
self.assertEqual(
self.ctrl.friendly_class_name(), props['friendly_class_name'])
self.assertEqual(
self.ctrl.texts(), props['texts'])
for prop_name in props:
self.assertEqual(getattr(self.ctrl, prop_name)(), props[prop_name])
def testItemCount(self):
self.assertEqual(8, self.ctrl.item_count())
def testGetColumnRectangle(self):
for i in range(0, 3):
self.assertEqual(self.item_rects[i].left, self.ctrl.get_column_rectangle(i).left)
self.assertEqual(self.item_rects[i].right, self.ctrl.get_column_rectangle(i).right)
self.assertEqual(self.item_rects[i].top, self.ctrl.get_column_rectangle(i).top)
self.assertFalse(abs(self.item_rects[i].bottom - self.ctrl.get_column_rectangle(i).bottom) > 2)
def testClientRects(self):
test_rects = self.item_rects
test_rects.insert(0, self.ctrl.client_rect())
client_rects = self.ctrl.client_rects()
self.assertEqual(len(test_rects), len(client_rects))
for i, r in enumerate(test_rects):
self.assertEqual(r.left, client_rects[i].left)
self.assertEqual(r.right, client_rects[i].right)
self.assertEqual(r.top, client_rects[i].top)
self.assertFalse(abs(r.bottom - client_rects[i].bottom) > 2) # may be equal to 17 or 19
def testGetColumnText(self):
for i in range(0, 3):
self.assertEqual(
self.texts[i],
self.ctrl.get_column_text(i))
class StatusBarTestCases(unittest.TestCase):
"""Unit tests for the TreeViewWrapper class"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.fast()
app = Application()
app.start(os.path.join(controlspy_folder, "Status bar.exe"))
self.texts = ["Long text", "", "Status Bar"]
self.part_rects = [
RECT(0, 2, 65, 22),
RECT(67, 2, 90, 22),
RECT(92, 2, 261, 22)]
self.app = app
self.dlg = app.MicrosoftControlSpy
self.ctrl = app.MicrosoftControlSpy.StatusBar.find()
def tearDown(self):
"""Close the application after tests"""
self.dlg.send_message(win32defines.WM_CLOSE)
def test_friendly_class_name(self):
"""Make sure the friendly class name is set correctly (StatusBar)"""
self.assertEqual(self.ctrl.friendly_class_name(), "StatusBar")
def test_texts(self):
"""Make sure the texts are set correctly"""
self.assertEqual(self.ctrl.texts()[1:], self.texts)
def testGetProperties(self):
"""Test getting the properties for the status bar control"""
props = self.ctrl.get_properties()
self.assertEqual(
self.ctrl.friendly_class_name(), props['friendly_class_name'])
self.assertEqual(
self.ctrl.texts(), props['texts'])
for prop_name in props:
self.assertEqual(getattr(self.ctrl, prop_name)(), props[prop_name])
def testBorderWidths(self):
"""Make sure the border widths are retrieved correctly"""
self.assertEqual(
self.ctrl.border_widths(),
dict(
Horizontal=0,
Vertical=2,
Inter=2,
)
)
def testPartCount(self):
"Make sure the number of parts is retrieved correctly"
self.assertEqual(self.ctrl.part_count(), 3)
def testPartRightEdges(self):
"Make sure the part widths are retrieved correctly"
for i in range(0, self.ctrl.part_count() - 1):
self.assertEqual(self.ctrl.part_right_edges()[i], self.part_rects[i].right)
self.assertEqual(self.ctrl.part_right_edges()[i + 1], -1)
def testGetPartRect(self):
"Make sure the part rectangles are retrieved correctly"
for i in range(0, self.ctrl.part_count()):
part_rect = self.ctrl.get_part_rect(i)
self.assertEqual(part_rect.left, self.part_rects[i].left)
if i != self.ctrl.part_count() - 1:
self.assertEqual(part_rect.right, self.part_rects[i].right)
self.assertEqual(part_rect.top, self.part_rects[i].top)
self.assertFalse(abs(part_rect.bottom - self.part_rects[i].bottom) > 2)
self.assertRaises(IndexError, self.ctrl.get_part_rect, 99)
def testClientRects(self):
self.assertEqual(self.ctrl.client_rect(), self.ctrl.client_rects()[0])
client_rects = self.ctrl.client_rects()[1:]
for i, client_rect in enumerate(client_rects):
self.assertEqual(self.part_rects[i].left, client_rect.left)
if i != len(client_rects) - 1:
self.assertEqual(self.part_rects[i].right, client_rect.right)
self.assertEqual(self.part_rects[i].top, client_rect.top)
self.assertFalse(abs(self.part_rects[i].bottom - client_rect.bottom) > 2)
def testGetPartText(self):
self.assertRaises(IndexError, self.ctrl.get_part_text, 99)
for i, text in enumerate(self.texts):
self.assertEqual(text, self.ctrl.get_part_text(i))
class TabControlTestCases(unittest.TestCase):
"""Unit tests for the TreeViewWrapper class"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.fast()
self.screen_w = win32api.GetSystemMetrics(0)
app = Application()
app.start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe"))
self.texts = [
u"CTreeCtrl", u"CAnimateCtrl", u"CToolBarCtrl",
u"CDateTimeCtrl", u"CMonthCalCtrl"]
self.rects = [
RECT(2, 2, 58, 20),
RECT(58, 2, 130, 20),
RECT(130, 2, 201, 20),
RECT(201, 2, 281, 20),
RECT(281, 2, 360, 20)
]
self.app = app
self.dlg = app.CommonControlsSample
self.ctrl = app.CommonControlsSample.TabControl.find()
def tearDown(self):
"""Close the application after tests"""
# close the application
self.dlg.send_message(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"""Make sure the friendly class is set correctly (TabControl)"""
self.assertEqual(self.ctrl.friendly_class_name(), "TabControl")
def testTexts(self):
"""Make sure the texts are set correctly"""
self.assertEqual(self.ctrl.texts()[1:], self.texts)
def testGetProperties(self):
"""Test getting the properties for the tabcontrol"""
props = self.ctrl.get_properties()
self.assertEqual(
self.ctrl.friendly_class_name(), props['friendly_class_name'])
self.assertEqual(
self.ctrl.texts(), props['texts'])
for prop_name in props:
self.assertEqual(getattr(self.ctrl, prop_name)(), props[prop_name])
def testRowCount(self):
self.assertEqual(1, self.ctrl.row_count())
dlgClientRect = self.ctrl.parent().rectangle() # use the parent as a reference
prev_rect = self.ctrl.rectangle() - dlgClientRect
# squeeze the tab control to force two rows
new_rect = RECT(prev_rect)
new_rect.right = int(new_rect.width() / 2)
self.ctrl.move_window(
new_rect.left,
new_rect.top,
new_rect.width(),
new_rect.height(),
)
time.sleep(0.1)
# verify two tab rows
self.assertEqual(2, self.ctrl.row_count())
# restore back the original size of the control
self.ctrl.move_window(prev_rect)
self.assertEqual(1, self.ctrl.row_count())
def testGetSelectedTab(self):
self.assertEqual(0, self.ctrl.get_selected_tab())
self.ctrl.select(1)
self.assertEqual(1, self.ctrl.get_selected_tab())
self.ctrl.select(u"CMonthCalCtrl")
self.assertEqual(4, self.ctrl.get_selected_tab())
def testTabCount(self):
"""Make sure the number of parts is retrieved correctly"""
self.assertEqual(self.ctrl.tab_count(), 5)
def testGetTabRect(self):
"""Make sure the part rectangles are retrieved correctly"""
for i, _ in enumerate(self.rects):
self.assertEqual(self.ctrl.get_tab_rect(i), self.rects[i])
self.assertRaises(IndexError, self.ctrl.get_tab_rect, 99)
# def testGetTabState(self):
# self.assertRaises(IndexError, self.ctrl.GetTabState, 99)
#
# self.dlg.StatementEdit.SetEditText ("MSG (TCM_HIGHLIGHTITEM,1,MAKELONG(TRUE,0))")
#
# time.sleep(.3)
# # use CloseClick to allow the control time to respond to the message
# self.dlg.Send.CloseClick()
# time.sleep(2)
# print("==\n",self.ctrl.TabStates())
#
# self.assertEqual(self.ctrl.GetTabState(1), 1)
#
# def testTabStates(self):
# print(self.ctrl.TabStates())
# raise "tabstates hiay"
def testGetTabText(self):
for i, text in enumerate(self.texts):
self.assertEqual(text, self.ctrl.get_tab_text(i))
self.assertRaises(IndexError, self.ctrl.get_tab_text, 99)
def testClientRects(self):
self.assertEqual(self.ctrl.client_rect(), self.ctrl.client_rects()[0])
self.assertEqual(self.rects, self.ctrl.client_rects()[1:])
def testSelect(self):
self.assertEqual(0, self.ctrl.get_selected_tab())
self.ctrl.select(1)
self.assertEqual(1, self.ctrl.get_selected_tab())
self.ctrl.select(u"CToolBarCtrl")
self.assertEqual(2, self.ctrl.get_selected_tab())
self.assertRaises(IndexError, self.ctrl.select, 99)
class ToolbarTestCases(unittest.TestCase):
"""Unit tests for the ToolbarWrapper class"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.fast()
app = Application()
app.start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe"))
self.app = app
self.dlg = app.CommonControlsSample
# select a tab with toolbar controls
self.dlg.SysTabControl.select(u"CToolBarCtrl")
# see identifiers available at that tab
#self.dlg.PrintControlIdentifiers()
# The sample app has two toolbars. The first toolbar can be
# addressed as Toolbar, Toolbar0 and Toolbar1.
# The second control goes as Toolbar2
self.ctrl = app.CommonControlsSample.ToolbarNew.find()
self.ctrl2 = app.CommonControlsSample.ToolbarErase.find()
def tearDown(self):
"""Close the application after tests"""
# close the application
self.dlg.send_message(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"""Make sure the friendly class is set correctly (Toolbar)"""
self.assertEqual(self.ctrl.friendly_class_name(), "Toolbar")
def testTexts(self):
"""Make sure the texts are set correctly"""
for txt in self.ctrl.texts():
self.assertEqual(isinstance(txt, six.string_types), True)
def testGetProperties(self):
"""Test getting the properties for the toolbar control"""
props = self.ctrl.get_properties()
self.assertEqual(
self.ctrl.friendly_class_name(), props['friendly_class_name'])
self.assertEqual(
self.ctrl.texts(), props['texts'])
self.assertEqual(
self.ctrl.button_count(), props['button_count'])
for prop_name in props:
self.assertEqual(getattr(self.ctrl, prop_name)(), props[prop_name])
def testButtonCount(self):
"""Test the button count method of the toolbar"""
# TODO: for a some reason the first toolbar returns button count = 12
# The same as in the second toolbar, even though their handles are different.
# Maybe the test app itself has to be fixed too.
#self.assertEqual(self.ctrl.button_count(), 9)
self.assertEqual(self.ctrl2.button_count(), 12)
def testGetButton(self):
self.assertRaises(IndexError, self.ctrl.get_button, 29)
def testGetButtonRect(self):
rect_ctrl = self.ctrl.get_button_rect(0)
self.assertEqual((rect_ctrl.left, rect_ctrl.top), (0, 0))
self.assertFalse((rect_ctrl.right - rect_ctrl.left) > 40)
self.assertFalse((rect_ctrl.right - rect_ctrl.left) < 36)
self.assertFalse((rect_ctrl.bottom - rect_ctrl.top) > 38)
self.assertFalse((rect_ctrl.bottom - rect_ctrl.top) < 36)
#self.assertEqual(rect_ctrl, RECT(0, 0, 40, 38))
rect_ctrl2 = self.ctrl2.get_button_rect(0)
self.assertEqual((rect_ctrl2.left, rect_ctrl2.top), (0, 0))
self.assertFalse((rect_ctrl2.right - rect_ctrl2.left) > 70)
self.assertFalse((rect_ctrl2.right - rect_ctrl2.left) < 64)
self.assertFalse((rect_ctrl2.bottom - rect_ctrl2.top) > 38)
self.assertFalse((rect_ctrl2.bottom - rect_ctrl2.top) < 36)
#self.assertEqual(rect_ctrl2, RECT(0, 0, 70, 38))
def testGetToolTipsControls(self):
tips = self.ctrl.get_tool_tips_control()
tt = tips.texts()
self.assertEqual(u"New" in tt, True)
self.assertEqual(u"About" in tt, True)
tips = self.ctrl2.get_tool_tips_control()
tt = tips.texts()
self.assertEqual(u"Pencil" in tt, True)
self.assertEqual(u"Ellipse" in tt, True)
def testPressButton(self):
self.ctrl.press_button(0)
#print(self.ctrl.texts())
self.assertRaises(
findbestmatch.MatchError,
self.ctrl.press_button,
"asdfdasfasdf")
# todo more tests for pressbutton
self.ctrl.press_button(u"Open")
def testCheckButton(self):
self.ctrl2.check_button('Erase', True)
self.assertEqual(self.ctrl2.button('Erase').is_checked(), True)
self.ctrl2.check_button('Pencil', True)
self.assertEqual(self.ctrl2.button('Erase').is_checked(), False)
self.ctrl2.check_button('Erase', False)
self.assertEqual(self.ctrl2.button('Erase').is_checked(), False)
# try to check separator
self.assertRaises(RuntimeError, self.ctrl.check_button, 3, True)
def testIsCheckable(self):
self.assertNotEqual(self.ctrl2.button('Erase').is_checkable(), False)
self.assertEqual(self.ctrl.button('New').is_checkable(), False)
def testIsPressable(self):
self.assertEqual(self.ctrl.button('New').is_pressable(), True)
def testButtonByTooltip(self):
self.assertEqual(self.ctrl.button('New', by_tooltip=True).text(), 'New')
self.assertEqual(self.ctrl.button('About', exact=False, by_tooltip=True).text(), 'About')
class RebarTestCases(unittest.TestCase):
"""Unit tests for the UpDownWrapper class"""
def setUp(self):
"""Start the application, set some data and wait for the state we want
The app title can be tricky. If no document is opened the title is just: "RebarTest"
However if a document is created/opened in the child frame
the title is appended with a document name: "RebarTest - RebarTest1"
A findbestmatch proc does well here with guessing the title
even though the app is started with a short title "RebarTest".
"""
Timings.fast()
app = Application()
app.start(os.path.join(mfc_samples_folder, "RebarTest.exe"))
mouse.move((-500, 200)) # remove the mouse from the screen to avoid side effects
self.app = app
self.dlg = app.RebarTest_RebarTest
self.dlg.wait('ready', 20)
self.ctrl = app.RebarTest_RebarTest.Rebar.find()
def tearDown(self):
"""Close the application after tests"""
self.app.kill(soft=True)
def testFriendlyClass(self):
"""Make sure the friendly class is set correctly (ReBar)"""
self.assertEqual(self.ctrl.friendly_class_name(), "ReBar")
def testTexts(self):
"""Make sure the texts are set correctly"""
for txt in self.ctrl.texts():
self.assertEqual(isinstance(txt, six.string_types), True)
def testBandCount(self):
"""Make sure band_count() returns 2"""
self.assertEqual(self.ctrl.band_count(), 2)
def testGetBand(self):
"""Check that get_band() is working corectly"""
self.assertRaises(IndexError, self.ctrl.get_band, 99)
self.assertRaises(IndexError, self.ctrl.get_band, 2)
band = self.ctrl.get_band(0)
self.assertEqual(band.hwndChild, self.dlg.MenuBar.handle)
self.assertEqual(self.ctrl.get_band(1).text, u"Tools band:")
self.assertEqual(self.ctrl.get_band(0).text, u"Menus band:")
def testGetToolTipsControl(self):
"""Make sure GetToolTipsControl() returns None"""
self.assertEqual(self.ctrl.get_tool_tips_control(), None)
def testAfxToolBarButtons(self):
"""Make sure we can click on Afx ToolBar button by index"""
Timings.closeclick_dialog_close_wait = 2.
self.dlg.StandardToolbar.button(1).click()
self.app.window(name='Open').wait('ready', timeout=30)
self.app.window(name='Open').Cancel.close_click()
def testMenuBarClickInput(self):
"""Make sure we can click on Menu Bar items by indexed path"""
self.assertRaises(TypeError, self.dlg.MenuBar.menu_bar_click_input, '#one->#0', self.app)
self.dlg.MenuBar.menu_bar_click_input('#1->#0->#0', self.app)
self.app.Customize.CloseButton.click()
self.app.Customize.wait_not('visible')
self.dlg.MenuBar.menu_bar_click_input([2, 0], self.app)
self.app.window(name='About RebarTest').OK.click()
self.app.window(name='About RebarTest').wait_not('visible')
class DatetimeTestCases(unittest.TestCase):
"""Unit tests for the DateTimePicker class"""
def setUp(self):
"""Start the application and get 'Date Time Picker' control"""
Timings.fast()
app = Application()
app.start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe"))
self.app = app
self.dlg = app.CommonControlsSample
self.dlg.wait('ready', 20)
tab = app.CommonControlsSample.TabControl.find()
tab.select(3)
self.ctrl = self.dlg.DateTimePicker
def tearDown(self):
"""Close the application after tests"""
# close the application
self.dlg.send_message(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"""Make sure the friendly class is set correctly (DateTimePicker)"""
self.assertEqual(self.ctrl.friendly_class_name(), "DateTimePicker")
def testGetTime(self):
"""Test reading a date from a 'Date Time Picker' control"""
# No check for seconds and milliseconds as it can slip
# These values are verified in the next 'testSetTime'
test_date_time = self.ctrl.get_time()
date_time_now = datetime.now()
self.assertEqual(test_date_time.wYear, date_time_now.year)
self.assertEqual(test_date_time.wMonth, date_time_now.month)
self.assertEqual(test_date_time.wDay, date_time_now.day)
self.assertEqual(test_date_time.wHour, date_time_now.hour)
self.assertEqual(test_date_time.wMinute, date_time_now.minute)
def testSetTime(self):
"""Test setting a date to a 'Date Time Picker' control"""
year = 2025
month = 9
day_of_week = 5
day = 19
hour = 1
minute = 2
second = 3
milliseconds = 781
self.ctrl.set_time(
year=year,
month=month,
day_of_week=day_of_week,
day=day,
hour=hour,
minute=minute,
second=second,
milliseconds=milliseconds
)
# Retrive back the values we set
test_date_time = self.ctrl.get_time()
self.assertEqual(test_date_time.wYear, year)
self.assertEqual(test_date_time.wMonth, month)
self.assertEqual(test_date_time.wDay, day)
self.assertEqual(test_date_time.wDayOfWeek, day_of_week)
self.assertEqual(test_date_time.wHour, hour)
self.assertEqual(test_date_time.wMinute, minute)
self.assertEqual(test_date_time.wSecond, second)
self.assertEqual(test_date_time.wMilliseconds, milliseconds)
class ToolTipsTestCases(unittest.TestCase):
"""Unit tests for the tooltips class"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.fast()
self.texts = [u'', u'New', u'Open', u'Save', u'Cut', u'Copy', u'Paste', u'Print', u'About', u'Help']
app = Application()
app.start(os.path.join(mfc_samples_folder, "CmnCtrl1.exe"))
#app.start_(os.path.join(controlspy_folder, "Tooltip.exe"))
self.app = app
self.dlg = app.Common_Controls_Sample
# Make sure the mouse doesn't hover over tested controls
# so it won't generate an unexpected tooltip
self.dlg.move_mouse_input(coords=(-100, -100), absolute=True)
self.dlg.TabControl.select(u'CToolBarCtrl')
self.ctrl = self.dlg.Toolbar.get_tool_tips_control()
def tearDown(self):
"""Close the application after tests"""
# close the application
self.app.kill()
def testFriendlyClass(self):
"""Make sure the friendly class is set correctly (ToolTips)"""
self.assertEqual(self.ctrl.friendly_class_name(), "ToolTips")
def testGetProperties(self):
"""Test getting the properties for the tooltips control"""
props = self.ctrl.get_properties()
self.assertEqual(
self.ctrl.friendly_class_name(), props['friendly_class_name'])
self.assertEqual(
self.ctrl.texts(), props['texts'])
for prop_name in props:
self.assertEqual(getattr(self.ctrl, prop_name)(), props[prop_name])
def test_get_tip(self):
"""Test that get_tip() returns correct ToolTip object"""
self.assertRaises(IndexError, self.ctrl.get_tip, 99)
tip = self.ctrl.get_tip(1)
self.assertEqual(tip.text, self.texts[1])
def test_tool_count(self):
"""Test that tool_count() returns correct value"""
self.assertEqual(10, self.ctrl.tool_count())
def test_get_tip_text(self):
"""Test that get_tip_text() returns correct text"""
self.assertEqual(self.texts[1], self.ctrl.get_tip_text(1))
def test_texts(self):
"""Make sure the texts are set correctly"""
# just to make sure a tooltip is not shown
self.dlg.move_mouse_input(coords=(0, 0), absolute=False)
ActionLogger().log('ToolTips texts = ' + ';'.join(self.ctrl.texts()))
self.assertEqual(self.ctrl.texts()[0], '')
self.assertEqual(self.ctrl.texts()[1:], self.texts)
class UpDownTestCases(unittest.TestCase):
"""Unit tests for the UpDownWrapper class"""
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
Timings.fast()
app = Application()
app.start(os.path.join(controlspy_folder, "Up-Down.exe"))
self.app = app
self.dlg = app.MicrosoftControlSpy
self.ctrl = app.MicrosoftControlSpy.UpDown2.find()
def tearDown(self):
"""Close the application after tests"""
# close the application
self.dlg.send_message(win32defines.WM_CLOSE)
def testFriendlyClass(self):
"""Make sure the friendly class is set correctly (UpDown)"""
self.assertEqual(self.ctrl.friendly_class_name(), "UpDown")
def testTexts(self):
"""Make sure the texts are set correctly"""
self.assertEqual(self.ctrl.texts()[1:], [])
def testGetProperties(self):
"""Test getting the properties for the updown control"""
props = self.ctrl.get_properties()
self.assertEqual(
self.ctrl.friendly_class_name(), props['friendly_class_name'])
self.assertEqual(
self.ctrl.texts(), props['texts'])
for prop_name in props:
self.assertEqual(getattr(self.ctrl, prop_name)(), props[prop_name])
def testGetValue(self):
"""Test getting up-down position"""
self.assertEqual(self.ctrl.get_value(), 0)
self.ctrl.set_value(23)
self.assertEqual(self.ctrl.get_value(), 23)
def testSetValue(self):
"""Test setting up-down position"""
self.assertEqual(self.ctrl.get_value(), 0)
self.ctrl.set_value(23)
self.assertEqual(self.ctrl.get_value(), 23)
self.assertEqual(
int(self.ctrl.get_buddy_control().texts()[1]),
23)
def testGetBase(self):
"""Test getting the base of the up-down control"""
self.assertEqual(self.ctrl.get_base(), 10)
#self.dlg.StatementEdit.SetEditText ("MSG (UDM_SETBASE, 16, 0)")
# use CloseClick to allow the control time to respond to the message
#self.dlg.Send.click_input()
self.ctrl.set_base(16)
self.assertEqual(self.ctrl.get_base(), 16)
def testGetRange(self):
"""Test getting the range of the up-down control"""
self.assertEqual((0, 9999), self.ctrl.get_range())
def testGetBuddy(self):
"""Test getting the buddy control"""
self.assertEqual(self.ctrl.get_buddy_control().handle, self.dlg.Edit6.handle)
def testIncrement(self):
"""Test incremementing up-down position"""
Timings.defaults()
self.ctrl.increment()
self.assertEqual(self.ctrl.get_value(), 1)
def testDecrement(self):
"""Test decrementing up-down position"""
Timings.defaults()
self.ctrl.set_value(23)
self.ctrl.decrement()
self.assertEqual(self.ctrl.get_value(), 22)
class TrackbarWrapperTestCases(unittest.TestCase):
def setUp(self):
"""Set some data and ensure the application is in the state we want"""
app = Application()
app.start(os.path.join(mfc_samples_folder, u"CmnCtrl2.exe"))
dlg = app.top_window()
dlg.TabControl.select(1)
ctrl = dlg.Trackbar.find()
self.app = app
self.dlg = dlg
self.ctrl = ctrl
def tearDown(self):
"""Close the application after tests"""
# close the application
self.dlg.send_message(win32defines.WM_CLOSE)
def test_friendly_class(self):
"""Make sure the Trackbar friendly class is set correctly"""
self.assertEqual(self.ctrl.friendly_class_name(), u"Trackbar")
def test_get_range_max(self):
"""Test the get_range_max method"""
self.ctrl.set_range_max(100)
self.assertEqual(self.ctrl.get_range_max(), 100)
def test_get_range_min(self):
"""Test the get_range_min method"""
self.ctrl.set_range_min(25)
self.assertEqual(self.ctrl.get_range_min(), 25)
def test_set_range_min_more_then_range_max(self):
"""Test the set_range_min method with error"""
self.assertRaises(ValueError, self.ctrl.set_range_min, self.ctrl.get_range_max() + 1)
def test_set_position_more_than_max_range(self):
"""Test the set_position method with error"""
self.ctrl.set_range_max(100)
self.assertRaises(ValueError, self.ctrl.set_position, 110)
def test_set_position_less_than_min_range(self):
"""Test the set_position method with error"""
self.assertRaises(ValueError, self.ctrl.set_position, self.ctrl.get_range_min() - 10)
def test_set_correct_position(self):
"""Test the set_position method"""
self.ctrl.set_position(23)
self.assertEqual(self.ctrl.get_position(), 23)
def test_get_num_ticks(self):
"""Test the get_num_ticks method"""
self.assertEqual(self.ctrl.get_num_ticks(), 6)
def test_get_channel_rect(self):
"""Test the get_channel_rect method"""
system_rect = RECT()
system_rect.left = 8
system_rect.top = 19
system_rect.right = 249
system_rect.bottom = 23
self.assert_channel_rect(self.ctrl.get_channel_rect(), system_rect)
def assert_channel_rect(self, first_rect, second_rect):
"""Compare two rect structures"""
self.assertEqual(first_rect.height(), second_rect.height())
self.assertEqual(first_rect.width(), second_rect.width())
def test_get_line_size(self):
"""Test the get_line_size method"""
self.ctrl.set_line_size(10)
self.assertEqual(self.ctrl.get_line_size(), 10)
def test_get_page_size(self):
"""Test the set_page_size method"""
self.ctrl.set_page_size(14)
self.assertEqual(self.ctrl.get_page_size(), 14)
def test_get_tool_tips_control(self):
"""Test the get_tooltips_control method"""
self.assertRaises(RuntimeError, self.ctrl.get_tooltips_control)
def test_set_sel(self):
"""Test the set_sel method"""
self.assertRaises(RuntimeError, self.ctrl.set_sel, 22, 55)
def test_get_sel_start(self):
"""Test the get_sel_start method"""
self.assertRaises(RuntimeError, self.ctrl.get_sel_start)
def test_get_sel_end(self):
"""Test the get_sel_end method"""
self.assertRaises(RuntimeError, self.ctrl.get_sel_end)
if __name__ == "__main__":
unittest.main()
|
19b6552fb2cc373ce7dac36f3ed31c68a511b55a
|
f27e3fdc97290b1db6d3fa7039ad59e4f8b5a760
|
/keras/comet-keras-optimizer.py
|
a0fc1d3834c5d33eae20a62e35f9a8e53ad032dd
|
[] |
no_license
|
comet-ml/comet-examples
|
9c7bcea8b97986fb7987cbe0f4533f619e2a0939
|
9da5d4f296e633bb7e63b47dc2d3f7a0780c0a4e
|
refs/heads/master
| 2023-08-19T03:32:51.864273
| 2023-08-09T09:30:34
| 2023-08-09T09:30:34
| 158,587,515
| 134
| 55
| null | 2023-09-13T16:58:41
| 2018-11-21T18:00:34
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 3,182
|
py
|
comet-keras-optimizer.py
|
# -*- coding: utf-8 -*-
# *******************************************************
# ____ _ _
# / ___|___ _ __ ___ ___| |_ _ __ ___ | |
# | | / _ \| '_ ` _ \ / _ \ __| | '_ ` _ \| |
# | |__| (_) | | | | | | __/ |_ _| | | | | | |
# \____\___/|_| |_| |_|\___|\__(_)_| |_| |_|_|
#
# Sign up for free at http://www.comet.ml
# Copyright (C) 2019 Comet ML INC
# This file can not be copied and/or distributed without
# the express permission of Comet ML Inc.
# *******************************************************
"""
Trains a simple deep NN on the MNIST dataset.
Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
"""
from __future__ import print_function
from os.path import dirname, join
from comet_ml import Optimizer # isort:skip
import keras
from keras.datasets import mnist
from keras.layers import Dense
from keras.models import Sequential
from keras.optimizers import RMSprop
def main():
num_classes = 10
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")
x_train /= 255
x_test /= 255
print(x_train.shape[0], "train samples")
print(x_test.shape[0], "test samples")
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
config = {
"algorithm": "bayes",
"name": "Optimize MNIST Network",
"spec": {"maxCombo": 10, "objective": "minimize", "metric": "loss"},
"parameters": {"first_layer_units": {"type": "integer", "min": 1, "max": 1000}},
"trials": 1,
}
opt = Optimizer(config)
for experiment in opt.get_experiments():
flu = experiment.get_parameter("first_layer_units")
score = fit(experiment, x_train, y_train, x_test, y_test, 3, 120, flu)
print("test loss, test acc:", score)
def build_model_graph(first_layer_units):
model = Sequential()
model.add(Dense(first_layer_units, activation="sigmoid", input_shape=(784,)))
model.add(Dense(128, activation="sigmoid"))
model.add(Dense(128, activation="sigmoid"))
model.add(Dense(10, activation="softmax"))
model.compile(
loss="categorical_crossentropy", optimizer=RMSprop(), metrics=["accuracy"]
)
return model
def fit(
experiment, x_train, y_train, x_test, y_test, epoch, batch_size, first_layer_units
):
current_dir = dirname(__file__)
experiment.log_dataset_hash(x_train)
experiment.log_parameter("first_layer_units", first_layer_units)
# Define model
model = build_model_graph(first_layer_units)
model.fit(
x_train,
y_train,
batch_size=batch_size,
epochs=epoch,
validation_data=(x_test, y_test),
)
score = model.evaluate(x_test, y_test, verbose=0)
return score
if __name__ == "__main__":
main()
|
15d80433efc7e3c73c7dc1616f4b12fd5f6c85cc
|
10582263a62298203ddc5cd0c0130dd70046aa76
|
/tffm/utils.py
|
5aa3ed135c408f6f45b21c9713e94e0bed5b28a3
|
[
"MIT"
] |
permissive
|
geffy/tffm
|
21faafde14b1cbb8714ddf28d3faaa54e27b478c
|
7bfe63e35e4a6264e095ae21882e9ceec3436f19
|
refs/heads/master
| 2022-07-28T03:34:26.416960
| 2022-01-17T20:38:58
| 2022-01-17T20:38:58
| 57,906,189
| 853
| 205
|
MIT
| 2020-05-22T21:40:58
| 2016-05-02T17:06:07
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 6,836
|
py
|
utils.py
|
"""Supporting functions for arbitrary order Factorization Machines."""
import math
import numpy as np
import tensorflow as tf
import itertools
from itertools import combinations_with_replacement, takewhile, count
from collections import defaultdict
def get_shorter_decompositions(basic_decomposition):
"""Returns all arrays simpler than basic_decomposition.
Returns all arrays that can be constructed from basic_decomposition
via joining (summing) its elements.
Parameters
----------
basic_decomposition : list or np.array
The array from which to build subsequent ones.
Returns
-------
decompositions : list of tuples
All possible arrays that can be constructed from basic_decomposition.
counts : np.array
counts[i] equals to the number of ways to build decompositions[i] from
basic_decomposition.
Example
-------
decompositions, counts = get_shorter_decompositions([1, 2, 3])
decompositions == [(1, 5), (2, 4), (3, 3), (6,)]
counts == [ 2., 1., 1., 2.]
"""
order = int(np.sum(basic_decomposition))
decompositions = []
variations = defaultdict(lambda: [])
for curr_len in range(1, len(basic_decomposition)):
for sum_rule in combinations_with_replacement(range(curr_len), order):
sum_rule = np.array(sum_rule)
curr_pows = np.array([np.sum(sum_rule == i) for i in range(curr_len)])
curr_pows = curr_pows[curr_pows != 0]
sorted_pow = tuple(np.sort(curr_pows))
variations[sorted_pow].append(tuple(curr_pows))
decompositions.append(sorted_pow)
if len(decompositions) > 1:
decompositions = np.unique(decompositions)
counts = np.zeros(decompositions.shape[0])
for i, dec in enumerate(decompositions):
counts[i] = len(np.unique(variations[dec]))
else:
counts = np.ones(1)
return decompositions, counts
def sort_topologically(children_by_node, node_list):
"""Topological sort of a graph.
Parameters
----------
children_by_node : dict
Children for any node.
node_list : list
All nodes (some nodes may not have children and thus a separate
parameter is needed).
Returns
-------
list, nodes in the topological order
"""
levels_by_node = {}
nodes_by_level = defaultdict(set)
def walk_depth_first(node):
if node in levels_by_node:
return levels_by_node[node]
children = children_by_node[node]
level = 0 if not children else (1 + max(walk_depth_first(lname) for lname, _ in children))
levels_by_node[node] = level
nodes_by_level[level].add(node)
return level
for node in node_list:
walk_depth_first(node)
nodes_by_level = list(takewhile(lambda x: x != [],
(list(nodes_by_level[i]) for i in count())))
return list(itertools.chain.from_iterable(nodes_by_level))
def initial_coefficient(decomposition):
"""Compute initial coefficient of the decomposition."""
order = np.sum(decomposition)
coef = math.factorial(order)
coef /= np.prod([math.factorial(x) for x in decomposition])
_, counts = np.unique(decomposition, return_counts=True)
coef /= np.prod([math.factorial(c) for c in counts])
return coef
def powers_and_coefs(order):
"""For a `order`-way FM returns the powers and their coefficients needed to
compute model equation efficiently
"""
decompositions, _ = get_shorter_decompositions(np.ones(order))
graph = defaultdict(lambda: list())
graph_reversed = defaultdict(lambda: list())
for dec in decompositions:
parents, weights = get_shorter_decompositions(dec)
for i in range(len(parents)):
graph[parents[i]].append((dec, weights[i]))
graph_reversed[dec].append((parents[i], weights[i]))
topo_order = sort_topologically(graph, decompositions)
final_coefs = defaultdict(lambda: 0)
for node in topo_order:
final_coefs[node] += initial_coefficient(node)
for p, w in graph_reversed[node]:
final_coefs[p] -= w * final_coefs[node]
powers_and_coefs_list = []
# for dec, c in final_coefs.iteritems():
for dec, c in final_coefs.items():
in_pows, out_pows = np.unique(dec, return_counts=True)
powers_and_coefs_list.append((in_pows, out_pows, c))
return powers_and_coefs_list
def matmul_wrapper(A, B, optype):
"""Wrapper for handling sparse and dense versions of `tf.matmul` operation.
Parameters
----------
A : tf.Tensor
B : tf.Tensor
optype : str, {'dense', 'sparse'}
Returns
-------
tf.Tensor
"""
with tf.name_scope('matmul_wrapper') as scope:
if optype == 'dense':
return tf.matmul(A, B)
elif optype == 'sparse':
return tf.sparse_tensor_dense_matmul(A, B)
else:
raise NameError('Unknown input type in matmul_wrapper')
def pow_wrapper(X, p, optype):
"""Wrapper for handling sparse and dense versions of `tf.pow` operation.
Parameters
----------
X : tf.Tensor
p : int
optype : str, {'dense', 'sparse'}
Returns
-------
tf.Tensor
"""
with tf.name_scope('pow_wrapper') as scope:
if optype == 'dense':
return tf.pow(X, p)
elif optype == 'sparse':
return tf.SparseTensor(X.indices, tf.pow(X.values, p), X.dense_shape)
else:
raise NameError('Unknown input type in pow_wrapper')
def count_nonzero_wrapper(X, optype):
"""Wrapper for handling sparse and dense versions of `tf.count_nonzero`.
Parameters
----------
X : tf.Tensor (N, K)
optype : str, {'dense', 'sparse'}
Returns
-------
tf.Tensor (1,K)
"""
with tf.name_scope('count_nonzero_wrapper') as scope:
if optype == 'dense':
return tf.count_nonzero(X, axis=0, keep_dims=True)
elif optype == 'sparse':
indicator_X = tf.SparseTensor(X.indices, tf.ones_like(X.values), X.dense_shape)
return tf.sparse_reduce_sum(indicator_X, axis=0, keep_dims=True)
else:
raise NameError('Unknown input type in count_nonzero_wrapper')
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# Predefined loss functions
# Should take 2 tf.Ops: outputs, targets and should return tf.Op of element-wise losses
# Be careful about dimensionality -- maybe tf.transpose(outputs) is needed
def loss_logistic(outputs, y):
margins = -y * tf.transpose(outputs)
raw_loss = tf.log(tf.add(1.0, tf.exp(margins)))
return tf.minimum(raw_loss, 100, name='truncated_log_loss')
def loss_mse(outputs, y):
return tf.pow(y - tf.transpose(outputs), 2, name='mse_loss')
|
0ea1c74760a3e4118a61b4cd7f8cb0d2531c7130
|
0337ca93de2a0c53eb36f5e2aa133ac76297731c
|
/data/lib/http_emitter.py
|
eb7dcb808d4e5b90bc24649761549c0614860267
|
[] |
no_license
|
drivy/jobs
|
2589b9b26c115ac3b5671e319acdc403c9ed0a35
|
3333e75f70c50b60b678cba2259cb1d745df85d7
|
refs/heads/master
| 2022-03-13T09:15:49.712335
| 2022-03-08T21:50:44
| 2022-03-08T21:50:44
| 31,727,807
| 196
| 155
| null | 2022-03-14T16:45:58
| 2015-03-05T18:00:23
|
Ruby
|
UTF-8
|
Python
| false
| false
| 417
|
py
|
http_emitter.py
|
import itertools
import requests
import uuid
import lib.log_generator as log_generator
ENDPOINT = "http://127.0.0.1:3000"
for i in range(1000):
try:
requests.post(ENDPOINT,json={
'log': log_generator.sample(uuid.uuid4())
}, timeout=0.1)
except requests.Timeout:
print(f'Remote server timed-out on {ENDPOINT}')
except requests.ConnectionError:
print(f'Connection refused on {ENDPOINT}')
|
23f95cb5fdb969dc733472932fb0629db879d8e7
|
d965f13bdb6e89d0da17acc1b9d6fbbb09fe29ae
|
/app/src/CLEAN/losses.py
|
c9491603a75495ead28eb531bc0b39447de2c86e
|
[] |
permissive
|
tttianhao/CLEAN
|
48fa6622823e1ba0bb7b6e3f98fcdee1098b78e1
|
cfc1a888bdb8fb2f38fc677437c8ee2a98c6775f
|
refs/heads/main
| 2023-07-25T10:19:45.687408
| 2023-07-22T08:47:37
| 2023-07-22T08:47:37
| 525,112,894
| 129
| 24
|
MIT
| 2023-06-01T22:08:32
| 2022-08-15T19:27:51
|
Python
|
UTF-8
|
Python
| false
| false
| 1,502
|
py
|
losses.py
|
import torch
import torch.nn.functional as F
def SupConHardLoss(model_emb, temp, n_pos):
'''
return the SupCon-Hard loss
features:
model output embedding, dimension [bsz, n_all, out_dim],
where bsz is batchsize,
n_all is anchor, pos, neg (n_all = 1 + n_pos + n_neg)
and out_dim is embedding dimension
temp:
temperature
n_pos:
number of positive examples per anchor
'''
# l2 normalize every embedding
features = F.normalize(model_emb, dim=-1, p=2)
# features_T is [bsz, outdim, n_all], for performing batch dot product
features_T = torch.transpose(features, 1, 2)
# anchor is the first embedding
anchor = features[:, 0]
# anchor is the first embedding
anchor_dot_features = torch.bmm(anchor.unsqueeze(1), features_T)/temp
# anchor_dot_features now [bsz, n_all], contains
anchor_dot_features = anchor_dot_features.squeeze(1)
# deduct by max logits, which will be 1/temp since features are L2 normalized
logits = anchor_dot_features - 1/temp
# the exp(z_i dot z_a) excludes the dot product between itself
# exp_logits is of size [bsz, n_pos+n_neg]
exp_logits = torch.exp(logits[:, 1:])
exp_logits_sum = n_pos * torch.log(exp_logits.sum(1)) # size [bsz], scale by n_pos
pos_logits_sum = logits[:, 1:n_pos+1].sum(1) #sum over all (anchor dot pos)
log_prob = (pos_logits_sum - exp_logits_sum)/n_pos
loss = - log_prob.mean()
return loss
|
ebe30efa756282172e9ce8e2fa2c4f339dace425
|
c4a2ae65c06d53466e9db29430c5048ad9988c94
|
/muddery/server/quests/base_quest_status.py
|
8be0ce82eb003d2e3590dbbceaafd7a3b0ffc623
|
[
"BSD-3-Clause"
] |
permissive
|
muddery/muddery
|
ac5a0dcb16b034844d91360e8154c70daca4c9d0
|
5fa06b29bf800646dc4da5851fdf7a1f299f15a7
|
refs/heads/master
| 2023-03-08T22:01:09.434955
| 2023-01-20T14:06:14
| 2023-01-20T14:06:14
| 33,435,868
| 139
| 64
|
NOASSERTION
| 2022-11-05T14:45:11
| 2015-04-05T09:07:47
|
Python
|
UTF-8
|
Python
| false
| false
| 269
|
py
|
base_quest_status.py
|
"""
Quest dependency's base class.
"""
class BaseQuestStatus(object):
"""
Quest status's base class.
"""
key = ""
name = ""
def match(self, caller, quest_key):
"""
If the quest matches status.
"""
return True
|
4978fcc1b275b1973c5397d3fe2a5d68f0796152
|
8bf388105cb28af02b321849ff5302f0e6fa563d
|
/testapp/conftest.py
|
55a57bf10c34d9e85fa23a460850ed79011ca797
|
[
"MIT"
] |
permissive
|
jrief/django-admin-sortable2
|
b3254015dbc5bc79df5fc1f16eeb9a9c09a9d4d6
|
b7169c5084ae9fd8dfae21fcc628129657213778
|
refs/heads/master
| 2023-08-27T08:17:30.285827
| 2023-08-01T06:27:53
| 2023-08-01T06:27:53
| 11,240,449
| 636
| 197
|
MIT
| 2023-08-26T16:59:47
| 2013-07-07T21:26:56
|
Python
|
UTF-8
|
Python
| false
| false
| 372
|
py
|
conftest.py
|
import os
import pytest
os.environ.setdefault('DJANGO_ALLOW_ASYNC_UNSAFE', 'true')
@pytest.fixture(scope='function')
def django_db_setup(django_db_blocker):
from django.core.management import call_command
with django_db_blocker.unblock():
call_command('migrate', verbosity=0)
call_command('loaddata', 'testapp/fixtures/data.json', verbosity=0)
|
0a2dbd560c03bd016a951acad72bdf7609982ca5
|
37ba914737fba69b3a656ab0a9fcdbc45d113f70
|
/library/panos_gre_tunnel.py
|
901caef8d860228f32f9653cf76b8cfc428fe242
|
[
"Apache-2.0"
] |
permissive
|
PaloAltoNetworks/ansible-pan
|
1a30def492393cb540d346b04dc5e7e0f217791c
|
dce32f6d1837dafb59f431e32d954c108c291a9a
|
refs/heads/develop
| 2023-06-23T13:30:26.444014
| 2023-06-14T13:13:14
| 2023-06-14T13:13:14
| 29,692,434
| 236
| 202
|
NOASSERTION
| 2023-06-14T13:13:10
| 2015-01-22T18:07:22
|
Python
|
UTF-8
|
Python
| false
| false
| 5,981
|
py
|
panos_gre_tunnel.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020 Palo Alto Networks, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: panos_gre_tunnel
short_description: Create GRE tunnels on PAN-OS devices.
description:
- NOTE: The modules in this role are deprecated in favour of the modules in the collection U(https://paloaltonetworks.github.io/pan-os-ansible)
- Create GRE tunnel objects on PAN-OS devices.
author:
- Garfield Lee Freeman (@shinmog)
version_added: "2.9"
requirements:
- pan-python can be obtained from PyPI U(https://pypi.python.org/pypi/pan-python)
- pandevice can be obtained from PyPI U(https://pypi.python.org/pypi/pandevice)
notes:
- 'Minimum PAN-OS version: 9.0'
- Panorama is supported.
- Check mode is supported.
extends_documentation_fragment:
- panos.transitional_provider
- panos.full_template_support
- panos.state
options:
name:
description:
- Name of object to create.
required: true
interface:
description:
- Interface to terminate the tunnel.
local_address_type:
description:
Type of local address.
choices:
- ip
- floating-ip
default: ip
local_address_value:
description:
- IP address value.
peer_address:
description:
- Peer IP address.
tunnel_interface:
description:
- To apply GRE tunnels to tunnel interface.
ttl:
description:
- TTL.
type: int
default: 64
copy_tos:
description:
- Copy IP TOS bits from inner packet to GRE packet.
type: bool
enable_keep_alive:
description:
- Enable tunnel monitoring.
type: bool
keep_alive_interval:
description:
- Keep alive interval.
type: int
default: 10
keep_alive_retry:
description:
- Keep alive retry time.
type: int
default: 3
keep_alive_hold_timer:
description:
- Keep alive hold timer.
type: int
default: 5
disabled:
description:
- Disable the GRE tunnel.
type: bool
'''
EXAMPLES = '''
- name: Create GRE tunnel
panos_gre_tunnel:
provider: '{{ provider }}'
name: 'myGreTunnel'
interface: 'ethernet1/5'
local_address_value: '10.1.1.1/24'
peer_address: '192.168.1.1'
tunnel_interface: 'tunnel.7'
ttl: 42
'''
RETURN = '''
# Default return values
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.panos.panos import get_connection
try:
from pandevice.network import GreTunnel
from pandevice.errors import PanDeviceError
except ImportError:
pass
def main():
helper = get_connection(
template=True,
template_stack=True,
with_classic_provider_spec=True,
with_state=True,
min_pandevice_version=(0, 13, 0),
min_panos_version=(9, 0, 0),
argument_spec=dict(
name=dict(required=True),
interface=dict(),
local_address_type=dict(default='ip', choices=['ip', 'floating-ip']),
local_address_value=dict(),
peer_address=dict(),
tunnel_interface=dict(),
ttl=dict(type='int', default=64),
copy_tos=dict(type='bool'),
enable_keep_alive=dict(type='bool'),
keep_alive_interval=dict(type='int', default=10),
keep_alive_retry=dict(type='int', default=3),
keep_alive_hold_timer=dict(type='int', default=5),
disabled=dict(type='bool'),
),
)
module = AnsibleModule(
argument_spec=helper.argument_spec,
required_one_of=helper.required_one_of,
supports_check_mode=True,
)
# Verify libs are present, get parent object.
parent = helper.get_pandevice_parent(module)
# Object params.
spec = {
'name': module.params['name'],
'interface': module.params['interface'],
'local_address_type': module.params['local_address_type'],
'local_address_value': module.params['local_address_value'],
'peer_address': module.params['peer_address'],
'tunnel_interface': module.params['tunnel_interface'],
'ttl': module.params['ttl'],
'copy_tos': module.params['copy_tos'],
'enable_keep_alive': module.params['enable_keep_alive'],
'keep_alive_interval': module.params['keep_alive_interval'],
'keep_alive_retry': module.params['keep_alive_retry'],
'keep_alive_hold_timer': module.params['keep_alive_hold_timer'],
'disabled': module.params['disabled'],
}
# Retrieve current info.
try:
listing = GreTunnel.refreshall(parent, add=False)
except PanDeviceError as e:
module.fail_json(msg='Failed refresh: {0}'.format(e))
# Build the object based on the user spec.
obj = GreTunnel(**spec)
parent.add(obj)
# Apply the state.
changed = helper.apply_state(obj, listing, module)
# Done.
module.exit_json(changed=changed)
if __name__ == '__main__':
main()
|
cc536bf4d8dff5079f68df8cc9e524acdcfb3450
|
9ed4d46aedd4d4acadb48d610e940594b5b7b3fd
|
/project_euler/problem_191/sol1.py
|
6bff9d54eeca4360ec324ad5c1b0db84f7ccaa86
|
[
"CC-BY-NC-4.0",
"CC-BY-NC-SA-4.0",
"MIT"
] |
permissive
|
TheAlgorithms/Python
|
7596a0e236ed12a61f9db19a7ea68309779cc85b
|
421ace81edb0d9af3a173f4ca7e66cc900078c1d
|
refs/heads/master
| 2023-09-01T17:32:20.190949
| 2023-08-29T13:18:10
| 2023-08-29T13:18:10
| 63,476,337
| 184,217
| 48,615
|
MIT
| 2023-09-14T02:05:29
| 2016-07-16T09:44:01
|
Python
|
UTF-8
|
Python
| false
| false
| 3,226
|
py
|
sol1.py
|
"""
Prize Strings
Problem 191
A particular school offers cash rewards to children with good attendance and
punctuality. If they are absent for three consecutive days or late on more
than one occasion then they forfeit their prize.
During an n-day period a trinary string is formed for each child consisting
of L's (late), O's (on time), and A's (absent).
Although there are eighty-one trinary strings for a 4-day period that can be
formed, exactly forty-three strings would lead to a prize:
OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA
OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO
AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL
AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA
LAOO LAOA LAAO
How many "prize" strings exist over a 30-day period?
References:
- The original Project Euler project page:
https://projecteuler.net/problem=191
"""
cache: dict[tuple[int, int, int], int] = {}
def _calculate(days: int, absent: int, late: int) -> int:
"""
A small helper function for the recursion, mainly to have
a clean interface for the solution() function below.
It should get called with the number of days (corresponding
to the desired length of the 'prize strings'), and the
initial values for the number of consecutive absent days and
number of total late days.
>>> _calculate(days=4, absent=0, late=0)
43
>>> _calculate(days=30, absent=2, late=0)
0
>>> _calculate(days=30, absent=1, late=0)
98950096
"""
# if we are absent twice, or late 3 consecutive days,
# no further prize strings are possible
if late == 3 or absent == 2:
return 0
# if we have no days left, and have not failed any other rules,
# we have a prize string
if days == 0:
return 1
# No easy solution, so now we need to do the recursive calculation
# First, check if the combination is already in the cache, and
# if yes, return the stored value from there since we already
# know the number of possible prize strings from this point on
key = (days, absent, late)
if key in cache:
return cache[key]
# now we calculate the three possible ways that can unfold from
# this point on, depending on our attendance today
# 1) if we are late (but not absent), the "absent" counter stays as
# it is, but the "late" counter increases by one
state_late = _calculate(days - 1, absent, late + 1)
# 2) if we are absent, the "absent" counter increases by 1, and the
# "late" counter resets to 0
state_absent = _calculate(days - 1, absent + 1, 0)
# 3) if we are on time, this resets the "late" counter and keeps the
# absent counter
state_ontime = _calculate(days - 1, absent, 0)
prizestrings = state_late + state_absent + state_ontime
cache[key] = prizestrings
return prizestrings
def solution(days: int = 30) -> int:
"""
Returns the number of possible prize strings for a particular number
of days, using a simple recursive function with caching to speed it up.
>>> solution()
1918080160
>>> solution(4)
43
"""
return _calculate(days, absent=0, late=0)
if __name__ == "__main__":
print(solution())
|
c12d50cf825a847f68cbb47786f7a24f6fd5f357
|
d689b3caab44773d1c27327c7635748b7510eef0
|
/barbican/tests/tasks/test_common.py
|
044ade792bbf1b65653d5de3d57758af9c82c441
|
[
"Apache-2.0"
] |
permissive
|
openstack/barbican
|
e9d8cd8c7821fbd0cd42381358040540e010d885
|
c8e3dc14e6225f1d400131434e8afec0aa410ae7
|
refs/heads/master
| 2023-09-04T03:08:34.120188
| 2023-08-28T08:06:46
| 2023-08-28T08:06:46
| 20,115,712
| 189
| 93
|
Apache-2.0
| 2021-07-27T06:00:23
| 2014-05-23T22:15:27
|
Python
|
UTF-8
|
Python
| false
| false
| 1,760
|
py
|
test_common.py
|
# Copyright (c) 2015 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from barbican import i18n as u
from barbican.tasks import common
from barbican.tests import utils
class WhenUsingFollowOnProcessingStatusDTO(utils.BaseTestCase):
"""Test using the :class:`WhenUsingFollowOnProcessingStatusDTO` class."""
def setUp(self):
super(WhenUsingFollowOnProcessingStatusDTO, self).setUp()
self.target = common.FollowOnProcessingStatusDTO()
def test_should_have_expected_defaults(self):
self.assertEqual(
common.RetryTasks.NO_ACTION_REQUIRED, self.target.retry_task)
self.assertEqual(u._('Unknown'), self.target.status)
self.assertEqual(u._('Unknown'), self.target.status_message)
self.assertEqual(common.RETRY_MSEC_DEFAULT, self.target.retry_msec)
self.assertFalse(self.target.is_follow_on_needed())
def test_should_indicate_no_follow_on_with_no_retry_task(self):
self.target.retry_task = None
self.assertFalse(self.target.is_follow_on_needed())
def test_should_indicate_follow_on_when_retry_task_provided(self):
self.target.retry_task = common.RetryTasks.INVOKE_SAME_TASK
self.assertTrue(self.target.is_follow_on_needed())
|
05af7f4f8ecaaaeb047574f9e4c6dd4b7e8acb56
|
f305f84ea6f721c2391300f0a60e21d2ce14f2a5
|
/20_杂题/atc競プロ/AtCoder Beginner Contest/224/G - Roll or Increment .py
|
14ca7403e31121de48e6ba6426091d082e469edf
|
[] |
no_license
|
981377660LMT/algorithm-study
|
f2ada3e6959338ae1bc21934a84f7314a8ecff82
|
7e79e26bb8f641868561b186e34c1127ed63c9e0
|
refs/heads/master
| 2023-09-01T18:26:16.525579
| 2023-09-01T12:21:58
| 2023-09-01T12:21:58
| 385,861,235
| 225
| 24
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 370
|
py
|
G - Roll or Increment .py
|
# 掷骰子
# 给定起点 S 与终点 T,可以做两个操作
# !S => S + 1 代价为 A
# !将S变为[1,N]的随机一个整数 代价为B
# 问在最优策略下,从 S 走到 T 的期望代价最小是多少
# 有两种可能的情况:
# !先随机走,如果随机到一个比较好的值,就一直加到T
# !如果满足S<T的话可以直接加到T
|
cc75f1fb6111b4a0da947ee2368ec0c2ff5e2674
|
c1ab5fc6d37749cf7dd693a8f6d5475dfa54cd45
|
/kubernetes/client/api/core_v1_api.py
|
27c87ab84ebf59cdf708fe22ee737cdd85afa139
|
[
"Apache-2.0"
] |
permissive
|
kubernetes-client/python
|
2d10e5d7c1358aa4473c1fcd54d2c5a1085cf56e
|
68d5a1479e7d735ea454021bc54e453c9b31baf7
|
refs/heads/master
| 2023-09-01T11:23:54.508420
| 2023-08-31T21:04:31
| 2023-08-31T21:04:31
| 72,473,727
| 5,792
| 3,654
|
Apache-2.0
| 2023-09-13T18:34:16
| 2016-10-31T20:08:03
|
Python
|
UTF-8
|
Python
| false
| false
| 2,251,164
|
py
|
core_v1_api.py
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.28
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from kubernetes.client.api_client import ApiClient
from kubernetes.client.exceptions import ( # noqa: F401
ApiTypeError,
ApiValueError
)
class CoreV1Api(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def connect_delete_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_delete_namespaced_pod_proxy # noqa: E501
connect DELETE requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_pod_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_delete_namespaced_pod_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_delete_namespaced_pod_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_delete_namespaced_pod_proxy # noqa: E501
connect DELETE requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_pod_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_delete_namespaced_pod_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_delete_namespaced_pod_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_delete_namespaced_pod_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_delete_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_delete_namespaced_pod_proxy_with_path # noqa: E501
connect DELETE requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_pod_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_delete_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_delete_namespaced_pod_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_delete_namespaced_pod_proxy_with_path # noqa: E501
connect DELETE requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_delete_namespaced_pod_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_delete_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_delete_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_delete_namespaced_pod_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_delete_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_delete_namespaced_service_proxy # noqa: E501
connect DELETE requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_service_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_delete_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_delete_namespaced_service_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_delete_namespaced_service_proxy # noqa: E501
connect DELETE requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_service_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_delete_namespaced_service_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_delete_namespaced_service_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_delete_namespaced_service_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_delete_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_delete_namespaced_service_proxy_with_path # noqa: E501
connect DELETE requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_service_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_delete_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_delete_namespaced_service_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_delete_namespaced_service_proxy_with_path # noqa: E501
connect DELETE requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_delete_namespaced_service_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_delete_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_delete_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_delete_namespaced_service_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy/{path}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_delete_node_proxy(self, name, **kwargs): # noqa: E501
"""connect_delete_node_proxy # noqa: E501
connect DELETE requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_node_proxy(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_delete_node_proxy_with_http_info(name, **kwargs) # noqa: E501
def connect_delete_node_proxy_with_http_info(self, name, **kwargs): # noqa: E501
"""connect_delete_node_proxy # noqa: E501
connect DELETE requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_node_proxy_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_delete_node_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_delete_node_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_delete_node_proxy_with_path(self, name, path, **kwargs): # noqa: E501
"""connect_delete_node_proxy_with_path # noqa: E501
connect DELETE requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_node_proxy_with_path(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_delete_node_proxy_with_path_with_http_info(name, path, **kwargs) # noqa: E501
def connect_delete_node_proxy_with_path_with_http_info(self, name, path, **kwargs): # noqa: E501
"""connect_delete_node_proxy_with_path # noqa: E501
connect DELETE requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_node_proxy_with_path_with_http_info(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_delete_node_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_delete_node_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_delete_node_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy/{path}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_get_namespaced_pod_attach(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_attach # noqa: E501
connect GET requests to attach of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_attach(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodAttachOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str container: The container in which to execute the command. Defaults to only container if there is only one container in the pod.
:param bool stderr: Stderr if true indicates that stderr is to be redirected for the attach call. Defaults to true.
:param bool stdin: Stdin if true, redirects the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Stdout if true indicates that stdout is to be redirected for the attach call. Defaults to true.
:param bool tty: TTY if true indicates that a tty will be allocated for the attach call. This is passed through the container runtime so the tty is allocated on the worker node by the container runtime. Defaults to false.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_get_namespaced_pod_attach_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_get_namespaced_pod_attach_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_attach # noqa: E501
connect GET requests to attach of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_attach_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodAttachOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str container: The container in which to execute the command. Defaults to only container if there is only one container in the pod.
:param bool stderr: Stderr if true indicates that stderr is to be redirected for the attach call. Defaults to true.
:param bool stdin: Stdin if true, redirects the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Stdout if true indicates that stdout is to be redirected for the attach call. Defaults to true.
:param bool tty: TTY if true indicates that a tty will be allocated for the attach call. This is passed through the container runtime so the tty is allocated on the worker node by the container runtime. Defaults to false.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'container',
'stderr',
'stdin',
'stdout',
'tty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_pod_attach" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_get_namespaced_pod_attach`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_pod_attach`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'container' in local_var_params and local_var_params['container'] is not None: # noqa: E501
query_params.append(('container', local_var_params['container'])) # noqa: E501
if 'stderr' in local_var_params and local_var_params['stderr'] is not None: # noqa: E501
query_params.append(('stderr', local_var_params['stderr'])) # noqa: E501
if 'stdin' in local_var_params and local_var_params['stdin'] is not None: # noqa: E501
query_params.append(('stdin', local_var_params['stdin'])) # noqa: E501
if 'stdout' in local_var_params and local_var_params['stdout'] is not None: # noqa: E501
query_params.append(('stdout', local_var_params['stdout'])) # noqa: E501
if 'tty' in local_var_params and local_var_params['tty'] is not None: # noqa: E501
query_params.append(('tty', local_var_params['tty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/attach', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_get_namespaced_pod_exec(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_exec # noqa: E501
connect GET requests to exec of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_exec(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodExecOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str command: Command is the remote command to execute. argv array. Not executed within a shell.
:param str container: Container in which to execute the command. Defaults to only container if there is only one container in the pod.
:param bool stderr: Redirect the standard error stream of the pod for this call.
:param bool stdin: Redirect the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Redirect the standard output stream of the pod for this call.
:param bool tty: TTY if true indicates that a tty will be allocated for the exec call. Defaults to false.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_get_namespaced_pod_exec_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_get_namespaced_pod_exec_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_exec # noqa: E501
connect GET requests to exec of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_exec_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodExecOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str command: Command is the remote command to execute. argv array. Not executed within a shell.
:param str container: Container in which to execute the command. Defaults to only container if there is only one container in the pod.
:param bool stderr: Redirect the standard error stream of the pod for this call.
:param bool stdin: Redirect the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Redirect the standard output stream of the pod for this call.
:param bool tty: TTY if true indicates that a tty will be allocated for the exec call. Defaults to false.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'command',
'container',
'stderr',
'stdin',
'stdout',
'tty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_pod_exec" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_get_namespaced_pod_exec`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_pod_exec`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'command' in local_var_params and local_var_params['command'] is not None: # noqa: E501
query_params.append(('command', local_var_params['command'])) # noqa: E501
if 'container' in local_var_params and local_var_params['container'] is not None: # noqa: E501
query_params.append(('container', local_var_params['container'])) # noqa: E501
if 'stderr' in local_var_params and local_var_params['stderr'] is not None: # noqa: E501
query_params.append(('stderr', local_var_params['stderr'])) # noqa: E501
if 'stdin' in local_var_params and local_var_params['stdin'] is not None: # noqa: E501
query_params.append(('stdin', local_var_params['stdin'])) # noqa: E501
if 'stdout' in local_var_params and local_var_params['stdout'] is not None: # noqa: E501
query_params.append(('stdout', local_var_params['stdout'])) # noqa: E501
if 'tty' in local_var_params and local_var_params['tty'] is not None: # noqa: E501
query_params.append(('tty', local_var_params['tty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/exec', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_get_namespaced_pod_portforward(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_portforward # noqa: E501
connect GET requests to portforward of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_portforward(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodPortForwardOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param int ports: List of ports to forward Required when using WebSockets
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_get_namespaced_pod_portforward_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_get_namespaced_pod_portforward_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_portforward # noqa: E501
connect GET requests to portforward of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_portforward_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodPortForwardOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param int ports: List of ports to forward Required when using WebSockets
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'ports'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_pod_portforward" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_get_namespaced_pod_portforward`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_pod_portforward`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'ports' in local_var_params and local_var_params['ports'] is not None: # noqa: E501
query_params.append(('ports', local_var_params['ports'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/portforward', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_get_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_proxy # noqa: E501
connect GET requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_get_namespaced_pod_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_get_namespaced_pod_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_proxy # noqa: E501
connect GET requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_pod_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_get_namespaced_pod_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_pod_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_get_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_proxy_with_path # noqa: E501
connect GET requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_get_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_get_namespaced_pod_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_proxy_with_path # noqa: E501
connect GET requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_pod_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_get_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_get_namespaced_pod_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_get_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_service_proxy # noqa: E501
connect GET requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_service_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_get_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_get_namespaced_service_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_service_proxy # noqa: E501
connect GET requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_service_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_service_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_get_namespaced_service_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_service_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_get_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_get_namespaced_service_proxy_with_path # noqa: E501
connect GET requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_service_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_get_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_get_namespaced_service_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_get_namespaced_service_proxy_with_path # noqa: E501
connect GET requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_service_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_get_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_get_namespaced_service_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy/{path}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_get_node_proxy(self, name, **kwargs): # noqa: E501
"""connect_get_node_proxy # noqa: E501
connect GET requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_node_proxy(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_get_node_proxy_with_http_info(name, **kwargs) # noqa: E501
def connect_get_node_proxy_with_http_info(self, name, **kwargs): # noqa: E501
"""connect_get_node_proxy # noqa: E501
connect GET requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_node_proxy_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_node_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_get_node_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_get_node_proxy_with_path(self, name, path, **kwargs): # noqa: E501
"""connect_get_node_proxy_with_path # noqa: E501
connect GET requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_node_proxy_with_path(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_get_node_proxy_with_path_with_http_info(name, path, **kwargs) # noqa: E501
def connect_get_node_proxy_with_path_with_http_info(self, name, path, **kwargs): # noqa: E501
"""connect_get_node_proxy_with_path # noqa: E501
connect GET requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_node_proxy_with_path_with_http_info(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_node_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_get_node_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_get_node_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy/{path}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_head_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_head_namespaced_pod_proxy # noqa: E501
connect HEAD requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_namespaced_pod_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_head_namespaced_pod_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_head_namespaced_pod_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_head_namespaced_pod_proxy # noqa: E501
connect HEAD requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_namespaced_pod_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_head_namespaced_pod_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_head_namespaced_pod_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_head_namespaced_pod_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy', 'HEAD',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_head_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_head_namespaced_pod_proxy_with_path # noqa: E501
connect HEAD requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_namespaced_pod_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_head_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_head_namespaced_pod_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_head_namespaced_pod_proxy_with_path # noqa: E501
connect HEAD requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_head_namespaced_pod_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_head_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_head_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_head_namespaced_pod_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}', 'HEAD',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_head_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_head_namespaced_service_proxy # noqa: E501
connect HEAD requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_namespaced_service_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_head_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_head_namespaced_service_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_head_namespaced_service_proxy # noqa: E501
connect HEAD requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_namespaced_service_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_head_namespaced_service_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_head_namespaced_service_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_head_namespaced_service_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy', 'HEAD',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_head_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_head_namespaced_service_proxy_with_path # noqa: E501
connect HEAD requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_namespaced_service_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_head_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_head_namespaced_service_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_head_namespaced_service_proxy_with_path # noqa: E501
connect HEAD requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_head_namespaced_service_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_head_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_head_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_head_namespaced_service_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy/{path}', 'HEAD',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_head_node_proxy(self, name, **kwargs): # noqa: E501
"""connect_head_node_proxy # noqa: E501
connect HEAD requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_node_proxy(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_head_node_proxy_with_http_info(name, **kwargs) # noqa: E501
def connect_head_node_proxy_with_http_info(self, name, **kwargs): # noqa: E501
"""connect_head_node_proxy # noqa: E501
connect HEAD requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_node_proxy_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_head_node_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_head_node_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy', 'HEAD',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_head_node_proxy_with_path(self, name, path, **kwargs): # noqa: E501
"""connect_head_node_proxy_with_path # noqa: E501
connect HEAD requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_node_proxy_with_path(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_head_node_proxy_with_path_with_http_info(name, path, **kwargs) # noqa: E501
def connect_head_node_proxy_with_path_with_http_info(self, name, path, **kwargs): # noqa: E501
"""connect_head_node_proxy_with_path # noqa: E501
connect HEAD requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_head_node_proxy_with_path_with_http_info(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_head_node_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_head_node_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_head_node_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy/{path}', 'HEAD',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_options_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_options_namespaced_pod_proxy # noqa: E501
connect OPTIONS requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_namespaced_pod_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_options_namespaced_pod_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_options_namespaced_pod_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_options_namespaced_pod_proxy # noqa: E501
connect OPTIONS requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_namespaced_pod_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_options_namespaced_pod_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_options_namespaced_pod_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_options_namespaced_pod_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy', 'OPTIONS',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_options_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_options_namespaced_pod_proxy_with_path # noqa: E501
connect OPTIONS requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_namespaced_pod_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_options_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_options_namespaced_pod_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_options_namespaced_pod_proxy_with_path # noqa: E501
connect OPTIONS requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_options_namespaced_pod_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_options_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_options_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_options_namespaced_pod_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}', 'OPTIONS',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_options_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_options_namespaced_service_proxy # noqa: E501
connect OPTIONS requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_namespaced_service_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_options_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_options_namespaced_service_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_options_namespaced_service_proxy # noqa: E501
connect OPTIONS requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_namespaced_service_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_options_namespaced_service_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_options_namespaced_service_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_options_namespaced_service_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy', 'OPTIONS',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_options_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_options_namespaced_service_proxy_with_path # noqa: E501
connect OPTIONS requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_namespaced_service_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_options_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_options_namespaced_service_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_options_namespaced_service_proxy_with_path # noqa: E501
connect OPTIONS requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_options_namespaced_service_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_options_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_options_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_options_namespaced_service_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy/{path}', 'OPTIONS',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_options_node_proxy(self, name, **kwargs): # noqa: E501
"""connect_options_node_proxy # noqa: E501
connect OPTIONS requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_node_proxy(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_options_node_proxy_with_http_info(name, **kwargs) # noqa: E501
def connect_options_node_proxy_with_http_info(self, name, **kwargs): # noqa: E501
"""connect_options_node_proxy # noqa: E501
connect OPTIONS requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_node_proxy_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_options_node_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_options_node_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy', 'OPTIONS',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_options_node_proxy_with_path(self, name, path, **kwargs): # noqa: E501
"""connect_options_node_proxy_with_path # noqa: E501
connect OPTIONS requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_node_proxy_with_path(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_options_node_proxy_with_path_with_http_info(name, path, **kwargs) # noqa: E501
def connect_options_node_proxy_with_path_with_http_info(self, name, path, **kwargs): # noqa: E501
"""connect_options_node_proxy_with_path # noqa: E501
connect OPTIONS requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_options_node_proxy_with_path_with_http_info(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_options_node_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_options_node_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_options_node_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy/{path}', 'OPTIONS',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_patch_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_patch_namespaced_pod_proxy # noqa: E501
connect PATCH requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_namespaced_pod_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_patch_namespaced_pod_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_patch_namespaced_pod_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_patch_namespaced_pod_proxy # noqa: E501
connect PATCH requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_namespaced_pod_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_patch_namespaced_pod_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_patch_namespaced_pod_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_patch_namespaced_pod_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_patch_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_patch_namespaced_pod_proxy_with_path # noqa: E501
connect PATCH requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_namespaced_pod_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_patch_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_patch_namespaced_pod_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_patch_namespaced_pod_proxy_with_path # noqa: E501
connect PATCH requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_patch_namespaced_pod_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_patch_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_patch_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_patch_namespaced_pod_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_patch_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_patch_namespaced_service_proxy # noqa: E501
connect PATCH requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_namespaced_service_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_patch_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_patch_namespaced_service_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_patch_namespaced_service_proxy # noqa: E501
connect PATCH requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_namespaced_service_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_patch_namespaced_service_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_patch_namespaced_service_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_patch_namespaced_service_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_patch_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_patch_namespaced_service_proxy_with_path # noqa: E501
connect PATCH requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_namespaced_service_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_patch_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_patch_namespaced_service_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_patch_namespaced_service_proxy_with_path # noqa: E501
connect PATCH requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_patch_namespaced_service_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_patch_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_patch_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_patch_namespaced_service_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy/{path}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_patch_node_proxy(self, name, **kwargs): # noqa: E501
"""connect_patch_node_proxy # noqa: E501
connect PATCH requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_node_proxy(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_patch_node_proxy_with_http_info(name, **kwargs) # noqa: E501
def connect_patch_node_proxy_with_http_info(self, name, **kwargs): # noqa: E501
"""connect_patch_node_proxy # noqa: E501
connect PATCH requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_node_proxy_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_patch_node_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_patch_node_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_patch_node_proxy_with_path(self, name, path, **kwargs): # noqa: E501
"""connect_patch_node_proxy_with_path # noqa: E501
connect PATCH requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_node_proxy_with_path(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_patch_node_proxy_with_path_with_http_info(name, path, **kwargs) # noqa: E501
def connect_patch_node_proxy_with_path_with_http_info(self, name, path, **kwargs): # noqa: E501
"""connect_patch_node_proxy_with_path # noqa: E501
connect PATCH requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_patch_node_proxy_with_path_with_http_info(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_patch_node_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_patch_node_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_patch_node_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy/{path}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_post_namespaced_pod_attach(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_attach # noqa: E501
connect POST requests to attach of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_attach(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodAttachOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str container: The container in which to execute the command. Defaults to only container if there is only one container in the pod.
:param bool stderr: Stderr if true indicates that stderr is to be redirected for the attach call. Defaults to true.
:param bool stdin: Stdin if true, redirects the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Stdout if true indicates that stdout is to be redirected for the attach call. Defaults to true.
:param bool tty: TTY if true indicates that a tty will be allocated for the attach call. This is passed through the container runtime so the tty is allocated on the worker node by the container runtime. Defaults to false.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_post_namespaced_pod_attach_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_post_namespaced_pod_attach_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_attach # noqa: E501
connect POST requests to attach of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_attach_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodAttachOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str container: The container in which to execute the command. Defaults to only container if there is only one container in the pod.
:param bool stderr: Stderr if true indicates that stderr is to be redirected for the attach call. Defaults to true.
:param bool stdin: Stdin if true, redirects the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Stdout if true indicates that stdout is to be redirected for the attach call. Defaults to true.
:param bool tty: TTY if true indicates that a tty will be allocated for the attach call. This is passed through the container runtime so the tty is allocated on the worker node by the container runtime. Defaults to false.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'container',
'stderr',
'stdin',
'stdout',
'tty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_pod_attach" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_attach`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_attach`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'container' in local_var_params and local_var_params['container'] is not None: # noqa: E501
query_params.append(('container', local_var_params['container'])) # noqa: E501
if 'stderr' in local_var_params and local_var_params['stderr'] is not None: # noqa: E501
query_params.append(('stderr', local_var_params['stderr'])) # noqa: E501
if 'stdin' in local_var_params and local_var_params['stdin'] is not None: # noqa: E501
query_params.append(('stdin', local_var_params['stdin'])) # noqa: E501
if 'stdout' in local_var_params and local_var_params['stdout'] is not None: # noqa: E501
query_params.append(('stdout', local_var_params['stdout'])) # noqa: E501
if 'tty' in local_var_params and local_var_params['tty'] is not None: # noqa: E501
query_params.append(('tty', local_var_params['tty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/attach', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_post_namespaced_pod_exec(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_exec # noqa: E501
connect POST requests to exec of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_exec(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodExecOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str command: Command is the remote command to execute. argv array. Not executed within a shell.
:param str container: Container in which to execute the command. Defaults to only container if there is only one container in the pod.
:param bool stderr: Redirect the standard error stream of the pod for this call.
:param bool stdin: Redirect the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Redirect the standard output stream of the pod for this call.
:param bool tty: TTY if true indicates that a tty will be allocated for the exec call. Defaults to false.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_post_namespaced_pod_exec_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_post_namespaced_pod_exec_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_exec # noqa: E501
connect POST requests to exec of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_exec_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodExecOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str command: Command is the remote command to execute. argv array. Not executed within a shell.
:param str container: Container in which to execute the command. Defaults to only container if there is only one container in the pod.
:param bool stderr: Redirect the standard error stream of the pod for this call.
:param bool stdin: Redirect the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Redirect the standard output stream of the pod for this call.
:param bool tty: TTY if true indicates that a tty will be allocated for the exec call. Defaults to false.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'command',
'container',
'stderr',
'stdin',
'stdout',
'tty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_pod_exec" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_exec`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_exec`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'command' in local_var_params and local_var_params['command'] is not None: # noqa: E501
query_params.append(('command', local_var_params['command'])) # noqa: E501
if 'container' in local_var_params and local_var_params['container'] is not None: # noqa: E501
query_params.append(('container', local_var_params['container'])) # noqa: E501
if 'stderr' in local_var_params and local_var_params['stderr'] is not None: # noqa: E501
query_params.append(('stderr', local_var_params['stderr'])) # noqa: E501
if 'stdin' in local_var_params and local_var_params['stdin'] is not None: # noqa: E501
query_params.append(('stdin', local_var_params['stdin'])) # noqa: E501
if 'stdout' in local_var_params and local_var_params['stdout'] is not None: # noqa: E501
query_params.append(('stdout', local_var_params['stdout'])) # noqa: E501
if 'tty' in local_var_params and local_var_params['tty'] is not None: # noqa: E501
query_params.append(('tty', local_var_params['tty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/exec', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_post_namespaced_pod_portforward(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_portforward # noqa: E501
connect POST requests to portforward of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_portforward(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodPortForwardOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param int ports: List of ports to forward Required when using WebSockets
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_post_namespaced_pod_portforward_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_post_namespaced_pod_portforward_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_portforward # noqa: E501
connect POST requests to portforward of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_portforward_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodPortForwardOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param int ports: List of ports to forward Required when using WebSockets
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'ports'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_pod_portforward" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_portforward`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_portforward`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'ports' in local_var_params and local_var_params['ports'] is not None: # noqa: E501
query_params.append(('ports', local_var_params['ports'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/portforward', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_post_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_proxy # noqa: E501
connect POST requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_post_namespaced_pod_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_post_namespaced_pod_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_proxy # noqa: E501
connect POST requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_pod_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_post_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_proxy_with_path # noqa: E501
connect POST requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_post_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_post_namespaced_pod_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_post_namespaced_pod_proxy_with_path # noqa: E501
connect POST requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_pod_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_post_namespaced_pod_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_post_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_service_proxy # noqa: E501
connect POST requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_service_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_post_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_post_namespaced_service_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_post_namespaced_service_proxy # noqa: E501
connect POST requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_service_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_service_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_post_namespaced_service_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_service_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_post_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_post_namespaced_service_proxy_with_path # noqa: E501
connect POST requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_service_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_post_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_post_namespaced_service_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_post_namespaced_service_proxy_with_path # noqa: E501
connect POST requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_service_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_post_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_post_namespaced_service_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy/{path}', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_post_node_proxy(self, name, **kwargs): # noqa: E501
"""connect_post_node_proxy # noqa: E501
connect POST requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_node_proxy(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_post_node_proxy_with_http_info(name, **kwargs) # noqa: E501
def connect_post_node_proxy_with_http_info(self, name, **kwargs): # noqa: E501
"""connect_post_node_proxy # noqa: E501
connect POST requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_node_proxy_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_node_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_post_node_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_post_node_proxy_with_path(self, name, path, **kwargs): # noqa: E501
"""connect_post_node_proxy_with_path # noqa: E501
connect POST requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_node_proxy_with_path(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_post_node_proxy_with_path_with_http_info(name, path, **kwargs) # noqa: E501
def connect_post_node_proxy_with_path_with_http_info(self, name, path, **kwargs): # noqa: E501
"""connect_post_node_proxy_with_path # noqa: E501
connect POST requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_post_node_proxy_with_path_with_http_info(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_node_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_post_node_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_post_node_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy/{path}', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_put_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_put_namespaced_pod_proxy # noqa: E501
connect PUT requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_namespaced_pod_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_put_namespaced_pod_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_put_namespaced_pod_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_put_namespaced_pod_proxy # noqa: E501
connect PUT requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_namespaced_pod_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_put_namespaced_pod_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_put_namespaced_pod_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_put_namespaced_pod_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_put_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_put_namespaced_pod_proxy_with_path # noqa: E501
connect PUT requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_namespaced_pod_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_put_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_put_namespaced_pod_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_put_namespaced_pod_proxy_with_path # noqa: E501
connect PUT requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_namespaced_pod_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to pod.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_put_namespaced_pod_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_put_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_put_namespaced_pod_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_put_namespaced_pod_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_put_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_put_namespaced_service_proxy # noqa: E501
connect PUT requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_namespaced_service_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_put_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) # noqa: E501
def connect_put_namespaced_service_proxy_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""connect_put_namespaced_service_proxy # noqa: E501
connect PUT requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_namespaced_service_proxy_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_put_namespaced_service_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_put_namespaced_service_proxy`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_put_namespaced_service_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_put_namespaced_service_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_put_namespaced_service_proxy_with_path # noqa: E501
connect PUT requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_namespaced_service_proxy_with_path(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_put_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, **kwargs) # noqa: E501
def connect_put_namespaced_service_proxy_with_path_with_http_info(self, name, namespace, path, **kwargs): # noqa: E501
"""connect_put_namespaced_service_proxy_with_path # noqa: E501
connect PUT requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_namespaced_service_proxy_with_path_with_http_info(name, namespace, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceProxyOptions (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str path: path to the resource (required)
:param str path2: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_put_namespaced_service_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_put_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `connect_put_namespaced_service_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_put_namespaced_service_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/proxy/{path}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_put_node_proxy(self, name, **kwargs): # noqa: E501
"""connect_put_node_proxy # noqa: E501
connect PUT requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_node_proxy(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_put_node_proxy_with_http_info(name, **kwargs) # noqa: E501
def connect_put_node_proxy_with_http_info(self, name, **kwargs): # noqa: E501
"""connect_put_node_proxy # noqa: E501
connect PUT requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_node_proxy_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_put_node_proxy" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_put_node_proxy`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'path' in local_var_params and local_var_params['path'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def connect_put_node_proxy_with_path(self, name, path, **kwargs): # noqa: E501
"""connect_put_node_proxy_with_path # noqa: E501
connect PUT requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_node_proxy_with_path(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.connect_put_node_proxy_with_path_with_http_info(name, path, **kwargs) # noqa: E501
def connect_put_node_proxy_with_path_with_http_info(self, name, path, **kwargs): # noqa: E501
"""connect_put_node_proxy_with_path # noqa: E501
connect PUT requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_put_node_proxy_with_path_with_http_info(name, path, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the NodeProxyOptions (required)
:param str path: path to the resource (required)
:param str path2: Path is the URL path to use for the current proxy request to node.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'path',
'path2'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_put_node_proxy_with_path" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `connect_put_node_proxy_with_path`") # noqa: E501
# verify the required parameter 'path' is set
if self.api_client.client_side_validation and ('path' not in local_var_params or # noqa: E501
local_var_params['path'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `path` when calling `connect_put_node_proxy_with_path`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'path' in local_var_params:
path_params['path'] = local_var_params['path'] # noqa: E501
query_params = []
if 'path2' in local_var_params and local_var_params['path2'] is not None: # noqa: E501
query_params.append(('path', local_var_params['path2'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['*/*']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/proxy/{path}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespace(self, body, **kwargs): # noqa: E501
"""create_namespace # noqa: E501
create a Namespace # 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_namespace(body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param V1Namespace body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespace_with_http_info(body, **kwargs) # noqa: E501
def create_namespace_with_http_info(self, body, **kwargs): # noqa: E501
"""create_namespace # noqa: E501
create a Namespace # 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_namespace_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param V1Namespace body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Namespace, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespace" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespace`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Namespace', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_binding(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_binding # noqa: E501
create a Binding # 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_namespaced_binding(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Binding body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Binding
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_binding_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_binding_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_binding # noqa: E501
create a Binding # 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_namespaced_binding_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Binding body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Binding, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'dry_run',
'field_manager',
'field_validation',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_binding" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_binding`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_binding`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/bindings', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Binding', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_config_map(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_config_map # noqa: E501
create a ConfigMap # 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_namespaced_config_map(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ConfigMap body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ConfigMap
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_config_map_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_config_map_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_config_map # noqa: E501
create a ConfigMap # 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_namespaced_config_map_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ConfigMap body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ConfigMap, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_config_map" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_config_map`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_config_map`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/configmaps', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ConfigMap', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_endpoints(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_endpoints # noqa: E501
create Endpoints # 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_namespaced_endpoints(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Endpoints body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Endpoints
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_endpoints_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_endpoints_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_endpoints # noqa: E501
create Endpoints # 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_namespaced_endpoints_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Endpoints body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Endpoints, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_endpoints" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_endpoints`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_endpoints`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/endpoints', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Endpoints', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_event(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_event # noqa: E501
create an Event # 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_namespaced_event(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param CoreV1Event body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: CoreV1Event
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_event_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_event_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_event # noqa: E501
create an Event # 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_namespaced_event_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param CoreV1Event body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(CoreV1Event, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_event`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/events', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CoreV1Event', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_limit_range(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_limit_range # noqa: E501
create a LimitRange # 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_namespaced_limit_range(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1LimitRange body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1LimitRange
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_limit_range_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_limit_range_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_limit_range # noqa: E501
create a LimitRange # 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_namespaced_limit_range_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1LimitRange body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1LimitRange, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_limit_range" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_limit_range`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_limit_range`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/limitranges', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1LimitRange', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_persistent_volume_claim(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_persistent_volume_claim # noqa: E501
create a PersistentVolumeClaim # 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_namespaced_persistent_volume_claim(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1PersistentVolumeClaim body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_persistent_volume_claim_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_persistent_volume_claim_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_persistent_volume_claim # noqa: E501
create a PersistentVolumeClaim # 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_namespaced_persistent_volume_claim_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1PersistentVolumeClaim body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeClaim, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_persistent_volume_claim" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_persistent_volume_claim`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_persistent_volume_claim`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/persistentvolumeclaims', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeClaim', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_pod(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_pod # noqa: E501
create a Pod # 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_namespaced_pod(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Pod body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_pod_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_pod_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_pod # noqa: E501
create a Pod # 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_namespaced_pod_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Pod body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_pod" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_pod`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_pod`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_pod_binding(self, name, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_pod_binding # noqa: E501
create binding of a Pod # 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_namespaced_pod_binding(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Binding (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Binding body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Binding
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_pod_binding_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def create_namespaced_pod_binding_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_pod_binding # noqa: E501
create binding of a Pod # 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_namespaced_pod_binding_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Binding (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Binding body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Binding, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'dry_run',
'field_manager',
'field_validation',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_pod_binding" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `create_namespaced_pod_binding`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_pod_binding`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_pod_binding`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/binding', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Binding', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_pod_eviction(self, name, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_pod_eviction # noqa: E501
create eviction of a Pod # 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_namespaced_pod_eviction(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Eviction (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Eviction body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Eviction
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_pod_eviction_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def create_namespaced_pod_eviction_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_pod_eviction # noqa: E501
create eviction of a Pod # 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_namespaced_pod_eviction_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Eviction (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Eviction body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Eviction, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'dry_run',
'field_manager',
'field_validation',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_pod_eviction" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `create_namespaced_pod_eviction`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_pod_eviction`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_pod_eviction`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/eviction', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Eviction', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_pod_template(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_pod_template # noqa: E501
create a PodTemplate # 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_namespaced_pod_template(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1PodTemplate body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PodTemplate
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_pod_template_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_pod_template_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_pod_template # noqa: E501
create a PodTemplate # 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_namespaced_pod_template_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1PodTemplate body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PodTemplate, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_pod_template" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_pod_template`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_pod_template`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/podtemplates', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PodTemplate', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_replication_controller(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_replication_controller # noqa: E501
create a ReplicationController # 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_namespaced_replication_controller(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ReplicationController body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_replication_controller_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_replication_controller_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_replication_controller # noqa: E501
create a ReplicationController # 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_namespaced_replication_controller_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ReplicationController body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ReplicationController, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_replication_controller" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_replication_controller`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_replication_controller`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ReplicationController', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_resource_quota(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_resource_quota # noqa: E501
create a ResourceQuota # 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_namespaced_resource_quota(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ResourceQuota body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_resource_quota_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_resource_quota_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_resource_quota # noqa: E501
create a ResourceQuota # 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_namespaced_resource_quota_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ResourceQuota body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ResourceQuota, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_resource_quota" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_resource_quota`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_resource_quota`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/resourcequotas', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ResourceQuota', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_secret(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_secret # noqa: E501
create a Secret # 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_namespaced_secret(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Secret body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Secret
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_secret_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_secret_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_secret # noqa: E501
create a Secret # 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_namespaced_secret_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Secret body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Secret, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_secret" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_secret`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_secret`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/secrets', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Secret', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_service(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_service # noqa: E501
create a Service # 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_namespaced_service(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Service body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_service_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_service_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_service # noqa: E501
create a Service # 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_namespaced_service_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Service body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Service, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_service" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_service`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_service`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Service', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_service_account(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_service_account # noqa: E501
create a ServiceAccount # 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_namespaced_service_account(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ServiceAccount body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ServiceAccount
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_service_account_with_http_info(namespace, body, **kwargs) # noqa: E501
def create_namespaced_service_account_with_http_info(self, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_service_account # noqa: E501
create a ServiceAccount # 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_namespaced_service_account_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ServiceAccount body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ServiceAccount, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_service_account" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_service_account`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_service_account`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/serviceaccounts', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ServiceAccount', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_service_account_token(self, name, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_service_account_token # noqa: E501
create token of a ServiceAccount # 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_namespaced_service_account_token(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the TokenRequest (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AuthenticationV1TokenRequest body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: AuthenticationV1TokenRequest
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_namespaced_service_account_token_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def create_namespaced_service_account_token_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""create_namespaced_service_account_token # noqa: E501
create token of a ServiceAccount # 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_namespaced_service_account_token_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the TokenRequest (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AuthenticationV1TokenRequest body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(AuthenticationV1TokenRequest, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'dry_run',
'field_manager',
'field_validation',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_service_account_token" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `create_namespaced_service_account_token`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_service_account_token`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_service_account_token`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/serviceaccounts/{name}/token', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AuthenticationV1TokenRequest', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_node(self, body, **kwargs): # noqa: E501
"""create_node # noqa: E501
create a Node # 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_node(body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param V1Node body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_node_with_http_info(body, **kwargs) # noqa: E501
def create_node_with_http_info(self, body, **kwargs): # noqa: E501
"""create_node # noqa: E501
create a Node # 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_node_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param V1Node body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Node, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_node" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_node`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Node', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def create_persistent_volume(self, body, **kwargs): # noqa: E501
"""create_persistent_volume # noqa: E501
create a PersistentVolume # 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_persistent_volume(body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param V1PersistentVolume body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.create_persistent_volume_with_http_info(body, **kwargs) # noqa: E501
def create_persistent_volume_with_http_info(self, body, **kwargs): # noqa: E501
"""create_persistent_volume # noqa: E501
create a PersistentVolume # 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_persistent_volume_with_http_info(body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param V1PersistentVolume body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolume, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method create_persistent_volume" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_persistent_volume`") # noqa: E501
collection_formats = {}
path_params = {}
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumes', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolume', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_config_map(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_config_map # noqa: E501
delete collection of ConfigMap # 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_collection_namespaced_config_map(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_config_map_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_config_map_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_config_map # noqa: E501
delete collection of ConfigMap # 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_collection_namespaced_config_map_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_config_map" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_config_map`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/configmaps', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_endpoints(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_endpoints # noqa: E501
delete collection of Endpoints # 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_collection_namespaced_endpoints(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_endpoints_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_endpoints_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_endpoints # noqa: E501
delete collection of Endpoints # 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_collection_namespaced_endpoints_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_endpoints" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_endpoints`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/endpoints', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_event(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_event # noqa: E501
delete collection of Event # 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_collection_namespaced_event(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_event_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_event_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_event # noqa: E501
delete collection of Event # 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_collection_namespaced_event_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/events', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_limit_range(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_limit_range # noqa: E501
delete collection of LimitRange # 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_collection_namespaced_limit_range(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_limit_range_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_limit_range_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_limit_range # noqa: E501
delete collection of LimitRange # 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_collection_namespaced_limit_range_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_limit_range" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_limit_range`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/limitranges', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_persistent_volume_claim(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_persistent_volume_claim # noqa: E501
delete collection of PersistentVolumeClaim # 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_collection_namespaced_persistent_volume_claim(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_persistent_volume_claim_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_persistent_volume_claim_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_persistent_volume_claim # noqa: E501
delete collection of PersistentVolumeClaim # 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_collection_namespaced_persistent_volume_claim_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_persistent_volume_claim" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_persistent_volume_claim`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/persistentvolumeclaims', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_pod(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_pod # noqa: E501
delete collection of Pod # 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_collection_namespaced_pod(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_pod_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_pod_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_pod # noqa: E501
delete collection of Pod # 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_collection_namespaced_pod_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_pod" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_pod`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_pod_template(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_pod_template # noqa: E501
delete collection of PodTemplate # 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_collection_namespaced_pod_template(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_pod_template_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_pod_template_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_pod_template # noqa: E501
delete collection of PodTemplate # 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_collection_namespaced_pod_template_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_pod_template" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_pod_template`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/podtemplates', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_replication_controller(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_replication_controller # noqa: E501
delete collection of ReplicationController # 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_collection_namespaced_replication_controller(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_replication_controller_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_replication_controller_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_replication_controller # noqa: E501
delete collection of ReplicationController # 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_collection_namespaced_replication_controller_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_replication_controller" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_replication_controller`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_resource_quota(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_resource_quota # noqa: E501
delete collection of ResourceQuota # 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_collection_namespaced_resource_quota(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_resource_quota_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_resource_quota_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_resource_quota # noqa: E501
delete collection of ResourceQuota # 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_collection_namespaced_resource_quota_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_resource_quota" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_resource_quota`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/resourcequotas', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_secret(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_secret # noqa: E501
delete collection of Secret # 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_collection_namespaced_secret(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_secret_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_secret_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_secret # noqa: E501
delete collection of Secret # 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_collection_namespaced_secret_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_secret" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_secret`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/secrets', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_service(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_service # noqa: E501
delete collection of Service # 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_collection_namespaced_service(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_service_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_service_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_service # noqa: E501
delete collection of Service # 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_collection_namespaced_service_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_service" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_service`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_service_account(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_service_account # noqa: E501
delete collection of ServiceAccount # 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_collection_namespaced_service_account(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_namespaced_service_account_with_http_info(namespace, **kwargs) # noqa: E501
def delete_collection_namespaced_service_account_with_http_info(self, namespace, **kwargs): # noqa: E501
"""delete_collection_namespaced_service_account # noqa: E501
delete collection of ServiceAccount # 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_collection_namespaced_service_account_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_service_account" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_service_account`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/serviceaccounts', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_node(self, **kwargs): # noqa: E501
"""delete_collection_node # noqa: E501
delete collection of Node # 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_collection_node(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_node_with_http_info(**kwargs) # noqa: E501
def delete_collection_node_with_http_info(self, **kwargs): # noqa: E501
"""delete_collection_node # noqa: E501
delete collection of Node # 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_collection_node_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_node" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_persistent_volume(self, **kwargs): # noqa: E501
"""delete_collection_persistent_volume # noqa: E501
delete collection of PersistentVolume # 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_collection_persistent_volume(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_collection_persistent_volume_with_http_info(**kwargs) # noqa: E501
def delete_collection_persistent_volume_with_http_info(self, **kwargs): # noqa: E501
"""delete_collection_persistent_volume # noqa: E501
delete collection of PersistentVolume # 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_collection_persistent_volume_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'pretty',
'_continue',
'dry_run',
'field_selector',
'grace_period_seconds',
'label_selector',
'limit',
'orphan_dependents',
'propagation_policy',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_persistent_volume" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumes', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespace(self, name, **kwargs): # noqa: E501
"""delete_namespace # noqa: E501
delete a Namespace # 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_namespace(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespace_with_http_info(name, **kwargs) # noqa: E501
def delete_namespace_with_http_info(self, name, **kwargs): # noqa: E501
"""delete_namespace # noqa: E501
delete a Namespace # 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_namespace_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespace" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespace`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_config_map(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_config_map # noqa: E501
delete a ConfigMap # 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_namespaced_config_map(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ConfigMap (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_config_map_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_config_map_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_config_map # noqa: E501
delete a ConfigMap # 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_namespaced_config_map_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ConfigMap (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_config_map" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_config_map`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_config_map`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/configmaps/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_endpoints(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_endpoints # noqa: E501
delete Endpoints # 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_namespaced_endpoints(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Endpoints (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_endpoints_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_endpoints_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_endpoints # noqa: E501
delete Endpoints # 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_namespaced_endpoints_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Endpoints (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_endpoints" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_endpoints`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_endpoints`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/endpoints/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_event(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_event # noqa: E501
delete an Event # 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_namespaced_event(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_event_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_event_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_event # noqa: E501
delete an Event # 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_namespaced_event_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_event`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/events/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_limit_range(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_limit_range # noqa: E501
delete a LimitRange # 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_namespaced_limit_range(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the LimitRange (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_limit_range_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_limit_range_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_limit_range # noqa: E501
delete a LimitRange # 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_namespaced_limit_range_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the LimitRange (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_limit_range" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_limit_range`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_limit_range`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/limitranges/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_persistent_volume_claim(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_persistent_volume_claim # noqa: E501
delete a PersistentVolumeClaim # 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_namespaced_persistent_volume_claim(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_persistent_volume_claim_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_persistent_volume_claim_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_persistent_volume_claim # noqa: E501
delete a PersistentVolumeClaim # 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_namespaced_persistent_volume_claim_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeClaim, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_persistent_volume_claim" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_persistent_volume_claim`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_persistent_volume_claim`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeClaim', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_pod(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_pod # noqa: E501
delete a Pod # 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_namespaced_pod(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_pod_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_pod_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_pod # noqa: E501
delete a Pod # 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_namespaced_pod_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_pod" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_pod`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_pod`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_pod_template(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_pod_template # noqa: E501
delete a PodTemplate # 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_namespaced_pod_template(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodTemplate (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PodTemplate
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_pod_template_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_pod_template_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_pod_template # noqa: E501
delete a PodTemplate # 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_namespaced_pod_template_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodTemplate (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PodTemplate, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_pod_template" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_pod_template`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_pod_template`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/podtemplates/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PodTemplate', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_replication_controller(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_replication_controller # noqa: E501
delete a ReplicationController # 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_namespaced_replication_controller(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_replication_controller_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_replication_controller_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_replication_controller # noqa: E501
delete a ReplicationController # 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_namespaced_replication_controller_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_replication_controller" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_replication_controller`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_replication_controller`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_resource_quota(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_resource_quota # noqa: E501
delete a ResourceQuota # 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_namespaced_resource_quota(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_resource_quota_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_resource_quota_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_resource_quota # noqa: E501
delete a ResourceQuota # 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_namespaced_resource_quota_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ResourceQuota, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_resource_quota" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_resource_quota`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_resource_quota`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/resourcequotas/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ResourceQuota', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_secret(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_secret # noqa: E501
delete a Secret # 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_namespaced_secret(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Secret (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_secret_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_secret_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_secret # noqa: E501
delete a Secret # 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_namespaced_secret_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Secret (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_secret" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_secret`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_secret`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/secrets/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_service(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_service # noqa: E501
delete a Service # 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_namespaced_service(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_service_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_service_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_service # noqa: E501
delete a Service # 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_namespaced_service_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Service, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_service" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_service`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_service`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Service', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_service_account(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_service_account # noqa: E501
delete a ServiceAccount # 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_namespaced_service_account(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceAccount (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ServiceAccount
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_namespaced_service_account_with_http_info(name, namespace, **kwargs) # noqa: E501
def delete_namespaced_service_account_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_service_account # noqa: E501
delete a ServiceAccount # 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_namespaced_service_account_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceAccount (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ServiceAccount, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_service_account" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_service_account`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_service_account`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/serviceaccounts/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ServiceAccount', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_node(self, name, **kwargs): # noqa: E501
"""delete_node # noqa: E501
delete a Node # 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_node(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_node_with_http_info(name, **kwargs) # noqa: E501
def delete_node_with_http_info(self, name, **kwargs): # noqa: E501
"""delete_node # noqa: E501
delete a Node # 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_node_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_node" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_node`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_persistent_volume(self, name, **kwargs): # noqa: E501
"""delete_persistent_volume # noqa: E501
delete a PersistentVolume # 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_persistent_volume(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.delete_persistent_volume_with_http_info(name, **kwargs) # noqa: E501
def delete_persistent_volume_with_http_info(self, name, **kwargs): # noqa: E501
"""delete_persistent_volume # noqa: E501
delete a PersistentVolume # 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_persistent_volume_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:param V1DeleteOptions body:
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolume, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'pretty',
'dry_run',
'grace_period_seconds',
'orphan_dependents',
'propagation_policy',
'body'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_persistent_volume" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `delete_persistent_volume`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501
query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501
if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501
query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501
if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501
query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumes/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolume', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def get_api_resources(self, **kwargs): # noqa: E501
"""get_api_resources # noqa: E501
get available resources # 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_api_resources(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1APIResourceList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.get_api_resources_with_http_info(**kwargs) # noqa: E501
def get_api_resources_with_http_info(self, **kwargs): # noqa: E501
"""get_api_resources # noqa: E501
get available resources # 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_api_resources_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1APIResourceList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method get_api_resources" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1APIResourceList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_component_status(self, **kwargs): # noqa: E501
"""list_component_status # noqa: E501
list objects of kind ComponentStatus # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_component_status(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ComponentStatusList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_component_status_with_http_info(**kwargs) # noqa: E501
def list_component_status_with_http_info(self, **kwargs): # noqa: E501
"""list_component_status # noqa: E501
list objects of kind ComponentStatus # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_component_status_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ComponentStatusList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_component_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/componentstatuses', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ComponentStatusList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_config_map_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_config_map_for_all_namespaces # noqa: E501
list or watch objects of kind ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_config_map_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ConfigMapList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_config_map_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_config_map_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_config_map_for_all_namespaces # noqa: E501
list or watch objects of kind ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_config_map_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ConfigMapList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_config_map_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/configmaps', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ConfigMapList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_endpoints_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_endpoints_for_all_namespaces # noqa: E501
list or watch objects of kind Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_endpoints_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1EndpointsList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_endpoints_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_endpoints_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_endpoints_for_all_namespaces # noqa: E501
list or watch objects of kind Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_endpoints_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1EndpointsList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_endpoints_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/endpoints', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1EndpointsList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_event_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_event_for_all_namespaces # noqa: E501
list or watch objects of kind Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_event_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: CoreV1EventList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_event_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_event_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_event_for_all_namespaces # noqa: E501
list or watch objects of kind Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_event_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(CoreV1EventList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_event_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/events', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CoreV1EventList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_limit_range_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_limit_range_for_all_namespaces # noqa: E501
list or watch objects of kind LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_limit_range_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1LimitRangeList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_limit_range_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_limit_range_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_limit_range_for_all_namespaces # noqa: E501
list or watch objects of kind LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_limit_range_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1LimitRangeList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_limit_range_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/limitranges', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1LimitRangeList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespace(self, **kwargs): # noqa: E501
"""list_namespace # noqa: E501
list or watch objects of kind Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespace(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1NamespaceList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespace_with_http_info(**kwargs) # noqa: E501
def list_namespace_with_http_info(self, **kwargs): # noqa: E501
"""list_namespace # noqa: E501
list or watch objects of kind Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespace_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1NamespaceList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespace" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1NamespaceList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_config_map(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_config_map # noqa: E501
list or watch objects of kind ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_config_map(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ConfigMapList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_config_map_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_config_map_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_config_map # noqa: E501
list or watch objects of kind ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_config_map_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ConfigMapList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_config_map" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_config_map`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/configmaps', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ConfigMapList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_endpoints(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_endpoints # noqa: E501
list or watch objects of kind Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_endpoints(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1EndpointsList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_endpoints_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_endpoints_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_endpoints # noqa: E501
list or watch objects of kind Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_endpoints_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1EndpointsList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_endpoints" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_endpoints`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/endpoints', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1EndpointsList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_event(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_event # noqa: E501
list or watch objects of kind Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_event(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: CoreV1EventList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_event_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_event_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_event # noqa: E501
list or watch objects of kind Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_event_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(CoreV1EventList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/events', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CoreV1EventList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_limit_range(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_limit_range # noqa: E501
list or watch objects of kind LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_limit_range(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1LimitRangeList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_limit_range_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_limit_range_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_limit_range # noqa: E501
list or watch objects of kind LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_limit_range_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1LimitRangeList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_limit_range" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_limit_range`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/limitranges', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1LimitRangeList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_persistent_volume_claim(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_persistent_volume_claim # noqa: E501
list or watch objects of kind PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_persistent_volume_claim(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeClaimList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_persistent_volume_claim_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_persistent_volume_claim_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_persistent_volume_claim # noqa: E501
list or watch objects of kind PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_persistent_volume_claim_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeClaimList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_persistent_volume_claim" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_persistent_volume_claim`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/persistentvolumeclaims', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeClaimList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_pod(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_pod # noqa: E501
list or watch objects of kind Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_pod(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PodList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_pod_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_pod_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_pod # noqa: E501
list or watch objects of kind Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_pod_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PodList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_pod" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_pod`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PodList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_pod_template(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_pod_template # noqa: E501
list or watch objects of kind PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_pod_template(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PodTemplateList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_pod_template_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_pod_template_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_pod_template # noqa: E501
list or watch objects of kind PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_pod_template_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PodTemplateList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_pod_template" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_pod_template`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/podtemplates', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PodTemplateList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_replication_controller(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_replication_controller # noqa: E501
list or watch objects of kind ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_replication_controller(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ReplicationControllerList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_replication_controller_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_replication_controller_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_replication_controller # noqa: E501
list or watch objects of kind ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_replication_controller_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ReplicationControllerList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_replication_controller" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_replication_controller`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ReplicationControllerList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_resource_quota(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_resource_quota # noqa: E501
list or watch objects of kind ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_resource_quota(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ResourceQuotaList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_resource_quota_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_resource_quota_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_resource_quota # noqa: E501
list or watch objects of kind ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_resource_quota_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ResourceQuotaList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_resource_quota" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_resource_quota`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/resourcequotas', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ResourceQuotaList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_secret(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_secret # noqa: E501
list or watch objects of kind Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_secret(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1SecretList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_secret_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_secret_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_secret # noqa: E501
list or watch objects of kind Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_secret_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1SecretList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_secret" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_secret`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/secrets', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1SecretList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_service(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_service # noqa: E501
list or watch objects of kind Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_service(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ServiceList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_service_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_service_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_service # noqa: E501
list or watch objects of kind Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_service_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ServiceList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_service" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_service`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ServiceList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_service_account(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_service_account # noqa: E501
list or watch objects of kind ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_service_account(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ServiceAccountList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_namespaced_service_account_with_http_info(namespace, **kwargs) # noqa: E501
def list_namespaced_service_account_with_http_info(self, namespace, **kwargs): # noqa: E501
"""list_namespaced_service_account # noqa: E501
list or watch objects of kind ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_service_account_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ServiceAccountList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'namespace',
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_service_account" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_service_account`") # noqa: E501
collection_formats = {}
path_params = {}
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/serviceaccounts', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ServiceAccountList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_node(self, **kwargs): # noqa: E501
"""list_node # noqa: E501
list or watch objects of kind Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_node(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1NodeList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_node_with_http_info(**kwargs) # noqa: E501
def list_node_with_http_info(self, **kwargs): # noqa: E501
"""list_node # noqa: E501
list or watch objects of kind Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_node_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1NodeList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_node" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1NodeList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_persistent_volume(self, **kwargs): # noqa: E501
"""list_persistent_volume # noqa: E501
list or watch objects of kind PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_persistent_volume(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_persistent_volume_with_http_info(**kwargs) # noqa: E501
def list_persistent_volume_with_http_info(self, **kwargs): # noqa: E501
"""list_persistent_volume # noqa: E501
list or watch objects of kind PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_persistent_volume_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str pretty: If 'true', then the output is pretty printed.
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'pretty',
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_persistent_volume" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumes', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_persistent_volume_claim_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_persistent_volume_claim_for_all_namespaces # noqa: E501
list or watch objects of kind PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_persistent_volume_claim_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeClaimList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_persistent_volume_claim_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_persistent_volume_claim_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_persistent_volume_claim_for_all_namespaces # noqa: E501
list or watch objects of kind PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_persistent_volume_claim_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeClaimList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_persistent_volume_claim_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumeclaims', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeClaimList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_pod_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_pod_for_all_namespaces # noqa: E501
list or watch objects of kind Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_pod_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PodList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_pod_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_pod_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_pod_for_all_namespaces # noqa: E501
list or watch objects of kind Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_pod_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PodList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_pod_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/pods', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PodList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_pod_template_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_pod_template_for_all_namespaces # noqa: E501
list or watch objects of kind PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_pod_template_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PodTemplateList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_pod_template_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_pod_template_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_pod_template_for_all_namespaces # noqa: E501
list or watch objects of kind PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_pod_template_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PodTemplateList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_pod_template_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/podtemplates', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PodTemplateList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_replication_controller_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_replication_controller_for_all_namespaces # noqa: E501
list or watch objects of kind ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_replication_controller_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ReplicationControllerList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_replication_controller_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_replication_controller_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_replication_controller_for_all_namespaces # noqa: E501
list or watch objects of kind ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_replication_controller_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ReplicationControllerList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_replication_controller_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/replicationcontrollers', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ReplicationControllerList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_resource_quota_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_resource_quota_for_all_namespaces # noqa: E501
list or watch objects of kind ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_resource_quota_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ResourceQuotaList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_resource_quota_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_resource_quota_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_resource_quota_for_all_namespaces # noqa: E501
list or watch objects of kind ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_resource_quota_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ResourceQuotaList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_resource_quota_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/resourcequotas', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ResourceQuotaList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_secret_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_secret_for_all_namespaces # noqa: E501
list or watch objects of kind Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_secret_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1SecretList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_secret_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_secret_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_secret_for_all_namespaces # noqa: E501
list or watch objects of kind Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_secret_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1SecretList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_secret_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/secrets', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1SecretList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_service_account_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_service_account_for_all_namespaces # noqa: E501
list or watch objects of kind ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_service_account_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ServiceAccountList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_service_account_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_service_account_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_service_account_for_all_namespaces # noqa: E501
list or watch objects of kind ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_service_account_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ServiceAccountList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_service_account_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/serviceaccounts', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ServiceAccountList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def list_service_for_all_namespaces(self, **kwargs): # noqa: E501
"""list_service_for_all_namespaces # noqa: E501
list or watch objects of kind Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_service_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ServiceList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.list_service_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
def list_service_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501
"""list_service_for_all_namespaces # noqa: E501
list or watch objects of kind Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_service_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset
:param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ServiceList, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'allow_watch_bookmarks',
'_continue',
'field_selector',
'label_selector',
'limit',
'pretty',
'resource_version',
'resource_version_match',
'send_initial_events',
'timeout_seconds',
'watch'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method list_service_for_all_namespaces" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501
query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501
if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501
query_params.append(('continue', local_var_params['_continue'])) # noqa: E501
if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501
query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501
if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501
query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501
if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501
query_params.append(('limit', local_var_params['limit'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501
query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501
if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501
query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501
if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501
query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501
if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501
query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501
if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501
query_params.append(('watch', local_var_params['watch'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/services', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ServiceList', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespace(self, name, body, **kwargs): # noqa: E501
"""patch_namespace # noqa: E501
partially update the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespace(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespace_with_http_info(name, body, **kwargs) # noqa: E501
def patch_namespace_with_http_info(self, name, body, **kwargs): # noqa: E501
"""patch_namespace # noqa: E501
partially update the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespace_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Namespace, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespace" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespace`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespace`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Namespace', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespace_status(self, name, body, **kwargs): # noqa: E501
"""patch_namespace_status # noqa: E501
partially update status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespace_status(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespace_status_with_http_info(name, body, **kwargs) # noqa: E501
def patch_namespace_status_with_http_info(self, name, body, **kwargs): # noqa: E501
"""patch_namespace_status # noqa: E501
partially update status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespace_status_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Namespace, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespace_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespace_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespace_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Namespace', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_config_map(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_config_map # noqa: E501
partially update the specified ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_config_map(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ConfigMap (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ConfigMap
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_config_map_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_config_map_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_config_map # noqa: E501
partially update the specified ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_config_map_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ConfigMap (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ConfigMap, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_config_map" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_config_map`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_config_map`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_config_map`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/configmaps/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ConfigMap', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_endpoints(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_endpoints # noqa: E501
partially update the specified Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_endpoints(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Endpoints (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Endpoints
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_endpoints_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_endpoints_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_endpoints # noqa: E501
partially update the specified Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_endpoints_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Endpoints (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Endpoints, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_endpoints" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_endpoints`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_endpoints`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_endpoints`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/endpoints/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Endpoints', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_event(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_event # noqa: E501
partially update the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_event(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: CoreV1Event
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_event_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_event_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_event # noqa: E501
partially update the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_event_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(CoreV1Event, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_event`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_event`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/events/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CoreV1Event', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_limit_range(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_limit_range # noqa: E501
partially update the specified LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_limit_range(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the LimitRange (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1LimitRange
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_limit_range_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_limit_range_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_limit_range # noqa: E501
partially update the specified LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_limit_range_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the LimitRange (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1LimitRange, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_limit_range" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_limit_range`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_limit_range`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_limit_range`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/limitranges/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1LimitRange', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_persistent_volume_claim(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_persistent_volume_claim # noqa: E501
partially update the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_persistent_volume_claim(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_persistent_volume_claim_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_persistent_volume_claim_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_persistent_volume_claim # noqa: E501
partially update the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_persistent_volume_claim_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeClaim, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_persistent_volume_claim" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_persistent_volume_claim`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_persistent_volume_claim`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_persistent_volume_claim`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeClaim', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_persistent_volume_claim_status(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_persistent_volume_claim_status # noqa: E501
partially update status of the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_persistent_volume_claim_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_persistent_volume_claim_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_persistent_volume_claim_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_persistent_volume_claim_status # noqa: E501
partially update status of the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_persistent_volume_claim_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeClaim, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_persistent_volume_claim_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_persistent_volume_claim_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_persistent_volume_claim_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_persistent_volume_claim_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeClaim', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_pod(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_pod # noqa: E501
partially update the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_pod(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_pod_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_pod_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_pod # noqa: E501
partially update the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_pod_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_pod" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_pod`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_pod`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_pod`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_pod_ephemeralcontainers(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_pod_ephemeralcontainers # noqa: E501
partially update ephemeralcontainers of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_pod_ephemeralcontainers(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_pod_ephemeralcontainers_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_pod_ephemeralcontainers_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_pod_ephemeralcontainers # noqa: E501
partially update ephemeralcontainers of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_pod_ephemeralcontainers_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_pod_ephemeralcontainers" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_pod_ephemeralcontainers`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_pod_ephemeralcontainers`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_pod_ephemeralcontainers`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/ephemeralcontainers', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_pod_status(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_pod_status # noqa: E501
partially update status of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_pod_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_pod_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_pod_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_pod_status # noqa: E501
partially update status of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_pod_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_pod_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_pod_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_pod_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_pod_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_pod_template(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_pod_template # noqa: E501
partially update the specified PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_pod_template(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodTemplate (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PodTemplate
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_pod_template_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_pod_template_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_pod_template # noqa: E501
partially update the specified PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_pod_template_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodTemplate (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PodTemplate, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_pod_template" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_pod_template`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_pod_template`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_pod_template`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/podtemplates/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PodTemplate', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_replication_controller(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_replication_controller # noqa: E501
partially update the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_replication_controller(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_replication_controller_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_replication_controller_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_replication_controller # noqa: E501
partially update the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_replication_controller_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ReplicationController, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_replication_controller" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_replication_controller`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_replication_controller`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_replication_controller`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ReplicationController', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_replication_controller_scale(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_replication_controller_scale # noqa: E501
partially update scale of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_replication_controller_scale(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Scale
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_replication_controller_scale_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_replication_controller_scale_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_replication_controller_scale # noqa: E501
partially update scale of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_replication_controller_scale_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_replication_controller_scale" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_replication_controller_scale`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_replication_controller_scale`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_replication_controller_scale`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers/{name}/scale', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Scale', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_replication_controller_status(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_replication_controller_status # noqa: E501
partially update status of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_replication_controller_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_replication_controller_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_replication_controller_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_replication_controller_status # noqa: E501
partially update status of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_replication_controller_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ReplicationController, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_replication_controller_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_replication_controller_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_replication_controller_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_replication_controller_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ReplicationController', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_resource_quota(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_resource_quota # noqa: E501
partially update the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_resource_quota(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_resource_quota_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_resource_quota_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_resource_quota # noqa: E501
partially update the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_resource_quota_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ResourceQuota, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_resource_quota" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_resource_quota`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_resource_quota`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_resource_quota`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/resourcequotas/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ResourceQuota', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_resource_quota_status(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_resource_quota_status # noqa: E501
partially update status of the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_resource_quota_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_resource_quota_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_resource_quota_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_resource_quota_status # noqa: E501
partially update status of the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_resource_quota_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ResourceQuota, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_resource_quota_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_resource_quota_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_resource_quota_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_resource_quota_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/resourcequotas/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ResourceQuota', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_secret(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_secret # noqa: E501
partially update the specified Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_secret(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Secret (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Secret
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_secret_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_secret_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_secret # noqa: E501
partially update the specified Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_secret_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Secret (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Secret, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_secret" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_secret`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_secret`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_secret`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/secrets/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Secret', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_service(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_service # noqa: E501
partially update the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_service(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_service_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_service_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_service # noqa: E501
partially update the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_service_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Service, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_service" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_service`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_service`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_service`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Service', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_service_account(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_service_account # noqa: E501
partially update the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_service_account(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceAccount (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ServiceAccount
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_service_account_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_service_account_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_service_account # noqa: E501
partially update the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_service_account_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceAccount (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ServiceAccount, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_service_account" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_service_account`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_service_account`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_service_account`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/serviceaccounts/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ServiceAccount', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_service_status(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_service_status # noqa: E501
partially update status of the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_service_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_namespaced_service_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def patch_namespaced_service_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_service_status # noqa: E501
partially update status of the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_service_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Service, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_service_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_service_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_service_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_service_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Service', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_node(self, name, body, **kwargs): # noqa: E501
"""patch_node # noqa: E501
partially update the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_node(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_node_with_http_info(name, body, **kwargs) # noqa: E501
def patch_node_with_http_info(self, name, body, **kwargs): # noqa: E501
"""patch_node # noqa: E501
partially update the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_node_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Node, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_node" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_node`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_node`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Node', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_node_status(self, name, body, **kwargs): # noqa: E501
"""patch_node_status # noqa: E501
partially update status of the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_node_status(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_node_status_with_http_info(name, body, **kwargs) # noqa: E501
def patch_node_status_with_http_info(self, name, body, **kwargs): # noqa: E501
"""patch_node_status # noqa: E501
partially update status of the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_node_status_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Node, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_node_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_node_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_node_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Node', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_persistent_volume(self, name, body, **kwargs): # noqa: E501
"""patch_persistent_volume # noqa: E501
partially update the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_persistent_volume(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_persistent_volume_with_http_info(name, body, **kwargs) # noqa: E501
def patch_persistent_volume_with_http_info(self, name, body, **kwargs): # noqa: E501
"""patch_persistent_volume # noqa: E501
partially update the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_persistent_volume_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolume, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_persistent_volume" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_persistent_volume`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_persistent_volume`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumes/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolume', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_persistent_volume_status(self, name, body, **kwargs): # noqa: E501
"""patch_persistent_volume_status # noqa: E501
partially update status of the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_persistent_volume_status(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.patch_persistent_volume_status_with_http_info(name, body, **kwargs) # noqa: E501
def patch_persistent_volume_status_with_http_info(self, name, body, **kwargs): # noqa: E501
"""patch_persistent_volume_status # noqa: E501
partially update status of the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_persistent_volume_status_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolume, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation',
'force'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_persistent_volume_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `patch_persistent_volume_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `patch_persistent_volume_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501
query_params.append(('force', local_var_params['force'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumes/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolume', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_component_status(self, name, **kwargs): # noqa: E501
"""read_component_status # noqa: E501
read the specified ComponentStatus # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_component_status(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ComponentStatus (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ComponentStatus
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_component_status_with_http_info(name, **kwargs) # noqa: E501
def read_component_status_with_http_info(self, name, **kwargs): # noqa: E501
"""read_component_status # noqa: E501
read the specified ComponentStatus # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_component_status_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ComponentStatus (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ComponentStatus, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_component_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_component_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/componentstatuses/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ComponentStatus', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespace(self, name, **kwargs): # noqa: E501
"""read_namespace # noqa: E501
read the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespace(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespace_with_http_info(name, **kwargs) # noqa: E501
def read_namespace_with_http_info(self, name, **kwargs): # noqa: E501
"""read_namespace # noqa: E501
read the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespace_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Namespace, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespace" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespace`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Namespace', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespace_status(self, name, **kwargs): # noqa: E501
"""read_namespace_status # noqa: E501
read status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespace_status(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespace_status_with_http_info(name, **kwargs) # noqa: E501
def read_namespace_status_with_http_info(self, name, **kwargs): # noqa: E501
"""read_namespace_status # noqa: E501
read status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespace_status_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Namespace, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespace_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespace_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Namespace', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_config_map(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_config_map # noqa: E501
read the specified ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_config_map(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ConfigMap (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ConfigMap
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_config_map_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_config_map_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_config_map # noqa: E501
read the specified ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_config_map_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ConfigMap (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ConfigMap, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_config_map" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_config_map`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_config_map`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/configmaps/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ConfigMap', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_endpoints(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_endpoints # noqa: E501
read the specified Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_endpoints(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Endpoints (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Endpoints
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_endpoints_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_endpoints_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_endpoints # noqa: E501
read the specified Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_endpoints_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Endpoints (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Endpoints, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_endpoints" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_endpoints`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_endpoints`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/endpoints/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Endpoints', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_event(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_event # noqa: E501
read the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_event(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: CoreV1Event
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_event_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_event_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_event # noqa: E501
read the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_event_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(CoreV1Event, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_event`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/events/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CoreV1Event', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_limit_range(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_limit_range # noqa: E501
read the specified LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_limit_range(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the LimitRange (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1LimitRange
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_limit_range_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_limit_range_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_limit_range # noqa: E501
read the specified LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_limit_range_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the LimitRange (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1LimitRange, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_limit_range" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_limit_range`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_limit_range`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/limitranges/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1LimitRange', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_persistent_volume_claim(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_persistent_volume_claim # noqa: E501
read the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_persistent_volume_claim(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_persistent_volume_claim_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_persistent_volume_claim_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_persistent_volume_claim # noqa: E501
read the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_persistent_volume_claim_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeClaim, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_persistent_volume_claim" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_persistent_volume_claim`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_persistent_volume_claim`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeClaim', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_persistent_volume_claim_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_persistent_volume_claim_status # noqa: E501
read status of the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_persistent_volume_claim_status(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_persistent_volume_claim_status_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_persistent_volume_claim_status_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_persistent_volume_claim_status # noqa: E501
read status of the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_persistent_volume_claim_status_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeClaim, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_persistent_volume_claim_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_persistent_volume_claim_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_persistent_volume_claim_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeClaim', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_pod(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod # noqa: E501
read the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_pod_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_pod_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod # noqa: E501
read the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_pod" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_pod`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_pod`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_pod_ephemeralcontainers(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_ephemeralcontainers # noqa: E501
read ephemeralcontainers of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_ephemeralcontainers(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_pod_ephemeralcontainers_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_pod_ephemeralcontainers_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_ephemeralcontainers # noqa: E501
read ephemeralcontainers of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_ephemeralcontainers_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_pod_ephemeralcontainers" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_pod_ephemeralcontainers`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_pod_ephemeralcontainers`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/ephemeralcontainers', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_pod_log(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_log # noqa: E501
read log of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_log(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str container: The container for which to stream logs. Defaults to only container if there is one container in the pod.
:param bool follow: Follow the log stream of the pod. Defaults to false.
:param bool insecure_skip_tls_verify_backend: insecureSkipTLSVerifyBackend indicates that the apiserver should not confirm the validity of the serving certificate of the backend it is connecting to. This will make the HTTPS connection between the apiserver and the backend insecure. This means the apiserver cannot verify the log data it is receiving came from the real kubelet. If the kubelet is configured to verify the apiserver's TLS credentials, it does not mean the connection to the real kubelet is vulnerable to a man in the middle attack (e.g. an attacker could not intercept the actual log data coming from the real kubelet).
:param int limit_bytes: If set, the number of bytes to read from the server before terminating the log output. This may not display a complete final line of logging, and may return slightly more or slightly less than the specified limit.
:param str pretty: If 'true', then the output is pretty printed.
:param bool previous: Return previous terminated container logs. Defaults to false.
:param int since_seconds: A relative time in seconds before the current time from which to show logs. If this value precedes the time a pod was started, only logs since the pod start will be returned. If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified.
:param int tail_lines: If set, the number of lines from the end of the logs to show. If not specified, logs are shown from the creation of the container or sinceSeconds or sinceTime
:param bool timestamps: If true, add an RFC3339 or RFC3339Nano timestamp at the beginning of every line of log output. Defaults to false.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_pod_log_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_pod_log_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_log # noqa: E501
read log of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_log_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str container: The container for which to stream logs. Defaults to only container if there is one container in the pod.
:param bool follow: Follow the log stream of the pod. Defaults to false.
:param bool insecure_skip_tls_verify_backend: insecureSkipTLSVerifyBackend indicates that the apiserver should not confirm the validity of the serving certificate of the backend it is connecting to. This will make the HTTPS connection between the apiserver and the backend insecure. This means the apiserver cannot verify the log data it is receiving came from the real kubelet. If the kubelet is configured to verify the apiserver's TLS credentials, it does not mean the connection to the real kubelet is vulnerable to a man in the middle attack (e.g. an attacker could not intercept the actual log data coming from the real kubelet).
:param int limit_bytes: If set, the number of bytes to read from the server before terminating the log output. This may not display a complete final line of logging, and may return slightly more or slightly less than the specified limit.
:param str pretty: If 'true', then the output is pretty printed.
:param bool previous: Return previous terminated container logs. Defaults to false.
:param int since_seconds: A relative time in seconds before the current time from which to show logs. If this value precedes the time a pod was started, only logs since the pod start will be returned. If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified.
:param int tail_lines: If set, the number of lines from the end of the logs to show. If not specified, logs are shown from the creation of the container or sinceSeconds or sinceTime
:param bool timestamps: If true, add an RFC3339 or RFC3339Nano timestamp at the beginning of every line of log output. Defaults to false.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(str, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'container',
'follow',
'insecure_skip_tls_verify_backend',
'limit_bytes',
'pretty',
'previous',
'since_seconds',
'tail_lines',
'timestamps'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_pod_log" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_pod_log`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_pod_log`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'container' in local_var_params and local_var_params['container'] is not None: # noqa: E501
query_params.append(('container', local_var_params['container'])) # noqa: E501
if 'follow' in local_var_params and local_var_params['follow'] is not None: # noqa: E501
query_params.append(('follow', local_var_params['follow'])) # noqa: E501
if 'insecure_skip_tls_verify_backend' in local_var_params and local_var_params['insecure_skip_tls_verify_backend'] is not None: # noqa: E501
query_params.append(('insecureSkipTLSVerifyBackend', local_var_params['insecure_skip_tls_verify_backend'])) # noqa: E501
if 'limit_bytes' in local_var_params and local_var_params['limit_bytes'] is not None: # noqa: E501
query_params.append(('limitBytes', local_var_params['limit_bytes'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'previous' in local_var_params and local_var_params['previous'] is not None: # noqa: E501
query_params.append(('previous', local_var_params['previous'])) # noqa: E501
if 'since_seconds' in local_var_params and local_var_params['since_seconds'] is not None: # noqa: E501
query_params.append(('sinceSeconds', local_var_params['since_seconds'])) # noqa: E501
if 'tail_lines' in local_var_params and local_var_params['tail_lines'] is not None: # noqa: E501
query_params.append(('tailLines', local_var_params['tail_lines'])) # noqa: E501
if 'timestamps' in local_var_params and local_var_params['timestamps'] is not None: # noqa: E501
query_params.append(('timestamps', local_var_params['timestamps'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['text/plain', 'application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/log', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_pod_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_status # noqa: E501
read status of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_status(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_pod_status_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_pod_status_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_status # noqa: E501
read status of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_status_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_pod_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_pod_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_pod_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_pod_template(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_template # noqa: E501
read the specified PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_template(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodTemplate (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PodTemplate
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_pod_template_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_pod_template_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_template # noqa: E501
read the specified PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_template_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodTemplate (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PodTemplate, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_pod_template" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_pod_template`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_pod_template`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/podtemplates/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PodTemplate', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_replication_controller(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller # noqa: E501
read the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replication_controller(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_replication_controller_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_replication_controller_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller # noqa: E501
read the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replication_controller_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ReplicationController, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_replication_controller" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_replication_controller`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_replication_controller`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ReplicationController', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_replication_controller_scale(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller_scale # noqa: E501
read scale of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replication_controller_scale(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Scale
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_replication_controller_scale_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_replication_controller_scale_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller_scale # noqa: E501
read scale of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replication_controller_scale_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_replication_controller_scale" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_replication_controller_scale`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_replication_controller_scale`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers/{name}/scale', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Scale', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_replication_controller_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller_status # noqa: E501
read status of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replication_controller_status(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_replication_controller_status_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_replication_controller_status_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller_status # noqa: E501
read status of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replication_controller_status_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ReplicationController, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_replication_controller_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_replication_controller_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_replication_controller_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ReplicationController', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_resource_quota(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_resource_quota # noqa: E501
read the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_resource_quota(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_resource_quota_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_resource_quota_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_resource_quota # noqa: E501
read the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_resource_quota_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ResourceQuota, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_resource_quota" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_resource_quota`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_resource_quota`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/resourcequotas/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ResourceQuota', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_resource_quota_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_resource_quota_status # noqa: E501
read status of the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_resource_quota_status(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_resource_quota_status_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_resource_quota_status_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_resource_quota_status # noqa: E501
read status of the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_resource_quota_status_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ResourceQuota, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_resource_quota_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_resource_quota_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_resource_quota_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/resourcequotas/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ResourceQuota', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_secret(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_secret # noqa: E501
read the specified Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_secret(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Secret (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Secret
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_secret_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_secret_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_secret # noqa: E501
read the specified Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_secret_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Secret (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Secret, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_secret" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_secret`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_secret`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/secrets/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Secret', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_service(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_service # noqa: E501
read the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_service(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_service_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_service_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_service # noqa: E501
read the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_service_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Service, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_service" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_service`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_service`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Service', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_service_account(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_service_account # noqa: E501
read the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_service_account(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceAccount (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ServiceAccount
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_service_account_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_service_account_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_service_account # noqa: E501
read the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_service_account_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceAccount (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ServiceAccount, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_service_account" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_service_account`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_service_account`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/serviceaccounts/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ServiceAccount', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_service_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_service_status # noqa: E501
read status of the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_service_status(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_namespaced_service_status_with_http_info(name, namespace, **kwargs) # noqa: E501
def read_namespaced_service_status_with_http_info(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_service_status # noqa: E501
read status of the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_service_status_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Service, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_service_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_service_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_service_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Service', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_node(self, name, **kwargs): # noqa: E501
"""read_node # noqa: E501
read the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_node(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_node_with_http_info(name, **kwargs) # noqa: E501
def read_node_with_http_info(self, name, **kwargs): # noqa: E501
"""read_node # noqa: E501
read the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_node_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Node, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_node" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_node`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Node', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_node_status(self, name, **kwargs): # noqa: E501
"""read_node_status # noqa: E501
read status of the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_node_status(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_node_status_with_http_info(name, **kwargs) # noqa: E501
def read_node_status_with_http_info(self, name, **kwargs): # noqa: E501
"""read_node_status # noqa: E501
read status of the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_node_status_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Node, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_node_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_node_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Node', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_persistent_volume(self, name, **kwargs): # noqa: E501
"""read_persistent_volume # noqa: E501
read the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_persistent_volume(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_persistent_volume_with_http_info(name, **kwargs) # noqa: E501
def read_persistent_volume_with_http_info(self, name, **kwargs): # noqa: E501
"""read_persistent_volume # noqa: E501
read the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_persistent_volume_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolume, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_persistent_volume" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_persistent_volume`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumes/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolume', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def read_persistent_volume_status(self, name, **kwargs): # noqa: E501
"""read_persistent_volume_status # noqa: E501
read status of the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_persistent_volume_status(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.read_persistent_volume_status_with_http_info(name, **kwargs) # noqa: E501
def read_persistent_volume_status_with_http_info(self, name, **kwargs): # noqa: E501
"""read_persistent_volume_status # noqa: E501
read status of the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_persistent_volume_status_with_http_info(name, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolume, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method read_persistent_volume_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `read_persistent_volume_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumes/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolume', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespace(self, name, body, **kwargs): # noqa: E501
"""replace_namespace # noqa: E501
replace the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespace(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param V1Namespace body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespace_with_http_info(name, body, **kwargs) # noqa: E501
def replace_namespace_with_http_info(self, name, body, **kwargs): # noqa: E501
"""replace_namespace # noqa: E501
replace the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespace_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param V1Namespace body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Namespace, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespace" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespace`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespace`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Namespace', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespace_finalize(self, name, body, **kwargs): # noqa: E501
"""replace_namespace_finalize # noqa: E501
replace finalize of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespace_finalize(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param V1Namespace body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param str pretty: If 'true', then the output is pretty printed.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespace_finalize_with_http_info(name, body, **kwargs) # noqa: E501
def replace_namespace_finalize_with_http_info(self, name, body, **kwargs): # noqa: E501
"""replace_namespace_finalize # noqa: E501
replace finalize of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespace_finalize_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param V1Namespace body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param str pretty: If 'true', then the output is pretty printed.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Namespace, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'dry_run',
'field_manager',
'field_validation',
'pretty'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespace_finalize" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespace_finalize`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespace_finalize`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{name}/finalize', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Namespace', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespace_status(self, name, body, **kwargs): # noqa: E501
"""replace_namespace_status # noqa: E501
replace status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespace_status(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param V1Namespace body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespace_status_with_http_info(name, body, **kwargs) # noqa: E501
def replace_namespace_status_with_http_info(self, name, body, **kwargs): # noqa: E501
"""replace_namespace_status # noqa: E501
replace status of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespace_status_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Namespace (required)
:param V1Namespace body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Namespace, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespace_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespace_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespace_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Namespace', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_config_map(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_config_map # noqa: E501
replace the specified ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_config_map(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ConfigMap (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ConfigMap body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ConfigMap
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_config_map_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_config_map_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_config_map # noqa: E501
replace the specified ConfigMap # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_config_map_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ConfigMap (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ConfigMap body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ConfigMap, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_config_map" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_config_map`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_config_map`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_config_map`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/configmaps/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ConfigMap', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_endpoints(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_endpoints # noqa: E501
replace the specified Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_endpoints(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Endpoints (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Endpoints body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Endpoints
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_endpoints_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_endpoints_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_endpoints # noqa: E501
replace the specified Endpoints # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_endpoints_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Endpoints (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Endpoints body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Endpoints, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_endpoints" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_endpoints`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_endpoints`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_endpoints`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/endpoints/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Endpoints', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_event(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_event # noqa: E501
replace the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_event(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param CoreV1Event body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: CoreV1Event
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_event_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_event_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_event # noqa: E501
replace the specified Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_event_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Event (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param CoreV1Event body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(CoreV1Event, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_event" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_event`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_event`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_event`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/events/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CoreV1Event', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_limit_range(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_limit_range # noqa: E501
replace the specified LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_limit_range(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the LimitRange (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1LimitRange body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1LimitRange
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_limit_range_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_limit_range_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_limit_range # noqa: E501
replace the specified LimitRange # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_limit_range_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the LimitRange (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1LimitRange body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1LimitRange, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_limit_range" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_limit_range`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_limit_range`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_limit_range`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/limitranges/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1LimitRange', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_persistent_volume_claim(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_persistent_volume_claim # noqa: E501
replace the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_persistent_volume_claim(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1PersistentVolumeClaim body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_persistent_volume_claim_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_persistent_volume_claim_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_persistent_volume_claim # noqa: E501
replace the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_persistent_volume_claim_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1PersistentVolumeClaim body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeClaim, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_persistent_volume_claim" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_persistent_volume_claim`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_persistent_volume_claim`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_persistent_volume_claim`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeClaim', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_persistent_volume_claim_status(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_persistent_volume_claim_status # noqa: E501
replace status of the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_persistent_volume_claim_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1PersistentVolumeClaim body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_persistent_volume_claim_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_persistent_volume_claim_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_persistent_volume_claim_status # noqa: E501
replace status of the specified PersistentVolumeClaim # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_persistent_volume_claim_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolumeClaim (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1PersistentVolumeClaim body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolumeClaim, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_persistent_volume_claim_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_persistent_volume_claim_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_persistent_volume_claim_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_persistent_volume_claim_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolumeClaim', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_pod(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_pod # noqa: E501
replace the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_pod(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Pod body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_pod_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_pod_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_pod # noqa: E501
replace the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_pod_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Pod body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_pod" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_pod`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_pod`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_pod`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_pod_ephemeralcontainers(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_pod_ephemeralcontainers # noqa: E501
replace ephemeralcontainers of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_pod_ephemeralcontainers(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Pod body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_pod_ephemeralcontainers_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_pod_ephemeralcontainers_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_pod_ephemeralcontainers # noqa: E501
replace ephemeralcontainers of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_pod_ephemeralcontainers_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Pod body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_pod_ephemeralcontainers" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_pod_ephemeralcontainers`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_pod_ephemeralcontainers`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_pod_ephemeralcontainers`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/ephemeralcontainers', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_pod_status(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_pod_status # noqa: E501
replace status of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_pod_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Pod body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_pod_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_pod_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_pod_status # noqa: E501
replace status of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_pod_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Pod (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Pod body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Pod, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_pod_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_pod_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_pod_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_pod_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/pods/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Pod', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_pod_template(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_pod_template # noqa: E501
replace the specified PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_pod_template(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodTemplate (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1PodTemplate body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PodTemplate
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_pod_template_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_pod_template_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_pod_template # noqa: E501
replace the specified PodTemplate # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_pod_template_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PodTemplate (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1PodTemplate body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PodTemplate, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_pod_template" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_pod_template`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_pod_template`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_pod_template`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/podtemplates/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PodTemplate', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_replication_controller(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_replication_controller # noqa: E501
replace the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_replication_controller(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ReplicationController body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_replication_controller_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_replication_controller_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_replication_controller # noqa: E501
replace the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_replication_controller_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ReplicationController body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ReplicationController, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_replication_controller" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_replication_controller`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_replication_controller`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_replication_controller`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ReplicationController', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_replication_controller_scale(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_replication_controller_scale # noqa: E501
replace scale of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_replication_controller_scale(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Scale body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Scale
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_replication_controller_scale_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_replication_controller_scale_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_replication_controller_scale # noqa: E501
replace scale of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_replication_controller_scale_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Scale body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Scale, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_replication_controller_scale" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_replication_controller_scale`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_replication_controller_scale`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_replication_controller_scale`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers/{name}/scale', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Scale', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_replication_controller_status(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_replication_controller_status # noqa: E501
replace status of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_replication_controller_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ReplicationController body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_replication_controller_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_replication_controller_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_replication_controller_status # noqa: E501
replace status of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_replication_controller_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ReplicationController (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ReplicationController body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ReplicationController, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_replication_controller_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_replication_controller_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_replication_controller_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_replication_controller_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/replicationcontrollers/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ReplicationController', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_resource_quota(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_resource_quota # noqa: E501
replace the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_resource_quota(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ResourceQuota body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_resource_quota_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_resource_quota_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_resource_quota # noqa: E501
replace the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_resource_quota_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ResourceQuota body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ResourceQuota, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_resource_quota" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_resource_quota`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_resource_quota`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_resource_quota`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/resourcequotas/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ResourceQuota', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_resource_quota_status(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_resource_quota_status # noqa: E501
replace status of the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_resource_quota_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ResourceQuota body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_resource_quota_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_resource_quota_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_resource_quota_status # noqa: E501
replace status of the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_resource_quota_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ResourceQuota (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ResourceQuota body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ResourceQuota, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_resource_quota_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_resource_quota_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_resource_quota_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_resource_quota_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/resourcequotas/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ResourceQuota', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_secret(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_secret # noqa: E501
replace the specified Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_secret(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Secret (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Secret body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Secret
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_secret_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_secret_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_secret # noqa: E501
replace the specified Secret # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_secret_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Secret (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Secret body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Secret, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_secret" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_secret`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_secret`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_secret`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/secrets/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Secret', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_service(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_service # noqa: E501
replace the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_service(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Service body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_service_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_service_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_service # noqa: E501
replace the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_service_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Service body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Service, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_service" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_service`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_service`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_service`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Service', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_service_account(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_service_account # noqa: E501
replace the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_service_account(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceAccount (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ServiceAccount body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1ServiceAccount
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_service_account_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_service_account_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_service_account # noqa: E501
replace the specified ServiceAccount # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_service_account_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the ServiceAccount (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1ServiceAccount body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1ServiceAccount, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_service_account" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_service_account`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_service_account`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_service_account`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/serviceaccounts/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1ServiceAccount', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_service_status(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_service_status # noqa: E501
replace status of the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_service_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Service body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_namespaced_service_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501
def replace_namespaced_service_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_service_status # noqa: E501
replace status of the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_service_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Service (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1Service body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Service, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'namespace',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_service_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_service_status`") # noqa: E501
# verify the required parameter 'namespace' is set
if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501
local_var_params['namespace'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_service_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_service_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
if 'namespace' in local_var_params:
path_params['namespace'] = local_var_params['namespace'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/namespaces/{namespace}/services/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Service', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_node(self, name, body, **kwargs): # noqa: E501
"""replace_node # noqa: E501
replace the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_node(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param V1Node body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_node_with_http_info(name, body, **kwargs) # noqa: E501
def replace_node_with_http_info(self, name, body, **kwargs): # noqa: E501
"""replace_node # noqa: E501
replace the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_node_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param V1Node body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Node, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_node" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_node`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_node`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Node', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_node_status(self, name, body, **kwargs): # noqa: E501
"""replace_node_status # noqa: E501
replace status of the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_node_status(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param V1Node body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_node_status_with_http_info(name, body, **kwargs) # noqa: E501
def replace_node_status_with_http_info(self, name, body, **kwargs): # noqa: E501
"""replace_node_status # noqa: E501
replace status of the specified Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_node_status_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the Node (required)
:param V1Node body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1Node, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_node_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_node_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_node_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/nodes/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Node', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_persistent_volume(self, name, body, **kwargs): # noqa: E501
"""replace_persistent_volume # noqa: E501
replace the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_persistent_volume(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param V1PersistentVolume body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_persistent_volume_with_http_info(name, body, **kwargs) # noqa: E501
def replace_persistent_volume_with_http_info(self, name, body, **kwargs): # noqa: E501
"""replace_persistent_volume # noqa: E501
replace the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_persistent_volume_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param V1PersistentVolume body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolume, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_persistent_volume" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_persistent_volume`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_persistent_volume`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumes/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolume', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_persistent_volume_status(self, name, body, **kwargs): # noqa: E501
"""replace_persistent_volume_status # noqa: E501
replace status of the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_persistent_volume_status(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param V1PersistentVolume body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_persistent_volume_status_with_http_info(name, body, **kwargs) # noqa: E501
def replace_persistent_volume_status_with_http_info(self, name, body, **kwargs): # noqa: E501
"""replace_persistent_volume_status # noqa: E501
replace status of the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_persistent_volume_status_with_http_info(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param V1PersistentVolume body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(V1PersistentVolume, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = [
'name',
'body',
'pretty',
'dry_run',
'field_manager',
'field_validation'
]
all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout'
]
)
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_persistent_volume_status" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'name' is set
if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501
local_var_params['name'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `name` when calling `replace_persistent_volume_status`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501
local_var_params['body'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `replace_persistent_volume_status`") # noqa: E501
collection_formats = {}
path_params = {}
if 'name' in local_var_params:
path_params['name'] = local_var_params['name'] # noqa: E501
query_params = []
if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501
query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501
if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501
query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501
if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501
query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501
if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501
query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in local_var_params:
body_params = local_var_params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/api/v1/persistentvolumes/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1PersistentVolume', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
|
53d9f714a94b006a450bf653145f70c231219545
|
b049a961f100444dde14599bab06a0a4224d869b
|
/sdk/python/pulumi_azure_native/azurestackhci/v20230301/get_update_run.py
|
95b22cf8afd27a7daa936b8f0858607d629effa6
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
pulumi/pulumi-azure-native
|
b390c88beef8381f9a71ab2bed5571e0dd848e65
|
4c499abe17ec6696ce28477dde1157372896364e
|
refs/heads/master
| 2023-08-30T08:19:41.564780
| 2023-08-28T19:29:04
| 2023-08-28T19:29:04
| 172,386,632
| 107
| 29
|
Apache-2.0
| 2023-09-14T13:17:00
| 2019-02-24T20:30:21
|
Python
|
UTF-8
|
Python
| false
| false
| 11,738
|
py
|
get_update_run.py
|
# coding=utf-8
# *** WARNING: this file was generated by pulumi. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = [
'GetUpdateRunResult',
'AwaitableGetUpdateRunResult',
'get_update_run',
'get_update_run_output',
]
@pulumi.output_type
class GetUpdateRunResult:
"""
Details of an Update run
"""
def __init__(__self__, description=None, duration=None, end_time_utc=None, error_message=None, id=None, last_updated_time=None, last_updated_time_utc=None, location=None, name=None, provisioning_state=None, start_time_utc=None, state=None, status=None, steps=None, system_data=None, time_started=None, type=None):
if description and not isinstance(description, str):
raise TypeError("Expected argument 'description' to be a str")
pulumi.set(__self__, "description", description)
if duration and not isinstance(duration, str):
raise TypeError("Expected argument 'duration' to be a str")
pulumi.set(__self__, "duration", duration)
if end_time_utc and not isinstance(end_time_utc, str):
raise TypeError("Expected argument 'end_time_utc' to be a str")
pulumi.set(__self__, "end_time_utc", end_time_utc)
if error_message and not isinstance(error_message, str):
raise TypeError("Expected argument 'error_message' to be a str")
pulumi.set(__self__, "error_message", error_message)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if last_updated_time and not isinstance(last_updated_time, str):
raise TypeError("Expected argument 'last_updated_time' to be a str")
pulumi.set(__self__, "last_updated_time", last_updated_time)
if last_updated_time_utc and not isinstance(last_updated_time_utc, str):
raise TypeError("Expected argument 'last_updated_time_utc' to be a str")
pulumi.set(__self__, "last_updated_time_utc", last_updated_time_utc)
if location and not isinstance(location, str):
raise TypeError("Expected argument 'location' to be a str")
pulumi.set(__self__, "location", location)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if provisioning_state and not isinstance(provisioning_state, str):
raise TypeError("Expected argument 'provisioning_state' to be a str")
pulumi.set(__self__, "provisioning_state", provisioning_state)
if start_time_utc and not isinstance(start_time_utc, str):
raise TypeError("Expected argument 'start_time_utc' to be a str")
pulumi.set(__self__, "start_time_utc", start_time_utc)
if state and not isinstance(state, str):
raise TypeError("Expected argument 'state' to be a str")
pulumi.set(__self__, "state", state)
if status and not isinstance(status, str):
raise TypeError("Expected argument 'status' to be a str")
pulumi.set(__self__, "status", status)
if steps and not isinstance(steps, list):
raise TypeError("Expected argument 'steps' to be a list")
pulumi.set(__self__, "steps", steps)
if system_data and not isinstance(system_data, dict):
raise TypeError("Expected argument 'system_data' to be a dict")
pulumi.set(__self__, "system_data", system_data)
if time_started and not isinstance(time_started, str):
raise TypeError("Expected argument 'time_started' to be a str")
pulumi.set(__self__, "time_started", time_started)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def description(self) -> Optional[str]:
"""
More detailed description of the step.
"""
return pulumi.get(self, "description")
@property
@pulumi.getter
def duration(self) -> Optional[str]:
"""
Duration of the update run.
"""
return pulumi.get(self, "duration")
@property
@pulumi.getter(name="endTimeUtc")
def end_time_utc(self) -> Optional[str]:
"""
When the step reached a terminal state.
"""
return pulumi.get(self, "end_time_utc")
@property
@pulumi.getter(name="errorMessage")
def error_message(self) -> Optional[str]:
"""
Error message, specified if the step is in a failed state.
"""
return pulumi.get(self, "error_message")
@property
@pulumi.getter
def id(self) -> str:
"""
Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="lastUpdatedTime")
def last_updated_time(self) -> Optional[str]:
"""
Timestamp of the most recently completed step in the update run.
"""
return pulumi.get(self, "last_updated_time")
@property
@pulumi.getter(name="lastUpdatedTimeUtc")
def last_updated_time_utc(self) -> Optional[str]:
"""
Completion time of this step or the last completed sub-step.
"""
return pulumi.get(self, "last_updated_time_utc")
@property
@pulumi.getter
def location(self) -> Optional[str]:
"""
The geo-location where the resource lives
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the resource
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> str:
"""
Provisioning state of the UpdateRuns proxy resource.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="startTimeUtc")
def start_time_utc(self) -> Optional[str]:
"""
When the step started, or empty if it has not started executing.
"""
return pulumi.get(self, "start_time_utc")
@property
@pulumi.getter
def state(self) -> Optional[str]:
"""
State of the update run.
"""
return pulumi.get(self, "state")
@property
@pulumi.getter
def status(self) -> Optional[str]:
"""
Status of the step, bubbled up from the ECE action plan for installation attempts. Values are: 'Success', 'Error', 'InProgress', and 'Unknown status'.
"""
return pulumi.get(self, "status")
@property
@pulumi.getter
def steps(self) -> Optional[Sequence['outputs.StepResponse']]:
"""
Recursive model for child steps of this step.
"""
return pulumi.get(self, "steps")
@property
@pulumi.getter(name="systemData")
def system_data(self) -> 'outputs.SystemDataResponse':
"""
Azure Resource Manager metadata containing createdBy and modifiedBy information.
"""
return pulumi.get(self, "system_data")
@property
@pulumi.getter(name="timeStarted")
def time_started(self) -> Optional[str]:
"""
Timestamp of the update run was started.
"""
return pulumi.get(self, "time_started")
@property
@pulumi.getter
def type(self) -> str:
"""
The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
"""
return pulumi.get(self, "type")
class AwaitableGetUpdateRunResult(GetUpdateRunResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetUpdateRunResult(
description=self.description,
duration=self.duration,
end_time_utc=self.end_time_utc,
error_message=self.error_message,
id=self.id,
last_updated_time=self.last_updated_time,
last_updated_time_utc=self.last_updated_time_utc,
location=self.location,
name=self.name,
provisioning_state=self.provisioning_state,
start_time_utc=self.start_time_utc,
state=self.state,
status=self.status,
steps=self.steps,
system_data=self.system_data,
time_started=self.time_started,
type=self.type)
def get_update_run(cluster_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
update_name: Optional[str] = None,
update_run_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetUpdateRunResult:
"""
Get the Update run for a specified update
:param str cluster_name: The name of the cluster.
:param str resource_group_name: The name of the resource group. The name is case insensitive.
:param str update_name: The name of the Update
:param str update_run_name: The name of the Update Run
"""
__args__ = dict()
__args__['clusterName'] = cluster_name
__args__['resourceGroupName'] = resource_group_name
__args__['updateName'] = update_name
__args__['updateRunName'] = update_run_name
opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)
__ret__ = pulumi.runtime.invoke('azure-native:azurestackhci/v20230301:getUpdateRun', __args__, opts=opts, typ=GetUpdateRunResult).value
return AwaitableGetUpdateRunResult(
description=pulumi.get(__ret__, 'description'),
duration=pulumi.get(__ret__, 'duration'),
end_time_utc=pulumi.get(__ret__, 'end_time_utc'),
error_message=pulumi.get(__ret__, 'error_message'),
id=pulumi.get(__ret__, 'id'),
last_updated_time=pulumi.get(__ret__, 'last_updated_time'),
last_updated_time_utc=pulumi.get(__ret__, 'last_updated_time_utc'),
location=pulumi.get(__ret__, 'location'),
name=pulumi.get(__ret__, 'name'),
provisioning_state=pulumi.get(__ret__, 'provisioning_state'),
start_time_utc=pulumi.get(__ret__, 'start_time_utc'),
state=pulumi.get(__ret__, 'state'),
status=pulumi.get(__ret__, 'status'),
steps=pulumi.get(__ret__, 'steps'),
system_data=pulumi.get(__ret__, 'system_data'),
time_started=pulumi.get(__ret__, 'time_started'),
type=pulumi.get(__ret__, 'type'))
@_utilities.lift_output_func(get_update_run)
def get_update_run_output(cluster_name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
update_name: Optional[pulumi.Input[str]] = None,
update_run_name: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetUpdateRunResult]:
"""
Get the Update run for a specified update
:param str cluster_name: The name of the cluster.
:param str resource_group_name: The name of the resource group. The name is case insensitive.
:param str update_name: The name of the Update
:param str update_run_name: The name of the Update Run
"""
...
|
9a12ea3e83059c11508821862f9de4e48ad521d7
|
e7efae2b83216d9621bd93390959d652de779c3d
|
/snmp/datadog_checks/snmp/config.py
|
45ef331897e1e97636c6f62ca6a91407f386c435
|
[
"BSD-3-Clause",
"MIT",
"BSD-3-Clause-Modification",
"Unlicense",
"Apache-2.0",
"LGPL-3.0-only",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
DataDog/integrations-core
|
ee1886cc7655972b2791e6ab8a1c62ab35afdb47
|
406072e4294edff5b46b513f0cdf7c2c00fac9d2
|
refs/heads/master
| 2023-08-31T04:08:06.243593
| 2023-08-30T18:22:10
| 2023-08-30T18:22:10
| 47,203,045
| 852
| 1,548
|
BSD-3-Clause
| 2023-09-14T16:39:54
| 2015-12-01T16:41:45
|
Python
|
UTF-8
|
Python
| false
| false
| 15,701
|
py
|
config.py
|
# (C) Datadog, Inc. 2010-present
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import ipaddress
import time
import weakref
from collections import defaultdict
from logging import Logger, getLogger # noqa: F401
from typing import Any, DefaultDict, Dict, Iterator, List, Optional, Set, Tuple # noqa: F401
from datadog_checks.base import ConfigurationError, is_affirmative
from .mibs import MIBLoader
from .models import OID, Device
from .parsing import ParsedMetric, ParsedSymbolMetric, SymbolTag, parse_metrics, parse_symbol_metric_tags # noqa: F401
from .pysnmp_types import (
CommunityData,
ContextData,
OctetString,
UsmUserData,
hlapi,
usmDESPrivProtocol,
usmHMACMD5AuthProtocol,
)
from .resolver import OIDResolver
from .types import OIDMatch # noqa: F401
from .utils import register_device_target
local_logger = getLogger(__name__)
SUPPORTED_DEVICE_TAGS = ['vendor']
class InstanceConfig:
"""Parse and hold configuration about a single instance."""
DEFAULT_RETRIES = 5
DEFAULT_TIMEOUT = 5
DEFAULT_ALLOWED_FAILURES = 3
DEFAULT_BULK_THRESHOLD = 0
DEFAULT_WORKERS = 5
DEFAULT_REFRESH_OIDS_CACHE_INTERVAL = 0 # `0` means disabled
AUTH_PROTOCOL_MAPPING = {
'md5': 'usmHMACMD5AuthProtocol',
'sha': 'usmHMACSHAAuthProtocol',
'sha224': 'usmHMAC128SHA224AuthProtocol',
'sha256': 'usmHMAC192SHA256AuthProtocol',
'sha384': 'usmHMAC256SHA384AuthProtocol',
'sha512': 'usmHMAC384SHA512AuthProtocol',
}
PRIV_PROTOCOL_MAPPING = {
'des': 'usmDESPrivProtocol',
'3des': 'usm3DESEDEPrivProtocol',
'aes': 'usmAesCfb128Protocol',
'aes192': 'usmAesBlumenthalCfb192Protocol',
'aes256': 'usmAesBlumenthalCfb256Protocol',
'aes192c': 'usmAesCfb192Protocol',
'aes256c': 'usmAesCfb256Protocol',
}
def __init__(
self,
instance, # type: dict
global_metrics=None, # type: List[dict]
mibs_path=None, # type: str
refresh_oids_cache_interval=DEFAULT_REFRESH_OIDS_CACHE_INTERVAL, # type: int
profiles=None, # type: Dict[str, dict]
profiles_by_oid=None, # type: Dict[str, str]
loader=None, # type: MIBLoader
logger=None, # type: Logger
):
# type: (...) -> None
global_metrics = [] if global_metrics is None else global_metrics
profiles = {} if profiles is None else profiles
profiles_by_oid = {} if profiles_by_oid is None else profiles_by_oid
loader = MIBLoader() if loader is None else loader
# Clean empty or null values. This will help templating.
for key, value in list(instance.items()):
if value in (None, ""):
instance.pop(key)
self.logger = weakref.ref(local_logger) if logger is None else weakref.ref(logger)
self.instance = instance
self.tags = instance.get('tags', [])
self.metrics = instance.get('metrics', [])
metric_tags = instance.get('metric_tags', [])
profile = instance.get('profile')
if is_affirmative(instance.get('use_global_metrics', True)):
self.metrics.extend(global_metrics)
self.enforce_constraints = is_affirmative(instance.get('enforce_mib_constraints', True))
self._snmp_engine = loader.create_snmp_engine(mibs_path)
mib_view_controller = loader.get_mib_view_controller(mibs_path)
self._resolver = OIDResolver(mib_view_controller, self.enforce_constraints)
self.device = None # type: Optional[Device]
self.ip_network = None
self.discovered_instances = {} # type: Dict[str, InstanceConfig]
self.failing_instances = defaultdict(int) # type: DefaultDict[str, int]
self.allowed_failures = int(instance.get('discovery_allowed_failures', self.DEFAULT_ALLOWED_FAILURES))
self.workers = int(instance.get('workers', self.DEFAULT_WORKERS))
self.bulk_threshold = int(instance.get('bulk_threshold', self.DEFAULT_BULK_THRESHOLD))
self._auth_data = self.get_auth_data(instance)
self._context_data = ContextData(*self.get_context_data(instance))
timeout = int(instance.get('timeout', self.DEFAULT_TIMEOUT))
retries = int(instance.get('retries', self.DEFAULT_RETRIES))
ip_address = instance.get('ip_address')
network_address = instance.get('network_address')
if not ip_address and not network_address:
raise ConfigurationError('An IP address or a network address needs to be specified')
if ip_address and network_address:
raise ConfigurationError('Only one of IP address and network address must be specified')
if ip_address:
port = int(instance.get('port', 161))
target = register_device_target(
ip_address,
port,
timeout=timeout,
retries=retries,
engine=self._snmp_engine,
auth_data=self._auth_data,
context_data=self._context_data,
)
device = Device(ip=ip_address, port=port, target=target)
self.device = device
self.tags.extend(device.tags)
if network_address:
if isinstance(network_address, bytes):
network_address = network_address.decode('utf-8')
self.ip_network = ipaddress.ip_network(network_address)
ignored_ip_addresses = instance.get('ignored_ip_addresses', [])
if not isinstance(ignored_ip_addresses, list):
raise ConfigurationError(
'ignored_ip_addresses should be a list (got {})'.format(type(ignored_ip_addresses))
)
self.ignored_ip_addresses = set(ignored_ip_addresses) # type: Set[str]
if not self.metrics and not profiles_by_oid and not profile:
raise ConfigurationError('Instance should specify at least one metric or profiles should be defined')
scalar_oids, next_oids, bulk_oids, self.parsed_metrics = self.parse_metrics(self.metrics)
tag_oids, self.parsed_metric_tags = self.parse_metric_tags(metric_tags)
if tag_oids:
scalar_oids.extend(tag_oids)
refresh_interval_sec = instance.get('refresh_oids_cache_interval', refresh_oids_cache_interval)
self.oid_config = OIDConfig(refresh_interval_sec)
self.oid_config.add_parsed_oids(scalar_oids=scalar_oids, next_oids=next_oids, bulk_oids=bulk_oids)
if profile:
if profile not in profiles:
raise ConfigurationError("Unknown profile '{}'".format(profile))
self.refresh_with_profile(profiles[profile])
self.add_profile_tag(profile)
self._uptime_metric_added = False
def resolve_oid(self, oid):
# type: (OID) -> OIDMatch
return self._resolver.resolve_oid(oid)
def refresh_with_profile(self, profile):
# type: (Dict[str, Any]) -> None
metrics = profile['definition'].get('metrics', [])
scalar_oids, next_oids, bulk_oids, parsed_metrics = self.parse_metrics(metrics)
metric_tags = profile['definition'].get('metric_tags', [])
tag_oids, parsed_metric_tags = self.parse_metric_tags(metric_tags)
device = profile['definition'].get('device', {})
self.add_device_tags(device)
# NOTE: `profile` may contain metrics and metric tags that have already been ingested in this configuration.
# As a result, multiple copies of metrics/tags will be fetched and submitted to Datadog, which is inefficient
# and possibly problematic.
# In the future we'll probably want to implement de-duplication.
self.metrics.extend(metrics)
self.oid_config.add_parsed_oids(scalar_oids=scalar_oids + tag_oids, next_oids=next_oids, bulk_oids=bulk_oids)
self.parsed_metrics.extend(parsed_metrics)
self.parsed_metric_tags.extend(parsed_metric_tags)
def add_profile_tag(self, profile_name):
# type: (str) -> None
self.tags.append('snmp_profile:{}'.format(profile_name))
def add_device_tags(self, device):
# type: (dict) -> None
for device_tag in SUPPORTED_DEVICE_TAGS:
tag = device.get(device_tag)
if tag:
self.tags.append('device_{}:{}'.format(device_tag, tag))
@classmethod
def get_auth_data(cls, instance):
# type: (Dict[str, Any]) -> Any
"""
Generate a Security Parameters object based on the instance's
configuration.
"""
if 'community_string' in instance:
# SNMP v1 - SNMP v2
# See http://snmplabs.com/pysnmp/docs/api-reference.html#pysnmp.hlapi.CommunityData
if int(instance.get('snmp_version', 2)) == 1:
return CommunityData(instance['community_string'], mpModel=0)
return CommunityData(instance['community_string'], mpModel=1)
if 'user' in instance:
# SNMP v3
user = instance['user']
auth_key = None
priv_key = None
auth_protocol = None
priv_protocol = None
if 'authKey' in instance:
auth_key = instance['authKey']
auth_protocol = usmHMACMD5AuthProtocol
if 'privKey' in instance:
priv_key = instance['privKey']
auth_protocol = usmHMACMD5AuthProtocol
priv_protocol = usmDESPrivProtocol
if 'authProtocol' in instance:
protocol_name = instance['authProtocol']
if protocol_name.lower() in cls.AUTH_PROTOCOL_MAPPING:
protocol_name = cls.AUTH_PROTOCOL_MAPPING[protocol_name.lower()]
auth_protocol = getattr(hlapi, protocol_name)
if 'privProtocol' in instance:
protocol_name = instance['privProtocol']
if protocol_name.lower() in cls.PRIV_PROTOCOL_MAPPING:
protocol_name = cls.PRIV_PROTOCOL_MAPPING[protocol_name.lower()]
priv_protocol = getattr(hlapi, protocol_name)
return UsmUserData(user, auth_key, priv_key, auth_protocol, priv_protocol)
raise ConfigurationError('An authentication method needs to be provided')
@staticmethod
def get_context_data(instance):
# type: (Dict[str, Any]) -> Tuple[Optional[OctetString], str]
"""
Generate a Context Parameters object based on the instance's
configuration.
We do not use the hlapi currently, but the rfc3413.oneliner.cmdgen
accepts Context Engine Id (always None for now) and Context Name parameters.
"""
context_engine_id = None
context_name = ''
if 'user' in instance:
if 'context_engine_id' in instance:
context_engine_id = OctetString(instance['context_engine_id'])
if 'context_name' in instance:
context_name = instance['context_name']
return context_engine_id, context_name
def network_hosts(self):
# type: () -> Iterator[str]
if self.ip_network is None:
raise RuntimeError('Expected ip_network to be set to iterate over network hosts.')
for ip_address in self.ip_network.hosts():
host = str(ip_address)
if host in self.discovered_instances:
continue
if host in self.ignored_ip_addresses:
continue
yield host
def parse_metrics(self, metrics):
# type: (list) -> Tuple[List[OID], List[OID], List[OID], List[ParsedMetric]]
"""Parse configuration and returns data to be used for SNMP queries."""
# Use bulk for SNMP version > 1 only.
bulk_threshold = self.bulk_threshold if self._auth_data.mpModel else 0
result = parse_metrics(metrics, resolver=self._resolver, logger=self.logger(), bulk_threshold=bulk_threshold)
return result['oids'], result['next_oids'], result['bulk_oids'], result['parsed_metrics']
def parse_metric_tags(self, metric_tags):
# type: (list) -> Tuple[List[OID], List[SymbolTag]]
"""Parse configuration for global metric_tags."""
result = parse_symbol_metric_tags(metric_tags, resolver=self._resolver)
return result['oids'], result['parsed_symbol_tags']
def add_uptime_metric(self):
# type: () -> None
if self._uptime_metric_added:
return
# Reference sysUpTimeInstance directly, see http://oidref.com/1.3.6.1.2.1.1.3.0
uptime_oid = OID('1.3.6.1.2.1.1.3.0')
self.oid_config.add_parsed_oids(scalar_oids=[uptime_oid])
self._resolver.register(uptime_oid, 'sysUpTimeInstance')
parsed_metric = ParsedSymbolMetric('sysUpTimeInstance', forced_type='gauge')
self.parsed_metrics.append(parsed_metric)
self._uptime_metric_added = True
class OIDConfig(object):
"""
Manages scalar/next/bulk oids to be used for snmp PDU calls.
"""
def __init__(self, refresh_interval_sec):
# type: (bool) -> None
self._refresh_interval_sec = refresh_interval_sec
self._last_ts = 0 # type: float
self._scalar_oids = [] # type: List[OID]
self._next_oids = [] # type: List[OID]
self._bulk_oids = [] # type: List[OID]
self._all_scalar_oids = [] # type: List[OID]
self._use_scalar_oids_cache = False
@property
def scalar_oids(self):
# type: () -> List[OID]
if self._use_scalar_oids_cache:
return self._all_scalar_oids
return self._scalar_oids
@property
def next_oids(self):
# type: () -> List[OID]
if self._use_scalar_oids_cache:
return []
return self._next_oids
@property
def bulk_oids(self):
# type: () -> List[OID]
if self._use_scalar_oids_cache:
return []
return self._bulk_oids
def add_parsed_oids(self, scalar_oids=None, next_oids=None, bulk_oids=None):
# type: (List[OID], List[OID], List[OID]) -> None
if scalar_oids:
self._scalar_oids.extend(scalar_oids)
if next_oids:
self._next_oids.extend(next_oids)
if bulk_oids:
self._bulk_oids.extend(bulk_oids)
self.reset()
def has_oids(self):
# type: () -> bool
"""
Return whether there are OIDs to fetch.
"""
return bool(self.scalar_oids or self.next_oids or self.bulk_oids)
def _is_cache_enabled(self):
# type: () -> bool
return self._refresh_interval_sec > 0
def update_scalar_oids(self, new_scalar_oids):
# type: (List[OID]) -> None
"""
Use only scalar oids for following snmp calls.
"""
if not self._is_cache_enabled():
return
# Do not update if we are already using scalar oids cache.
if self._use_scalar_oids_cache:
return
self._all_scalar_oids = new_scalar_oids
self._use_scalar_oids_cache = True
self._last_ts = time.time()
def should_reset(self):
# type: () -> bool
"""
Whether we should reset OIDs to initial parsed OIDs.
"""
if not self._is_cache_enabled():
return False
elapsed = time.time() - self._last_ts
return elapsed > self._refresh_interval_sec
def reset(self):
# type: () -> None
"""
Reset scalar oids cache.
"""
self._all_scalar_oids = []
self._use_scalar_oids_cache = False
|
1facb72df7b42a179a2b9b90e1bba73c3c421195
|
5b6ba0f288b1e2ac236af846a9bf546a63228476
|
/mmtbx/arrays.py
|
027245942fc80eebfd0846f9ae413ccfcf50e830
|
[
"BSD-3-Clause-LBNL"
] |
permissive
|
cctbx/cctbx_project
|
5b547b416cadbdf95cca21dace9f54272a08d98a
|
7f4dfb6c873fd560920f697cbfd8a5ff6eed82fa
|
refs/heads/master
| 2023-08-17T17:44:05.077010
| 2023-08-16T22:40:22
| 2023-08-16T22:40:22
| 39,508,026
| 206
| 131
|
NOASSERTION
| 2023-09-14T17:12:55
| 2015-07-22T13:36:27
|
Python
|
UTF-8
|
Python
| false
| false
| 5,456
|
py
|
arrays.py
|
from __future__ import absolute_import, division, print_function
from scitbx.array_family import flex
from libtbx import adopt_init_args
import boost_adaptbx.boost.python as bp
from six.moves import range
ext = bp.import_ext("mmtbx_f_model_ext")
from cctbx import miller
class init(object): # XXX PVA: Why Fobs, HL and r_free_flags are not here?
def __init__(self,
f_calc,
f_masks=None,
f_part1=None,
f_part2=None,
k_masks=None,
k_isotropic_exp=None,
k_isotropic=None,
k_anisotropic=None):
adopt_init_args(self, locals())
if(self.f_masks is None):
self.f_masks = [self.f_calc.customized_copy(
data=flex.complex_double(f_calc.data().size(), 0))]
else:
if(not (type(self.f_masks) in [list, tuple])):
self.f_masks = [self.f_masks]
for fm in self.f_masks:
assert self.f_calc.indices().all_eq(fm.indices())
if(self.k_isotropic_exp is not None):
assert self.k_isotropic_exp.size() == self.f_calc.indices().size()
else: self.k_isotropic_exp = flex.double(f_calc.data().size(), 1)
if(self.k_isotropic is not None):
assert self.k_isotropic.size() == self.f_calc.indices().size()
else: self.k_isotropic = flex.double(f_calc.data().size(), 1)
if(self.k_anisotropic is not None):
assert self.k_anisotropic.size() == self.f_calc.indices().size()
else: self.k_anisotropic = flex.double(f_calc.data().size(), 1)
if(self.k_masks is None):
n=len(self.f_masks)
self.k_masks = [flex.double(f_calc.data().size(), 0)]*n
else:
if(not (type(self.k_masks) in [list, tuple])):
self.k_masks = [self.k_masks]
if(self.f_part1 is not None):
assert self.f_calc.indices().all_eq(self.f_part1.indices())
else:
self.f_part1 = self.f_calc.customized_copy(
data=flex.complex_double(f_calc.data().size(), 0))
if(self.f_part2 is not None):
assert self.f_calc.indices().all_eq(self.f_part2.indices())
else:
self.f_part2 = self.f_calc.customized_copy(
data=flex.complex_double(f_calc.data().size(), 0))
# assemble f_bulk
f_bulk_data = flex.complex_double(f_calc.data().size(), 0)
assert len(self.k_masks) == len(self.f_masks)
for i in range(len(self.k_masks)):
f_bulk_data += self.k_masks[i]*self.f_masks[i].data()
#
self.data = ext.data(
f_calc = self.f_calc.data(),
f_bulk = f_bulk_data,
k_isotropic_exp = self.k_isotropic_exp,
k_isotropic = self.k_isotropic,
k_anisotropic = self.k_anisotropic,
f_part1 = self.f_part1.data(),
f_part2 = self.f_part2.data())
self.f_model = miller.array(miller_set=self.f_calc, data=self.data.f_model)
self.f_model_no_aniso_scale = miller.array(
miller_set=self.f_calc,
data =self.data.f_model_no_aniso_scale)
def f_mask(self):
assert len(self.f_masks)==1
return self.f_masks[0]
def k_mask(self):
assert len(self.k_masks)==1
return self.k_masks[0]
def select(self, selection=None):
if(selection is None): return self
assert self.f_calc.indices().size() == selection.size()
f_masks = [fm.select(selection=selection) for fm in self.f_masks]
k_masks = [km.select(selection) for km in self.k_masks]
return init(
f_calc = self.f_calc.select(selection),
f_masks = f_masks,
k_isotropic_exp = self.k_isotropic_exp.select(selection),
k_isotropic = self.k_isotropic.select(selection),
k_masks = k_masks,
k_anisotropic = self.k_anisotropic.select(selection),
f_part1 = self.f_part1.select(selection),
f_part2 = self.f_part2.select(selection))
def deep_copy(self):
return self.select(selection=flex.bool(self.f_calc.indices().size(), True))
def __getstate__(self):
return {"args": (
self.f_calc,
self.f_masks,
self.f_part1,
self.f_part2,
self.k_masks,
self.k_isotropic_exp,
self.k_isotropic,
self.k_anisotropic)}
def __setstate__(self, state):
assert len(state) == 1
self.__init__(*state["args"])
# XXX PVA: returns new object, not itself updated. This is misleading!
# See fmodel_kbu where this is done rigth.
def update(self,
f_calc=None,
f_masks=None,
k_isotropic_exp=None,
k_isotropic=None,
k_masks=None,
k_anisotropic=None,
f_part1=None,
f_part2=None):
if(f_calc is None): f_calc = self.f_calc
if(f_masks is None): f_masks = self.f_masks
if(k_isotropic_exp is None): k_isotropic_exp = self.k_isotropic_exp
if(k_isotropic is None): k_isotropic = self.k_isotropic
if(k_masks is None): k_masks = self.k_masks
if(k_anisotropic is None): k_anisotropic = self.k_anisotropic
if(f_part1 is None): f_part1 = self.f_part1
if(f_part2 is None): f_part2 = self.f_part2
self.__init__(
f_calc = f_calc,
f_masks = f_masks,
k_isotropic_exp = k_isotropic_exp,
k_isotropic = k_isotropic,
k_masks = k_masks,
k_anisotropic = k_anisotropic,
f_part1 = f_part1,
f_part2 = f_part2)
return self
|
37888eac27f55c031a3a0c2d797687791449fa0a
|
d05c946e345baa67e7894ee33ca21e24b8d26028
|
/python-standard-library/handling-files/handling-files.py
|
65feb8c3ac81454dae9b02a9b8ee870d09550e1a
|
[
"MIT"
] |
permissive
|
x4nth055/pythoncode-tutorials
|
327255550812f84149841d56f2d13eaa84efd42e
|
d6ba5d672f7060ba88384db5910efab1768c7230
|
refs/heads/master
| 2023-09-01T02:36:58.442748
| 2023-08-19T14:04:34
| 2023-08-19T14:04:34
| 199,449,624
| 1,858
| 2,055
|
MIT
| 2023-08-25T20:41:56
| 2019-07-29T12:35:40
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 1,744
|
py
|
handling-files.py
|
import os
import shutil
# print the current directory
print("The current directory:", os.getcwd())
# make an empty directory (folder)
os.mkdir("folder")
# running mkdir again with the same name raises FileExistsError, run this instead:
# if not os.path.isdir("folder"):
# os.mkdir("folder")
# changing the current directory to 'folder'
os.chdir("folder")
# printing the current directory now
print("The current directory changing the directory to folder:", os.getcwd())
# go back a directory
os.chdir("..")
# make several nested directories
os.makedirs("nested1/nested2/nested3")
# create a new text file
text_file = open("text.txt", "w")
# write to this file some text
text_file.write("This is a text file")
# rename text.txt to renamed-text.txt
os.rename("text.txt", "renamed-text.txt")
# replace (move) this file to another directory
os.replace("renamed-text.txt", "folder/renamed-text.txt")
# print all files and folders in the current directory
print("All folders & files:", os.listdir())
# print all files & folders recursively
for dirpath, dirnames, filenames in os.walk("."):
# iterate over directories
for dirname in dirnames:
print("Directory:", os.path.join(dirpath, dirname))
# iterate over files
for filename in filenames:
print("File:", os.path.join(dirpath, filename))
# delete that file
os.remove("folder/renamed-text.txt")
# remove the folder
os.rmdir("folder")
# remove nested empty folders
os.removedirs("nested1/nested2/nested3")
# remote non-empty folders
shutil.rmtree("nested1")
open("text.txt", "w").write("This is a text file")
# print some stats about the file
print(os.stat("text.txt"))
# get the file size for example
print("File size:", os.stat("text.txt").st_size)
|
4b0bd3d2469ff1d9790d1e5a0bcb7dfc31a24655
|
ff0ab350c70ada2e6182d68e99fe970eddf8b983
|
/aws_google_auth/tests/test_args_parser.py
|
ad55116fa6514773faacbd478f68b994979c546c
|
[
"MIT"
] |
permissive
|
cevoaustralia/aws-google-auth
|
71b01d70db2747c997c5143be2d3850c7b39a492
|
dd42263bbeeb053e1b66a2db9a7b1f23606940f0
|
refs/heads/master
| 2023-08-15T16:59:54.246982
| 2022-05-02T21:48:28
| 2022-05-02T21:48:28
| 94,195,575
| 549
| 196
|
MIT
| 2023-07-20T09:34:34
| 2017-06-13T09:30:29
|
Python
|
UTF-8
|
Python
| false
| false
| 3,920
|
py
|
test_args_parser.py
|
#!/usr/bin/env python
import unittest
from aws_google_auth import parse_args
class TestPythonFailOnVersion(unittest.TestCase):
def test_no_arguments(self):
"""
This test case exists to validate the default settings of the args parser.
Changes that break these checks should be considered for backwards compatibility review.
:return:
"""
parser = parse_args([])
self.assertTrue(parser.saml_cache)
self.assertEqual(parser.saml_assertion, None)
self.assertFalse(parser.ask_role)
self.assertFalse(parser.print_creds)
self.assertFalse(parser.keyring)
self.assertFalse(parser.resolve_aliases)
self.assertFalse(parser.disable_u2f, None)
self.assertEqual(parser.duration, None)
self.assertEqual(parser.auto_duration, False)
self.assertEqual(parser.idp_id, None)
self.assertEqual(parser.sp_id, None)
self.assertEqual(parser.profile, None)
self.assertEqual(parser.region, None)
self.assertEqual(parser.role_arn, None)
self.assertEqual(parser.username, None)
self.assertEqual(parser.quiet, False)
self.assertEqual(parser.bg_response, None)
self.assertEqual(parser.account, None)
self.assertFalse(parser.save_failure_html)
self.assertFalse(parser.save_saml_flow)
# Assert the size of the parameter so that new parameters trigger a review of this function
# and the appropriate defaults are added here to track backwards compatibility in the future.
self.assertEqual(len(vars(parser)), 21)
def test_username(self):
parser = parse_args(['-u', 'username@gmail.com'])
self.assertTrue(parser.saml_cache)
self.assertFalse(parser.ask_role)
self.assertFalse(parser.keyring)
self.assertFalse(parser.resolve_aliases)
self.assertEqual(parser.duration, None)
self.assertEqual(parser.auto_duration, False)
self.assertEqual(parser.idp_id, None)
self.assertEqual(parser.profile, None)
self.assertEqual(parser.region, None)
self.assertEqual(parser.role_arn, None)
self.assertEqual(parser.username, 'username@gmail.com')
self.assertEqual(parser.account, None)
def test_nocache(self):
parser = parse_args(['--no-cache'])
self.assertFalse(parser.saml_cache)
self.assertFalse(parser.ask_role)
self.assertFalse(parser.keyring)
self.assertFalse(parser.resolve_aliases)
self.assertEqual(parser.duration, None)
self.assertEqual(parser.auto_duration, False)
self.assertEqual(parser.idp_id, None)
self.assertEqual(parser.profile, None)
self.assertEqual(parser.region, None)
self.assertEqual(parser.role_arn, None)
self.assertEqual(parser.username, None)
self.assertEqual(parser.account, None)
def test_resolvealiases(self):
parser = parse_args(['--resolve-aliases'])
self.assertTrue(parser.saml_cache)
self.assertFalse(parser.ask_role)
self.assertFalse(parser.keyring)
self.assertTrue(parser.resolve_aliases)
self.assertEqual(parser.duration, None)
self.assertEqual(parser.auto_duration, False)
self.assertEqual(parser.idp_id, None)
self.assertEqual(parser.profile, None)
self.assertEqual(parser.region, None)
self.assertEqual(parser.role_arn, None)
self.assertEqual(parser.username, None)
self.assertEqual(parser.account, None)
def test_ask_and_supply_role(self):
with self.assertRaises(SystemExit):
parse_args(['-a', '-r', 'da-role'])
def test_invalid_duration(self):
"""
Should fail parsing a non-int value for `-d`.
:return:
"""
with self.assertRaises(SystemExit):
parse_args(['-d', 'abce'])
|
f705060af70e52c8b7da813f30983a59c949d0ff
|
507103d591ed6993203db92fd8dffc992e8bcd5c
|
/k2/python/tests/top_sort_test.py
|
2468d683584f5c22e9f6f422dd6249384aad8675
|
[
"Apache-2.0"
] |
permissive
|
k2-fsa/k2
|
6e661bd505f06583af779f4249bbb8ea87a0d662
|
2b2ac14b326d61d79d04e53fbd69b1ff6d630411
|
refs/heads/master
| 2023-09-03T11:57:13.505432
| 2023-08-23T21:58:26
| 2023-08-23T21:58:26
| 256,463,281
| 851
| 192
|
Apache-2.0
| 2023-08-26T06:51:21
| 2020-04-17T09:44:05
|
Cuda
|
UTF-8
|
Python
| false
| false
| 2,173
|
py
|
top_sort_test.py
|
#!/usr/bin/env python3
#
# Copyright 2020 Mobvoi Inc. (authors: Fangjun Kuang)
#
# See ../../../LICENSE for clarification regarding multiple authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# To run this single test, use
#
# ctest --verbose -R top_sort_test_py
import unittest
import k2
import torch
class TestTopSort(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.devices = [torch.device('cpu')]
if torch.cuda.is_available() and k2.with_cuda:
cls.devices.append(torch.device('cuda', 0))
if torch.cuda.device_count() > 1:
torch.cuda.set_device(1)
cls.devices.append(torch.device('cuda', 1))
def test(self):
# arc 0: 0 -> 1, weight 1
# arc 1: 0 -> 2, weight 2
# arc 2: 1 -> 3, weight 3
# arc 3: 2 -> 1, weight 4
# the shortest path is 0 -> 1 -> 3, weight is 4
# That is, (arc 0) -> (arc 2)
s = '''
0 1 1 1
0 2 2 2
1 3 -1 3
2 1 3 4
3
'''
for device in self.devices:
fsa = k2.Fsa.from_str(s).to(device)
fsa.requires_grad_(True)
sorted_fsa = k2.top_sort(fsa)
# the shortest path in the sorted fsa is (arc 0) -> (arc 3)
loss = (sorted_fsa.scores[0] + sorted_fsa.scores[3]) / 2
loss.backward()
assert torch.allclose(
fsa.scores.grad,
torch.tensor([0.5, 0, 0.5, 0],
dtype=torch.float32,
device=device))
if __name__ == '__main__':
unittest.main()
|
489e0577e19bc8e1f9284d2f921c6e2ea0fd3f92
|
73cf7b1d2e75ee77e69f12044f5baa74035d9462
|
/latent_rationale/nn/bernoulli_gate.py
|
3f0be1987e683d3907017f0fba27d53256b96967
|
[
"MIT"
] |
permissive
|
bastings/interpretable_predictions
|
c165d14adadebb0c17a00dd4b5c2cff10c5047f0
|
fef61833bd22205dc2d4f77e2c0ed3f40cbe8ea6
|
refs/heads/master
| 2021-06-16T23:34:19.500600
| 2021-05-07T16:49:38
| 2021-05-07T16:49:38
| 187,211,218
| 116
| 24
|
MIT
| 2021-04-02T10:39:50
| 2019-05-17T12:19:13
|
Python
|
UTF-8
|
Python
| false
| false
| 725
|
py
|
bernoulli_gate.py
|
# coding: utf-8
import torch.nn as nn
from torch.nn import Linear, Sequential
from torch.distributions.bernoulli import Bernoulli
class BernoulliGate(nn.Module):
"""
Computes a Bernoulli Gate
Assigns a 0 or a 1 to each input word.
"""
def __init__(self, in_features, out_features=1):
super(BernoulliGate, self).__init__()
self.layer = Sequential(
Linear(in_features, out_features, bias=True)
)
def forward(self, x):
"""
Compute Binomial gate
:param x: word represenatations [B, T, D]
:return: gate distribution
"""
logits = self.layer(x) # [B, T, 1]
dist = Bernoulli(logits=logits)
return dist
|
38b4cdce9dcdcde06394a5760a79aa00c160814e
|
9b391863599ecc26a6804f9f272f8c7f2aee8a8c
|
/tick/base_model/model_lipschitz.py
|
869f2940203daf0c534b0e0b296763406385a1aa
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
X-DataInitiative/tick
|
4db1bce7471bb48757b54e86b0f7946f36e78dde
|
04dbb377b47783036a8343c6a61b60fc9f430dc3
|
refs/heads/master
| 2023-08-13T10:28:15.560632
| 2023-03-05T00:16:57
| 2023-03-05T00:16:57
| 75,284,069
| 475
| 120
|
BSD-3-Clause
| 2023-03-05T00:16:58
| 2016-12-01T10:59:08
|
Python
|
UTF-8
|
Python
| false
| false
| 2,632
|
py
|
model_lipschitz.py
|
# License: BSD 3 clause
from abc import abstractmethod
from . import Model
__author__ = 'Stephane Gaiffas'
class ModelLipschitz(Model):
"""An abstract base class for a model that implements lipschitz
constants
Parameters
----------
dtype : `{'float64', 'float32'}`, default='float64'
Type of the arrays used. This value is set from model and prox dtypes.
Notes
-----
This class should be not used by end-users, it is intended for
development only.
"""
_attrinfos = {
"_ready_lip_best": {
"writable": False
},
"_lip_best": {
"writable": False
}
}
def __init__(self):
Model.__init__(self)
self._ready_lip_best = False
self._lip_best = None
def fit(self, *args):
self._set("_ready_lip_best", False)
def get_lip_max(self) -> float:
"""Returns the maximum Lipschitz constant of individual losses. This is
particularly useful for step-size tuning of some solvers.
Returns
-------
output : `float`
The maximum Lipschitz constant
"""
if self._fitted:
return self._model.get_lip_max()
else:
raise ValueError("call ``fit`` before calling ``get_lip_max``")
def get_lip_mean(self) -> float:
"""Returns the average Lipschitz constant of individual losses. This is
particularly useful for step-size tuning of some solvers.
Returns
-------
output : `float`
The average Lipschitz constant
"""
if self._fitted:
return self._model.get_lip_mean()
else:
raise ValueError("call ``fit`` before using ``get_lip_max``")
def get_lip_best(self) -> float:
"""Returns the best Lipschitz constant, using all samples
Warning: this might take some time, since it requires a SVD computation.
Returns
-------
output : `float`
The best Lipschitz constant
"""
if self._fitted:
if self._ready_lip_best:
return self._lip_best
else:
lip_best = self._get_lip_best()
self._set("_lip_best", lip_best)
self._set("_ready_lip_best", True)
return lip_best
else:
raise ValueError("call ``fit`` before calling ``get_lip_best``")
@abstractmethod
def _get_lip_best(self) -> float:
"""The method that actually does the computation. Must be overloaded
in childs
"""
pass
|
bfe991a07bb4d2283c066276b7ac0ef3d104ff0d
|
c43b5835b4499f4e6d6fa4efda9546dc67ae0767
|
/sfepy/examples/large_deformation/hyperelastic_ul.py
|
1fae3300ca3dfe230bdcc32015f80e256bcbce81
|
[
"BSD-3-Clause"
] |
permissive
|
sfepy/sfepy
|
4b74e7839b5e7b5e8d90e19ab6e90a068fe33df4
|
0c2d1690e764b601b2687be1e4261b82207ca366
|
refs/heads/master
| 2023-09-04T22:07:28.041123
| 2023-08-28T14:47:50
| 2023-08-28T14:47:50
| 802,525
| 651
| 188
|
BSD-3-Clause
| 2023-09-12T07:28:19
| 2010-07-28T09:14:41
|
Python
|
UTF-8
|
Python
| false
| false
| 3,627
|
py
|
hyperelastic_ul.py
|
# -*- coding: utf-8 -*-
r"""
Nearly incompressible Mooney-Rivlin hyperelastic material model.
Large deformation is described using the updated Lagrangian formulation.
Models of this kind can be used to model e.g. rubber or some biological
materials.
"""
from __future__ import print_function
from __future__ import absolute_import
import numpy as nm
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/3d/cylinder.mesh'
options = {
'nls': 'newton',
'ls': 'ls',
'ts': 'ts',
'ulf': True,
'mesh_update_variables': ['u'],
'output_dir': 'output',
'post_process_hook': 'stress_strain',
}
fields = {
'displacement': ('real', 3, 'Omega', 1),
}
materials = {
'solid': ({'K': 1e3, # bulk modulus
'mu': 20e0, # shear modulus of neoHookean term
'kappa': 10e0, # shear modulus of Mooney-Rivlin term
},),
}
variables = {
'u': ('unknown field', 'displacement', 0),
'v': ('test field', 'displacement', 'u'),
}
regions = {
'Omega' : 'all',
'Left' : ('vertices in (x < 0.001)', 'facet'),
'Right' : ('vertices in (x > 0.099)', 'facet'),
}
##
# Dirichlet BC + related functions.
ebcs = {
'l' : ('Left', {'u.all' : 0.0}),
'r' : ('Right', {'u.0' : 0.0, 'u.[1,2]' : 'rotate_yz'}),
}
centre = nm.array( [0, 0], dtype = nm.float64 )
def rotate_yz(ts, coor, **kwargs):
from sfepy.linalg import rotation_matrix2d
vec = coor[:,1:3] - centre
angle = 10.0 * ts.step
print('angle:', angle)
mtx = rotation_matrix2d( angle )
vec_rotated = nm.dot( vec, mtx )
displacement = vec_rotated - vec
return displacement
functions = {
'rotate_yz' : (rotate_yz,),
}
def stress_strain( out, problem, state, extend = False ):
from sfepy.base.base import Struct
ev = problem.evaluate
strain = ev('dw_ul_he_neohook.3.Omega( solid.mu, v, u )',
mode='el_avg', term_mode='strain')
out['green_strain'] = Struct(name='output_data',
mode='cell', data=strain, dofs=None)
stress = ev('dw_ul_he_neohook.3.Omega( solid.mu, v, u )',
mode='el_avg', term_mode='stress')
out['neohook_stress'] = Struct(name='output_data',
mode='cell', data=stress, dofs=None)
stress = ev('dw_ul_he_mooney_rivlin.3.Omega( solid.kappa, v, u )',
mode='el_avg', term_mode='stress')
out['mooney_rivlin_stress'] = Struct(name='output_data',
mode='cell', data=stress, dofs=None)
stress = ev('dw_ul_bulk_penalty.3.Omega( solid.K, v, u )',
mode='el_avg', term_mode= 'stress')
out['bulk_stress'] = Struct(name='output_data',
mode='cell', data=stress, dofs=None)
return out
equations = {
'balance': """dw_ul_he_neohook.3.Omega( solid.mu, v, u )
+ dw_ul_he_mooney_rivlin.3.Omega(solid.kappa, v, u)
+ dw_ul_bulk_penalty.3.Omega( solid.K, v, u )
= 0""",
}
##
# Solvers etc.
solvers = {
'ls': ('ls.scipy_direct', {}),
'newton': ('nls.newton', {
'i_max': 25,
'eps_a': 1e-8,
'eps_r': 1.0,
'macheps': 1e-16,
'lin_red': 1e-2, # Linear system error < (eps_a * lin_red).
'ls_red': 0.1,
'ls_red_warp': 0.001,
'ls_on': 1.1,
'ls_min': 1e-5,
'check': 0,
'delta': 1e-6,
}),
'ts': ('ts.simple', {
't0': 0,
't1': 1,
'dt': None,
'n_step': 11, # has precedence over dt!
'verbose' : 1,
}),
}
|
6b8f566e6a2aede9b5a89853fa79f2599529cfc2
|
529e713a78e82de2ae5d44cfb8ef209e0894d72a
|
/understanding-asynchronous-programming/example_3.py
|
7cbb00cff3a0c8dd9c94730b445d5069b08edee7
|
[
"MIT"
] |
permissive
|
realpython/materials
|
cd2f548276be2c82f134ca03eadb1cd279e0f26e
|
d2d62756d3854f54a12a767f2bf9470486c0ceef
|
refs/heads/master
| 2023-09-05T22:12:29.806738
| 2023-08-31T20:56:28
| 2023-08-31T20:56:28
| 132,374,697
| 4,678
| 6,482
|
MIT
| 2023-09-12T22:22:06
| 2018-05-06T20:46:18
|
HTML
|
UTF-8
|
Python
| false
| false
| 993
|
py
|
example_3.py
|
import time
import queue
from codetiming import Timer
def task(name, queue):
timer = Timer(text=f"Task {name} elapsed time: {{:.1f}}")
while not queue.empty():
delay = queue.get()
print(f"Task {name} running")
timer.start()
time.sleep(delay)
timer.stop()
yield
def main():
"""
This is the main entry point for the program
"""
# Create the queue of work
work_queue = queue.Queue()
# Put some work in the queue
for work in [15, 10, 5, 2]:
work_queue.put(work)
tasks = [task("One", work_queue), task("Two", work_queue)]
# Run the tasks
done = False
with Timer(text="\nTotal elapsed time: {:.1f}"):
while not done:
for t in tasks:
try:
next(t)
except StopIteration:
tasks.remove(t)
if len(tasks) == 0:
done = True
if __name__ == "__main__":
main()
|
323d70da12395766aa3c6cc6eef476957729b4e2
|
9ed83e0f003d9a196fd5ee4d46e935272889637f
|
/custom_components/microsoft_todo/outlook_tasks_api.py
|
181d0a6438af520cac204b3fac1d3551d1075a17
|
[
"MIT"
] |
permissive
|
black-roland/homeassistant-microsoft-todo
|
02def72d0f7e630ad0e2c3b3cbf39ee664493cd6
|
9e1fa078bdbb68e4093d7a9f09f9b5b789b3d63f
|
refs/heads/master
| 2023-02-21T14:25:36.293628
| 2022-11-20T17:01:34
| 2022-11-20T17:01:34
| 218,158,850
| 103
| 17
|
MIT
| 2023-02-08T00:44:28
| 2019-10-28T22:43:35
|
Python
|
UTF-8
|
Python
| false
| false
| 3,663
|
py
|
outlook_tasks_api.py
|
import re
from requests.exceptions import HTTPError
import emoji # pylint: disable=import-error
class OutlookTasksApi:
api_endpoint = "https://graph.microsoft.com"
def __init__(self, client, logger, timezone):
self.client = client
self.logger = logger
self.timezone = timezone
def create_task(self, subject, list_id=None, note=None, due_date=None, reminder_date_time=None):
uri = self.api_endpoint + "/beta/me/outlook/tasks"
if list_id:
uri = self.api_endpoint + "/beta/me/outlook/taskFolders/{}/tasks".format(list_id)
task_req = {
"subject": subject,
}
if note:
task_req["body"] = {
"contentType": "Text",
"content": note
}
if due_date:
task_req["dueDateTime"] = {
"dateTime": due_date.isoformat(),
"timeZone": str(self.timezone)
}
if reminder_date_time:
task_req["reminderDateTime"] = {
"dateTime": reminder_date_time.isoformat(),
"timeZone": str(self.timezone)
}
task_req["isReminderOn"] = True
try:
self.logger.debug("Create task request: %s", task_req)
res = self.client.post(uri, json=task_req)
res.raise_for_status()
self.logger.debug("Create task response: %s", res.json())
except HTTPError as ex:
self.logger.error("Unable to create task: %s. Response: %s", ex, res.json())
raise
return res
def get_uncompleted_tasks(self, list_id):
uri = self.api_endpoint + "/beta/me/outlook/taskFolders/{}/tasks".format(list_id)
query_params = {
"$filter": "status ne 'completed'",
"$top": 100
}
try:
self.logger.debug("Fetching To Do lists info")
res = self.client.get(uri, params=query_params)
res.raise_for_status()
self.logger.debug("To Do tasks response: %s", res.json())
except HTTPError as ex:
self.logger.error("Unable to get tasks: %s. Response: %s", ex, res.json())
raise
return res.json()
def get_list_id_by_name(self, list_name):
lists = self.get_lists()
try:
return next(
l["id"] for l in lists["value"]
if l["name"] == list_name
# To Do allows to set an icon (emoji) for a list and this emoji
# is prepended to the list name so it needs to be stripped.
or OutlookTasksApi.strip_emoji_icon(l["name"]) == list_name
)
except StopIteration as ex:
self.logger.error("No list with the name %s. %s", list_name, ex)
raise
def get_lists(self):
uri = self.api_endpoint + "/beta/me/outlook/taskFolders"
# NOTE: don't increase more, implement proper pagination instead
query_params = {"$top": 100}
try:
self.logger.debug("Fetching To Do lists info")
res = self.client.get(uri, params=query_params)
res.raise_for_status()
self.logger.debug("To Do lists response: %s", res.json())
except HTTPError as ex:
self.logger.error("Unable to get lists info: %s. Response: %s", ex, res.json())
raise
return res.json()
@staticmethod
def strip_emoji_icon(list_name):
emoji_re = emoji.get_emoji_regexp()
list_emoji_icon_re = re.compile(u"^" + emoji_re.pattern)
return list_emoji_icon_re.sub(r"", list_name)
|
34e6894e77368763beab46bacfb4ed392143465c
|
d694225d0deac8bda3f6cf4cfb37d43ca8a1d7a7
|
/pinn/networks/pinet.py
|
8b82302844e774020a4a9828d4881880b521582e
|
[
"BSD-3-Clause"
] |
permissive
|
Teoroo-CMC/PiNN
|
e7ce5a021207b8b8ea03ff51757f4720626403fc
|
5717be6dab46c980d6c1e13949719e61b2ba335a
|
refs/heads/master
| 2023-09-04T07:50:57.893981
| 2023-08-18T07:24:11
| 2023-08-18T07:44:37
| 212,766,497
| 108
| 27
|
BSD-3-Clause
| 2019-12-17T11:49:10
| 2019-10-04T08:13:18
|
Python
|
UTF-8
|
Python
| false
| false
| 7,639
|
py
|
pinet.py
|
# -*- coding: utf-8 -*-
import tensorflow as tf
from pinn.utils import pi_named, connect_dist_grad
from pinn.layers import CellListNL, CutoffFunc, \
PolynomialBasis, GaussianBasis, AtomicOnehot, ANNOutput
class FFLayer(tf.keras.layers.Layer):
"""Feed-forward layer, a shortcut for constructing multiple layers
Args:
n_node (list): dimension of the layers
act: activation function of the layers
name: name of the layer
Returns:
Nodes after the fc layers
"""
def __init__(self, n_nodes=[64, 64], **kwargs):
super(FFLayer, self).__init__()
self.dense_layers = [tf.keras.layers.Dense(
n_node, **kwargs) for n_node in n_nodes]
def call(self, tensor):
for layer in self.dense_layers:
tensor = layer(tensor)
return tensor
class PILayer(tf.keras.layers.Layer):
"""PiNN style interaction layer
Args:
n_nodes: number of nodes to use
Note that the last element of n_nodes specifies the dimention of
the fully connected network before applying the basis function.
Dimension of the last node is [pairs*n_nodes[-1]*n_basis], the
output is then summed with the basis to form the interaction nodes
**kwargs: keyword arguments will be parsed to the feed forward layers
"""
def __init__(self, n_nodes=[64], **kwargs):
super(PILayer, self).__init__()
self.n_nodes = n_nodes
self.kwargs = kwargs
def build(self, shapes):
self.n_basis = shapes[2][-1]
n_nodes_iter = self.n_nodes.copy()
n_nodes_iter[-1] *= self.n_basis
self.ff_layer = FFLayer(n_nodes_iter, **self.kwargs)
def call(self, tensors):
ind_2, prop, basis = tensors
ind_i = ind_2[:, 0]
ind_j = ind_2[:, 1]
prop_i = tf.gather(prop, ind_i)
prop_j = tf.gather(prop, ind_j)
inter = tf.concat([prop_i, prop_j], axis=-1)
inter = self.ff_layer(inter)
inter = tf.reshape(inter, [-1, self.n_nodes[-1], self.n_basis])
inter = tf.einsum('pcb,pb->pc', inter, basis)
return inter
class IPLayer(tf.keras.layers.Layer):
"""PiNet style IP layer
transforms pairwise interactions to atomic properties"""
def __init__(self):
super(IPLayer, self).__init__()
def call(self, tensors):
ind_2, prop, inter = tensors
n_atoms = tf.shape(prop)[0]
return tf.math.unsorted_segment_sum(inter, ind_2[:, 0], n_atoms)
class OutLayer(tf.keras.layers.Layer):
"""PiNet style output layer
generates outputs from atomic properties after each GC block"""
def __init__(self, n_nodes, out_units, **kwargs):
super(OutLayer, self).__init__()
self.out_units = out_units
self.ff_layer = FFLayer(n_nodes, **kwargs)
self.out_units = tf.keras.layers.Dense(
out_units, activation=None, use_bias=False)
def call(self, tensors):
ind_1, prop, prev_output = tensors
prop = self.ff_layer(prop)
output = self.out_units(prop) + prev_output
return output
class GCBlock(tf.keras.layers.Layer):
def __init__(self, pp_nodes, pi_nodes, ii_nodes, **kwargs):
super(GCBlock, self).__init__()
iiargs = kwargs.copy()
iiargs.update(use_bias=False)
self.pp_layer = FFLayer(pp_nodes, **kwargs)
self.pi_layer = PILayer(pi_nodes, **kwargs)
self.ii_layer = FFLayer(ii_nodes, **iiargs)
self.ip_layer = IPLayer()
def call(self, tensors):
ind_2, prop, basis = tensors
prop = self.pp_layer(prop)
inter = self.pi_layer([ind_2, prop, basis])
inter = self.ii_layer(inter)
prop = self.ip_layer([ind_2, prop, inter])
return prop
class ResUpdate(tf.keras.layers.Layer):
def __init__(self):
super(ResUpdate, self).__init__()
def build(self, shapes):
assert isinstance(shapes, list) and len(shapes)==2
if shapes[0][-1] == shapes[1][-1]:
self.transform = lambda x:x
else:
self.transform = tf.keras.layers.Dense(
shapes[1][-1], use_bias=False, activation=None)
def call(self, tensors):
old, new = tensors
return self.transform(old) + new
class PreprocessLayer(tf.keras.layers.Layer):
def __init__(self, atom_types, rc):
super(PreprocessLayer, self).__init__()
self.embed = AtomicOnehot(atom_types)
self.nl_layer = CellListNL(rc)
def call(self, tensors):
tensors = tensors.copy()
for k in ['elems', 'dist']:
if k in tensors.keys():
tensors[k] = tf.reshape(tensors[k], tf.shape(tensors[k])[:1])
if 'ind_2' not in tensors:
tensors.update(self.nl_layer(tensors))
tensors['prop'] = tf.cast(
self.embed(tensors['elems']), tensors['coord'].dtype)
return tensors
class PiNet(tf.keras.Model):
"""Keras model for the PiNet neural network
Args:
tensors: input data (nested tensor from dataset).
atom_types (list): elements for the one-hot embedding.
pp_nodes (list): number of nodes for pp layer.
pi_nodes (list): number of nodes for pi layer.
ii_nodes (list): number of nodes for ii layer.
en_nodes (list): number of nodes for en layer.
depth (int): number of interaction blocks.
rc (float): cutoff radius.
basis_type (string): type of basis function to use,
can be "polynomial" or "gaussian".
n_basis (int): number of basis functions to use.
gamma (float or array): width of gaussian function for gaussian basis.
center (float or array): center of gaussian function for gaussian basis.
cutoff_type (string): cutoff function to use with the basis.
act (string): activation function to use.
preprocess (bool): whether to return the preprocessed tensor.
"""
def __init__(self, atom_types=[1, 6, 7, 8], rc=4.0, cutoff_type='f1',
basis_type='polynomial', n_basis=4, gamma=3.0, center=None,
pp_nodes=[16, 16], pi_nodes=[16, 16], ii_nodes=[16, 16],
out_nodes=[16, 16], out_units=1, out_pool=False,
act='tanh', depth=4):
super(PiNet, self).__init__()
self.depth = depth
self.preprocess = PreprocessLayer(atom_types, rc)
self.cutoff = CutoffFunc(rc, cutoff_type)
if basis_type == 'polynomial':
self.basis_fn = PolynomialBasis(n_basis)
elif basis_type == 'gaussian':
self.basis_fn = GaussianBasis(center, gamma, rc, n_basis)
self.res_update = [ResUpdate() for i in range(depth)]
self.gc_blocks = [GCBlock([], pi_nodes, ii_nodes, activation=act)]
self.gc_blocks += [GCBlock(pp_nodes, pi_nodes, ii_nodes, activation=act)
for i in range(depth-1)]
self.out_layers = [OutLayer(out_nodes, out_units) for i in range(depth)]
self.ann_output = ANNOutput(out_pool)
def call(self, tensors):
tensors = self.preprocess(tensors)
fc = self.cutoff(tensors['dist'])
basis = self.basis_fn(tensors['dist'], fc=fc)
output = 0.0
for i in range(self.depth):
prop = self.gc_blocks[i]([tensors['ind_2'], tensors['prop'], basis])
output = self.out_layers[i]([tensors['ind_1'], prop, output])
tensors['prop'] = self.res_update[i]([tensors['prop'], prop])
output = self.ann_output([tensors['ind_1'], output])
return output
|
3221c5070e1ca770f5c6cd0be2a5f353f1c399b1
|
3a6a211ea0d32405497fbd6486c490bb147e25f9
|
/third_party/gsutil/gslib/__init__.py
|
6ab6c62afc6a187466c908a73e48bf41ab2642ce
|
[
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
catapult-project/catapult
|
e2cbdd5eb89f3b1492fc8752494e62ea1df4bae0
|
53102de187a48ac2cfc241fef54dcbc29c453a8e
|
refs/heads/main
| 2021-05-25T07:37:22.832505
| 2021-05-24T08:01:49
| 2021-05-25T06:07:38
| 33,947,548
| 2,032
| 742
|
BSD-3-Clause
| 2022-08-26T16:01:18
| 2015-04-14T17:49:05
|
HTML
|
UTF-8
|
Python
| false
| false
| 6,365
|
py
|
__init__.py
|
# -*- coding: utf-8 -*-
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""Package marker file."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import os
import pkgutil
import sys
import tempfile
import gslib.exception # pylint: disable=g-import-not-at-top
from gslib.utils.version_check import check_python_version_support
supported, err = check_python_version_support()
if not supported:
raise gslib.exception.CommandException(err)
sys.exit(1)
coverage_outfile = os.getenv('GSUTIL_COVERAGE_OUTPUT_FILE', None)
if coverage_outfile:
try:
import coverage # pylint: disable=g-import-not-at-top
coverage_controller = coverage.coverage(data_file=coverage_outfile,
data_suffix=True,
auto_data=True,
source=['gslib'],
omit=[
'gslib/third_party/*',
'gslib/tests/*',
tempfile.gettempdir() + '*',
])
coverage_controller.start()
except ImportError:
pass
# Directory containing the gslib module.
GSLIB_DIR = os.path.dirname(os.path.realpath(__file__))
# Path to gsutil executable. This assumes gsutil is the running script.
GSUTIL_PATH = os.path.realpath(sys.argv[0])
# The directory that contains the gsutil executable.
GSUTIL_DIR = os.path.dirname(GSUTIL_PATH)
# Whether or not this was installed via a package manager like pip, deb, rpm,
# etc. If installed by just extracting a tarball or zip file, this will be
# False.
IS_PACKAGE_INSTALL = True
# Whether or not this was installed via setup.py develop mode. This creates a
# symlink directly to the source directory.
IS_EDITABLE_INSTALL = False
# Directory where program files like VERSION and CHECKSUM will be. When
# installed via tarball, this is the gsutil directory, but the files are moved
# to the gslib directory when installed via setup.py.
PROGRAM_FILES_DIR = GSLIB_DIR
# The gslib directory will be underneath the gsutil directory when installed
# from a tarball, but somewhere else on the machine if installed via setup.py.
if (not os.path.isfile(os.path.join(PROGRAM_FILES_DIR, 'VERSION')) and
os.path.commonprefix((GSUTIL_DIR, GSLIB_DIR)) == GSUTIL_DIR):
IS_PACKAGE_INSTALL = False
PROGRAM_FILES_DIR = GSUTIL_DIR
# If the module was installed from source using editable mode
# (i.e. pip install -e) then the files might be one directory up.
if not os.path.isfile(os.path.join(PROGRAM_FILES_DIR, 'VERSION')):
PROGRAM_FILES_DIR = os.path.normpath(os.path.join(GSLIB_DIR, '..'))
IS_EDITABLE_INSTALL = True
def _AddVendoredDepsToPythonPath():
"""Fix our Python path so that it correctly finds our vendored libraries."""
vendored_path = os.path.join(GSLIB_DIR, 'vendored')
# Similar structure to the THIRD_PARTY_LIBS list in gsutil.py:
vendored_lib_dirs = [
('boto', ''),
]
# Prepend our vendored libraries to be in the front of the Python path so that
# they're found before any system installations that might be present.
for libdir, subdir in vendored_lib_dirs:
sys.path.insert(0, os.path.join(vendored_path, libdir, subdir))
# This is the location of mock_storage_location module. Not every directory
# in this path has an __init__.py file, so we couldn't just run
# `from boto.tests.integration.s3 import mock_storage_service`.
#
# We add this to the end, rather than prepending it, so that if other
# modules in this directory have the same name as something in our library,
# we find our version first.
sys.path.append(
os.path.join(vendored_path, 'boto', 'tests', 'integration', 's3'))
_AddVendoredDepsToPythonPath()
def _GetFileContents(filename):
"""Tries to find the given filename on disk or via pkgutil.get_data.
Args:
filename: String name of the file.
Returns:
A tuple containing the absolute path to the requested file and the file's
contents as a string (or None if the file doesn't exist).
"""
fpath = os.path.join(PROGRAM_FILES_DIR, filename)
if os.path.isfile(fpath):
with open(fpath, 'r') as f:
content = f.read()
else:
content = pkgutil.get_data('gslib', filename)
fpath = None
if content is not None:
if sys.version_info.major > 2 and isinstance(content, bytes):
content = content.decode('utf-8')
content = content.strip()
return (fpath, content)
# Get the version file and store it.
VERSION_FILE, VERSION = _GetFileContents('VERSION')
if not VERSION:
raise gslib.exception.CommandException(
'VERSION file not found. Please reinstall gsutil from scratch')
__version__ = VERSION
# Get the checksum file and store it.
CHECKSUM_FILE, CHECKSUM = _GetFileContents('CHECKSUM')
if not CHECKSUM:
raise gslib.exception.CommandException(
'CHECKSUM file not found. Please reinstall gsutil from scratch')
def GetGsutilVersionModifiedTime():
"""Returns unix timestamp of when the VERSION file was last modified."""
if not VERSION_FILE:
return 0
return int(os.path.getmtime(VERSION_FILE))
|
257f1e2720255f3cff57a0bd0972de077bbc5ab7
|
21f35d6b81c94bd1ed07b923482c1a9e17423d4c
|
/examples/plot_1_exp.py
|
3d0253ce645f8324c6bb430f3e249557f15e3f94
|
[] |
permissive
|
sphinx-gallery/sphinx-gallery
|
06378c2ecedf9cb306b3958327a1ba294c8d6725
|
4e298a6ccee1c4ff8b33cd65371127118f626032
|
refs/heads/master
| 2023-08-17T06:30:59.195322
| 2023-08-15T16:00:25
| 2023-08-15T16:00:25
| 25,860,190
| 382
| 235
|
BSD-3-Clause
| 2023-09-12T15:29:13
| 2014-10-28T08:41:46
|
Python
|
UTF-8
|
Python
| false
| false
| 1,088
|
py
|
plot_1_exp.py
|
"""
Plotting the exponential function
=================================
This example demonstrates how to import a local module and how images are
stacked when two plots are created in one code block. The variable ``N`` from
the example 'Local module' (file ``local_module.py``) is imported in the code
below. Further, note that when there is only one code block in an example, the
output appears before the code block.
"""
# Code source: Óscar Nájera
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
# You can use modules local to the example being run, here we import
# N from local_module
from local_module import N # = 100
def main():
x = np.linspace(-1, 2, N)
y = np.exp(x)
plt.figure()
plt.plot(x, y)
plt.xlabel("$x$")
plt.ylabel(r"$\exp(x)$")
plt.title("Exponential function")
plt.figure()
plt.plot(x, -np.exp(-x))
plt.xlabel("$x$")
plt.ylabel(r"$-\exp(-x)$")
plt.title("Negative exponential\nfunction")
# To avoid matplotlib text output
plt.show()
if __name__ == "__main__":
main()
|
1afd85b0baa3fa138ff10348a17febcae40556ab
|
3a3089cd8caba86cd4cb2bb043d2b42f91bf7647
|
/tests/test_key_utils.py
|
71ec16be9c046f5ca89fec757848dfe8c0a029d5
|
[
"Apache-2.0"
] |
permissive
|
aws/aws-ec2-instance-connect-cli
|
ab17477afd5464695308dc41a5b178345577e78a
|
536a3e6ab02cfe62ddff7dcfaece279e67573fd7
|
refs/heads/master
| 2023-07-01T18:27:29.781011
| 2023-06-15T21:48:52
| 2023-06-15T21:48:52
| 141,064,336
| 156
| 49
|
Apache-2.0
| 2023-06-15T21:48:54
| 2018-07-15T23:03:03
|
Python
|
UTF-8
|
Python
| false
| false
| 7,261
|
py
|
test_key_utils.py
|
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
from cryptography.hazmat.backends import default_backend as crypto_default_backend
from cryptography.hazmat.primitives import serialization as crypto_serialization
from ec2instanceconnectcli import key_utils
from unittest import TestCase
try:
from unittest import mock
except ImportError:
import mock
class TestKeyUtils(TestCase):
password = 'password'
mock_key = mock.Mock()
public_exponent = 65537
key_size = 2048
@mock.patch('cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key')
def test_generate_key(self, mock_gen_key):
key_utils.generate_key(self.key_size)
mock_gen_key.assert_called_with(backend=crypto_default_backend(),
public_exponent=self.public_exponent,
key_size=self.key_size)
def test_invalid_encodings(self):
try:
key_utils.serialize_key(self.mock_key, encoding='INVALID')
self.fail('Invalid encoding accepted')
except AssertionError:
pass
try:
key_utils.serialize_key(self.mock_key, encoding='OpenSSH', return_private=True)
self.fail('Private keys shouldn''t accept OpenSSH encoding')
except AssertionError:
pass
def test_public_encodings(self):
mock_pub_key = mock.Mock()
self.mock_key.public_key.return_value = mock_pub_key
calls = [mock.call(encoding=crypto_serialization.Encoding.OpenSSH,
format=crypto_serialization.PublicFormat.OpenSSH),
mock.call(encoding=crypto_serialization.Encoding.DER,
format=crypto_serialization.PublicFormat.SubjectPublicKeyInfo),
mock.call(encoding=crypto_serialization.Encoding.PEM,
format=crypto_serialization.PublicFormat.SubjectPublicKeyInfo)]
key_utils.serialize_key(self.mock_key, encoding='OpenSSH', return_private=False)
key_utils.serialize_key(self.mock_key, encoding='DER', return_private=False)
key_utils.serialize_key(self.mock_key, encoding='PEM', return_private=False)
mock_pub_key.public_bytes.assert_has_calls(calls)
@mock.patch('cryptography.hazmat.primitives.serialization.NoEncryption')
def test_private_encodings(self, mock_encryption):
mock_enc = mock.Mock()
mock_encryption.return_value = mock_enc
calls = [mock.call(encoding=crypto_serialization.Encoding.DER,
format=crypto_serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=mock_enc),
mock.call(encoding=crypto_serialization.Encoding.PEM,
format=crypto_serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=mock_enc)]
key_utils.serialize_key(self.mock_key, encoding='DER', return_private=True)
key_utils.serialize_key(self.mock_key, encoding='PEM', return_private=True)
self.mock_key.private_bytes.assert_has_calls(calls)
@mock.patch('cryptography.hazmat.primitives.serialization.BestAvailableEncryption')
def test_private_password(self, mock_encryption):
mock_enc = mock.Mock()
mock_encryption.return_value = mock_enc
key_utils.serialize_key(self.mock_key, encoding='PEM', return_private=True, password=self.password)
mock_encryption.assert_called_with(self.password)
self.mock_key.private_bytes.assert_called_with(
encoding=crypto_serialization.Encoding.PEM,
format=crypto_serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=mock_enc)
@mock.patch('ec2instanceconnectcli.key_utils.serialize_key')
@mock.patch('cryptography.hazmat.primitives.serialization.load_der_private_key')
def test_convert_der_pem_private(self, mock_load_private, mock_serialize):
mock_load_private.return_value = self.mock_key
key_utils.convert_der_to_pem(self.mock_key, is_private=True)
calls = [mock.call(self.mock_key, encoding='PEM', return_private=True)]
mock_load_private.assert_called_with(self.mock_key, backend=crypto_default_backend())
mock_serialize.assert_has_calls(calls)
@mock.patch('cryptography.hazmat.primitives.serialization.load_der_public_key')
def test_convert_der_pem_public(self, mock_load_public):
mock_load_public.return_value = self.mock_key
key_utils.convert_der_to_pem(self.mock_key, is_private=False)
mock_load_public.assert_called_with(self.mock_key, backend=crypto_default_backend())
self.mock_key.public_bytes.assert_called_with(
encoding=crypto_serialization.Encoding.PEM,
format=crypto_serialization.PublicFormat.SubjectPublicKeyInfo)
@mock.patch('ec2instanceconnectcli.key_utils.serialize_key')
@mock.patch('cryptography.hazmat.primitives.serialization.load_pem_private_key')
def test_convert_pem_der_private(self, mock_load_private, mock_serialize):
mock_load_private.return_value = self.mock_key
fake_priv = str.encode("{0}\n".format(key_utils.begin_key.format(key_utils.private_str)))
key_utils.convert_pem_to_der(fake_priv)
calls = [mock.call(self.mock_key, encoding='DER', return_private=True)]
mock_load_private.assert_called_with(fake_priv, backend=crypto_default_backend())
mock_serialize.assert_has_calls(calls)
@mock.patch('cryptography.hazmat.primitives.serialization.load_pem_public_key')
def test_convert_pem_der_public(self, mock_load_public):
mock_load_public.return_value = self.mock_key
fake_pub = str.encode("{0}\n".format(key_utils.begin_key.format(key_utils.public_str)))
key_utils.convert_pem_to_der(fake_pub)
mock_load_public.assert_called_with(fake_pub, backend=crypto_default_backend())
self.mock_key.public_bytes.assert_called_with(
encoding=crypto_serialization.Encoding.DER,
format=crypto_serialization.PublicFormat.SubjectPublicKeyInfo)
@mock.patch('cryptography.hazmat.primitives.serialization.load_pem_public_key')
def test_convert_pem_to_openssh(self, mock_load_public):
mock_load_public.return_value = self.mock_key
key_utils.convert_pem_to_openssh(self.mock_key)
mock_load_public.assert_called_with(self.mock_key, backend=crypto_default_backend())
self.mock_key.public_bytes.assert_called_with(
encoding=crypto_serialization.Encoding.OpenSSH,
format=crypto_serialization.PublicFormat.OpenSSH)
|
cd7eec6352b21a3c62a00d35f18e0f9358bb0f08
|
60d6b8501d0be546437b26a6ee1f9fab97ec3897
|
/platypush/schemas/system/_fan/__init__.py
|
d3433f3208c53e7d9e84e1f75c5d38c84951ea9f
|
[
"MIT"
] |
permissive
|
BlackLight/platypush
|
68284a85b2f9eef303d26b04530f075927b5834a
|
446bc2f67493d3554c5422242ff91d5b5c76d78a
|
refs/heads/master
| 2023-08-31T21:01:53.519960
| 2023-08-29T22:05:38
| 2023-08-29T22:05:38
| 109,421,017
| 265
| 25
|
MIT
| 2023-09-01T23:15:49
| 2017-11-03T16:56:24
|
Python
|
UTF-8
|
Python
| false
| false
| 88
|
py
|
__init__.py
|
from ._model import Fan
from ._schemas import FanSchema
__all__ = ["Fan", "FanSchema"]
|
242c57808a8632394cf5a7873c90895bc0dd6faf
|
bb33e6be8316f35decbb2b81badf2b6dcf7df515
|
/source/res/scripts/client/gui/impl/gen/view_models/views/lobby/wt_event/tooltips/wt_event_ammunition_tooltip_view_model.py
|
b67683ffed1e10b3709647a5e461ba95ac6986a8
|
[] |
no_license
|
StranikS-Scan/WorldOfTanks-Decompiled
|
999c9567de38c32c760ab72c21c00ea7bc20990c
|
d2fe9c195825ececc728e87a02983908b7ea9199
|
refs/heads/1.18
| 2023-08-25T17:39:27.718097
| 2022-09-22T06:49:44
| 2022-09-22T06:49:44
| 148,696,315
| 103
| 39
| null | 2022-09-14T17:50:03
| 2018-09-13T20:49:11
|
Python
|
UTF-8
|
Python
| false
| false
| 1,853
|
py
|
wt_event_ammunition_tooltip_view_model.py
|
# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/gui/impl/gen/view_models/views/lobby/wt_event/tooltips/wt_event_ammunition_tooltip_view_model.py
from gui.impl.gen import R
from frameworks.wulf import ViewModel
class WtEventAmmunitionTooltipViewModel(ViewModel):
__slots__ = ()
def __init__(self, properties=7, commands=0):
super(WtEventAmmunitionTooltipViewModel, self).__init__(properties=properties, commands=commands)
def getIcon(self):
return self._getResource(0)
def setIcon(self, value):
self._setResource(0, value)
def getTitle(self):
return self._getString(1)
def setTitle(self, value):
self._setString(1, value)
def getDescription(self):
return self._getString(2)
def setDescription(self, value):
self._setString(2, value)
def getAnimation(self):
return self._getString(3)
def setAnimation(self, value):
self._setString(3, value)
def getSubtitle(self):
return self._getString(4)
def setSubtitle(self, value):
self._setString(4, value)
def getText(self):
return self._getString(5)
def setText(self, value):
self._setString(5, value)
def getAdditionalInfoText(self):
return self._getString(6)
def setAdditionalInfoText(self, value):
self._setString(6, value)
def _initialize(self):
super(WtEventAmmunitionTooltipViewModel, self)._initialize()
self._addResourceProperty('icon', R.invalid())
self._addStringProperty('title', '')
self._addStringProperty('description', '')
self._addStringProperty('animation', '')
self._addStringProperty('subtitle', '')
self._addStringProperty('text', '')
self._addStringProperty('additionalInfoText', '')
|
b84b594a5f97fcdba987f719156fb929d0108c0b
|
f80ef3a3cf859b13e8af8433af549b6b1043bf6e
|
/pyobjc-framework-Contacts/PyObjCTest/test_cngroup.py
|
4b9fbd34b6077c65b5222275a2f28193b562d0a3
|
[
"MIT"
] |
permissive
|
ronaldoussoren/pyobjc
|
29dc9ca0af838a56105a9ddd62fb38ec415f0b86
|
77b98382e52818690449111cd2e23cd469b53cf5
|
refs/heads/master
| 2023-09-01T05:15:21.814504
| 2023-06-13T20:00:17
| 2023-06-13T20:00:17
| 243,933,900
| 439
| 49
| null | 2023-06-25T02:49:07
| 2020-02-29T08:43:12
|
Python
|
UTF-8
|
Python
| false
| false
| 288
|
py
|
test_cngroup.py
|
from PyObjCTools.TestSupport import TestCase, min_os_level
import Contacts
class TestCNGroup(TestCase):
@min_os_level("10.11")
def testConstants(self):
self.assertIsInstance(Contacts.CNGroupIdentifierKey, str)
self.assertIsInstance(Contacts.CNGroupNameKey, str)
|
1c09ad023d0c6e732131e18bf740f1dfa4d37a3c
|
1577e1cf4e89584a125cffb855ca50a9654c6d55
|
/pyobjc/pyobjc/pyobjc-framework-Quartz-2.5.1/PyObjCTest/test_cgdisplayconfiguration.py
|
aab8941c8a8d216e099eb9f79b1508d7aa1d6018
|
[
"MIT"
] |
permissive
|
apple-open-source/macos
|
a4188b5c2ef113d90281d03cd1b14e5ee52ebffb
|
2d2b15f13487673de33297e49f00ef94af743a9a
|
refs/heads/master
| 2023-08-01T11:03:26.870408
| 2023-03-27T00:00:00
| 2023-03-27T00:00:00
| 180,595,052
| 124
| 24
| null | 2022-12-27T14:54:09
| 2019-04-10T14:06:23
| null |
UTF-8
|
Python
| false
| false
| 5,788
|
py
|
test_cgdisplayconfiguration.py
|
from PyObjCTools.TestSupport import *
from Quartz.CoreGraphics import *
try:
long
except NameError:
long = int
class TestCGDisplayConfiguration (TestCase):
def testTypes(self):
self.assertIsOpaquePointer(CGDisplayConfigRef)
err, config = CGBeginDisplayConfiguration(None)
self.assertEqual(err, 0)
self.assertIsInstance(config, CGDisplayConfigRef)
err = CGConfigureDisplayOrigin(config,
CGMainDisplayID(), 0, 0)
self.assertEqual(err, 0)
err = CGConfigureDisplayMode(config,
CGMainDisplayID(), CGDisplayAvailableModes(CGMainDisplayID())[0])
self.assertEqual(err, 0)
err = CGConfigureDisplayStereoOperation(config,
CGMainDisplayID(), False, False)
self.assertEqual(err, 0)
err = CGConfigureDisplayMirrorOfDisplay(config,
CGMainDisplayID(), CGMainDisplayID())
self.assertIsInstance(err, (int, long))
err = CGCancelDisplayConfiguration(config)
self.assertEqual(err, 0)
config = None
myInfo = object()
info = []
def reconfig(display, flags, userInfo):
self.assertIsInstance(display, (int, long))
self.assertIsInstance(flags, (int, long))
self.assertTrue(userInfo is myInfo)
info.append((display, flags, userInfo))
try:
err, config = CGBeginDisplayConfiguration(None)
self.assertEqual(err, 0)
self.assertIsInstance(config, CGDisplayConfigRef)
err = CGDisplayRegisterReconfigurationCallback(reconfig, myInfo)
self.assertEqual(err, 0)
err = CGConfigureDisplayMode(config,
CGMainDisplayID(), CGDisplayAvailableModes(CGMainDisplayID())[0])
CGCompleteDisplayConfiguration(config, kCGConfigureForAppOnly)
# XXX: For some reason this fails on OSX 10.5:
if os_release() > (10, 5):
self.assertTrue(len(info) > 0)
finally:
err = CGDisplayRemoveReconfigurationCallback(reconfig, myInfo)
self.assertEqual(err, 0)
l = len(info)
CGRestorePermanentDisplayConfiguration()
self.assertEqual(len(info), l)
err = CGDisplaySetStereoOperation(CGMainDisplayID(), False, False, kCGConfigureForAppOnly)
self.assertIsInstance(err, (int, long))
v = CGDisplayIsActive(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayIsAsleep(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayIsOnline(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayIsMain(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayIsBuiltin(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayIsInMirrorSet(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayIsAlwaysInMirrorSet(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayIsInHWMirrorSet(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayMirrorsDisplay(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayIsStereo(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayPrimaryDisplay(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayUnitNumber(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayVendorNumber(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayModelNumber(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplaySerialNumber(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayIOServicePort(CGMainDisplayID())
self.assertIsInstance(v, (int, long))
v = CGDisplayScreenSize(CGMainDisplayID())
self.assertIsInstance(v, CGSize)
v = CGDisplayRotation(CGMainDisplayID())
self.assertIsInstance(v, float)
v = CGDisplayCopyColorSpace(CGMainDisplayID())
self.assertIsInstance(v, CGColorSpaceRef)
def testContents(self):
self.assertEqual(kCGConfigureForAppOnly, 0)
self.assertEqual(kCGConfigureForSession, 1)
self.assertEqual(kCGConfigurePermanently, 2)
self.assertEqual(kCGDisplayBeginConfigurationFlag, (1 << 0))
self.assertEqual(kCGDisplayMovedFlag, (1 << 1))
self.assertEqual(kCGDisplaySetMainFlag, (1 << 2))
self.assertEqual(kCGDisplaySetModeFlag, (1 << 3))
self.assertEqual(kCGDisplayAddFlag, (1 << 4))
self.assertEqual(kCGDisplayRemoveFlag, (1 << 5))
self.assertEqual(kCGDisplayEnabledFlag, (1 << 8))
self.assertEqual(kCGDisplayDisabledFlag, (1 << 9))
self.assertEqual(kCGDisplayMirrorFlag, (1 << 10))
self.assertEqual(kCGDisplayUnMirrorFlag, (1 << 11))
self.assertEqual(kCGDisplayDesktopShapeChangedFlag, (1 << 12))
@min_os_level('10.6')
def testFunctions10_6(self):
self.assertResultHasType(CGConfigureDisplayWithDisplayMode, b'i')
self.assertArgHasType(CGConfigureDisplayWithDisplayMode, 0,
b'^{_CGDisplayConfigRef=}')
self.assertArgHasType(CGConfigureDisplayWithDisplayMode, 1,
b'I')
self.assertArgHasType(CGConfigureDisplayWithDisplayMode, 2,
b'^{CGDisplayMode=}')
self.assertArgHasType(CGConfigureDisplayWithDisplayMode, 3,
b'^{__CFDictionary=}')
if __name__ == "__main__":
main()
|
ad79aeaa79fbae6e35d4e1fc1d2a15c936f67906
|
c1ff870879152fba2b54eddfb7591ec322eb3061
|
/plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/deps/v8/tools/jsmin.py
|
236f511d447b228e9b5473dddba99fb93902397e
|
[
"ISC",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"Artistic-2.0",
"NAIST-2003",
"MIT",
"BSD-3-Clause",
"Zlib",
"NTP",
"LicenseRef-scancode-openssl",
"ICU",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-unknown-license-reference",
"bzip2-1.0.6",
"SunPro",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
MTASZTAKI/ApertusVR
|
1a9809fb7af81c3cd7fb732ed481ebe4ce66fefa
|
424ec5515ae08780542f33cc4841a8f9a96337b3
|
refs/heads/0.9
| 2022-12-11T20:03:42.926813
| 2019-10-11T09:29:45
| 2019-10-11T09:29:45
| 73,708,854
| 188
| 55
|
MIT
| 2022-12-11T08:53:21
| 2016-11-14T13:48:00
|
C++
|
UTF-8
|
Python
| false
| false
| 11,383
|
py
|
jsmin.py
|
#!/usr/bin/python2.4
# Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""A JavaScript minifier.
It is far from being a complete JS parser, so there are many valid
JavaScript programs that will be ruined by it. Another strangeness is that
it accepts $ and % as parts of identifiers. It doesn't merge lines or strip
out blank lines in order to ease debugging. Variables at the top scope are
properties of the global object so we can't rename them. It is assumed that
you introduce variables with var as if JavaScript followed C++ scope rules
around curly braces, so the declaration must be above the first use.
Use as:
import jsmin
minifier = JavaScriptMinifier()
program1 = minifier.JSMinify(program1)
program2 = minifier.JSMinify(program2)
"""
import re
class JavaScriptMinifier(object):
"""An object that you can feed code snippets to to get them minified."""
def __init__(self):
# We prepopulate the list of identifiers that shouldn't be used. These
# short language keywords could otherwise be used by the script as variable
# names.
self.seen_identifiers = {"do": True, "in": True}
self.identifier_counter = 0
self.in_comment = False
self.map = {}
self.nesting = 0
def LookAtIdentifier(self, m):
"""Records identifiers or keywords that we see in use.
(So we can avoid renaming variables to these strings.)
Args:
m: The match object returned by re.search.
Returns:
Nothing.
"""
identifier = m.group(1)
self.seen_identifiers[identifier] = True
def Push(self):
"""Called when we encounter a '{'."""
self.nesting += 1
def Pop(self):
"""Called when we encounter a '}'."""
self.nesting -= 1
# We treat each top-level opening brace as a single scope that can span
# several sets of nested braces.
if self.nesting == 0:
self.map = {}
self.identifier_counter = 0
def Declaration(self, m):
"""Rewrites bits of the program selected by a regexp.
These can be curly braces, literal strings, function declarations and var
declarations. (These last two must be on one line including the opening
curly brace of the function for their variables to be renamed).
Args:
m: The match object returned by re.search.
Returns:
The string that should replace the match in the rewritten program.
"""
matched_text = m.group(0)
if matched_text.startswith("`") and matched_text.endswith("`"):
return re.sub(r"\$\{([\w$%]+)\}",
lambda m: '${' + self.FindNewName(m.group(1)) + '}',
matched_text)
if matched_text == "{":
self.Push()
return matched_text
if matched_text == "}":
self.Pop()
return matched_text
if re.match("[\"'/]", matched_text):
return matched_text
m = re.match(r"var ", matched_text)
if m:
var_names = matched_text[m.end():]
var_names = re.split(r",", var_names)
return "var " + ",".join(map(self.FindNewName, var_names))
m = re.match(r"(function\b[^(]*)\((.*)\)\{$", matched_text)
if m:
up_to_args = m.group(1)
args = m.group(2)
args = re.split(r",", args)
self.Push()
return up_to_args + "(" + ",".join(map(self.FindNewName, args)) + "){"
if matched_text in self.map:
return self.map[matched_text]
return matched_text
def CharFromNumber(self, number):
"""A single-digit base-52 encoding using a-zA-Z."""
if number < 26:
return chr(number + 97)
number -= 26
return chr(number + 65)
def FindNewName(self, var_name):
"""Finds a new 1-character or 2-character name for a variable.
Enters it into the mapping table for this scope.
Args:
var_name: The name of the variable before renaming.
Returns:
The new name of the variable.
"""
new_identifier = ""
# Variable names that end in _ are member variables of the global object,
# so they can be visible from code in a different scope. We leave them
# alone.
if var_name in self.map:
return self.map[var_name]
if self.nesting == 0:
return var_name
# Do not rename arguments object.
if var_name == 'arguments':
return 'arguments'
while True:
identifier_first_char = self.identifier_counter % 52
identifier_second_char = self.identifier_counter // 52
new_identifier = self.CharFromNumber(identifier_first_char)
if identifier_second_char != 0:
new_identifier = (
self.CharFromNumber(identifier_second_char - 1) + new_identifier)
self.identifier_counter += 1
if not new_identifier in self.seen_identifiers:
break
self.map[var_name] = new_identifier
return new_identifier
def RemoveSpaces(self, m):
"""Returns literal strings unchanged, replaces other inputs with group 2.
Other inputs are replaced with the contents of capture 1. This is either
a single space or an empty string.
Args:
m: The match object returned by re.search.
Returns:
The string that should be inserted instead of the matched text.
"""
entire_match = m.group(0)
replacement = m.group(1)
if re.match(r"'.*'$", entire_match):
return entire_match
if re.match(r'".*"$', entire_match):
return entire_match
if re.match(r"`.*`$", entire_match):
return entire_match
if re.match(r"/.+/$", entire_match):
return entire_match
return replacement
def JSMinify(self, text):
"""The main entry point. Takes a text and returns a compressed version.
The compressed version hopefully does the same thing. Line breaks are
preserved.
Args:
text: The text of the code snippet as a multiline string.
Returns:
The compressed text of the code snippet as a multiline string.
"""
new_lines = []
for line in re.split(r"\n", text):
line = line.replace("\t", " ")
if self.in_comment:
m = re.search(r"\*/", line)
if m:
line = line[m.end():]
self.in_comment = False
else:
new_lines.append("")
continue
if not self.in_comment:
line = re.sub(r"/\*.*?\*/", " ", line)
line = re.sub(r"//.*", "", line)
m = re.search(r"/\*", line)
if m:
line = line[:m.start()]
self.in_comment = True
# Strip leading and trailing spaces.
line = re.sub(r"^ +", "", line)
line = re.sub(r" +$", "", line)
# A regexp that matches a literal string surrounded by "double quotes".
# This regexp can handle embedded backslash-escaped characters including
# embedded backslash-escaped double quotes.
double_quoted_string = r'"(?:[^"\\]|\\.)*"'
# A regexp that matches a literal string surrounded by 'single quotes'.
single_quoted_string = r"'(?:[^'\\]|\\.)*'"
# A regexp that matches a template string
template_string = r"`(?:[^`\\]|\\.)*`"
# A regexp that matches a regexp literal surrounded by /slashes/.
# Don't allow a regexp to have a ) before the first ( since that's a
# syntax error and it's probably just two unrelated slashes.
# Also don't allow it to come after anything that can only be the
# end of a primary expression.
slash_quoted_regexp = r"(?<![\w$'\")\]])/(?:(?=\()|(?:[^()/\\]|\\.)+)(?:\([^/\\]|\\.)*/"
# Replace multiple spaces with a single space.
line = re.sub("|".join([double_quoted_string,
single_quoted_string,
template_string,
slash_quoted_regexp,
"( )+"]),
self.RemoveSpaces,
line)
# Strip single spaces unless they have an identifier character both before
# and after the space. % and $ are counted as identifier characters.
line = re.sub("|".join([double_quoted_string,
single_quoted_string,
template_string,
slash_quoted_regexp,
r"(?<![a-zA-Z_0-9$%]) | (?![a-zA-Z_0-9$%])()"]),
self.RemoveSpaces,
line)
# Collect keywords and identifiers that are already in use.
if self.nesting == 0:
re.sub(r"([a-zA-Z0-9_$%]+)", self.LookAtIdentifier, line)
function_declaration_regexp = (
r"\bfunction" # Function definition keyword...
r"( [\w$%]+)?" # ...optional function name...
r"\([\w$%,]+\)\{") # ...argument declarations.
# Unfortunately the keyword-value syntax { key:value } makes the key look
# like a variable where in fact it is a literal string. We use the
# presence or absence of a question mark to try to distinguish between
# this case and the ternary operator: "condition ? iftrue : iffalse".
if re.search(r"\?", line):
block_trailing_colon = r""
else:
block_trailing_colon = r"(?![:\w$%])"
# Variable use. Cannot follow a period precede a colon.
variable_use_regexp = r"(?<![.\w$%])[\w$%]+" + block_trailing_colon
line = re.sub("|".join([double_quoted_string,
single_quoted_string,
template_string,
slash_quoted_regexp,
r"\{", # Curly braces.
r"\}",
r"\bvar [\w$%,]+", # var declarations.
function_declaration_regexp,
variable_use_regexp]),
self.Declaration,
line)
new_lines.append(line)
return "\n".join(new_lines) + "\n"
|
5d495e04a2fcd969860bb1d5f47ebea3cae8c1b8
|
56a77194fc0cd6087b0c2ca1fb6dc0de64b8a58a
|
/applications/ExaquteSandboxApplication/python_scripts/WindGenerator/RandomMaterial.py
|
1375a8eba65b2e10efd46df281dc90433f616c96
|
[
"BSD-3-Clause"
] |
permissive
|
KratosMultiphysics/Kratos
|
82b902a2266625b25f17239b42da958611a4b9c5
|
366949ec4e3651702edc6ac3061d2988f10dd271
|
refs/heads/master
| 2023-08-30T20:31:37.818693
| 2023-08-30T18:01:01
| 2023-08-30T18:01:01
| 81,815,495
| 994
| 285
|
NOASSERTION
| 2023-09-14T13:22:43
| 2017-02-13T10:58:24
|
C++
|
UTF-8
|
Python
| false
| false
| 6,724
|
py
|
RandomMaterial.py
|
import pyfftw
from math import *
import numpy as np
from scipy.special import erfinv
from scipy import misc
from scipy.signal import convolve2d
# from scipy.special import kv as Kv
# from itertools import product
import os, sys, csv
from time import time
from multiprocessing import Pool, Process
# from joblib import Parallel, delayed
from tqdm import tqdm
import matplotlib.pyplot as plt
# from pyevtk.hl import imageToVTK
from RandomFieldModule.GaussianRandomField import GaussianRandomField
from RandomFieldModule.utilities.common import *
from RandomFieldModule.utilities.ErrorMessages import *
from RandomFieldModule.utilities.Exports import exportVTK
#######################################################################################################
def levelcut(field, level=0):
phase = np.where(field > level, 1, 0)
return phase.astype(np.intc)
def get_vf(phase):
return np.mean(phase)
#######################################################################################################
# Random material generator class
#######################################################################################################
class RandomMaterial:
def __init__(self, grid_level, ndim=2, verbose=0, levelcut_strategy="abs", **kwargs):
self.verbose = verbose
self.ndim = int(ndim) # dimension 2D or 3D
if not (self.ndim==2 or self.ndim==3): msgDimError(self.ndim)
self.N = int(2**grid_level)
self.Nd = self.N * np.ones(self.ndim, dtype=np.intc)
self.nvoxels = np.prod(self.Nd)
### Level-cut strategy:
### 'abs' - level-cut of the abs(field)
### 'sym' - standard level-cut
self.levelcut_strategy = levelcut_strategy
vf = kwargs['vf']
self.set_level(vf)
### Gaussian Random Field (Intensity)
if self.verbose: print('\nBuilding GRF...\n')
self.GRF = GaussianRandomField(grid_level=grid_level, ndim=ndim, verbose=verbose, **kwargs)
#--------------------------------------------------------------------------
# Updates
#--------------------------------------------------------------------------
def set_level(self, vf=None, tau=None):
if vf is not None:
self.vf = vf
self.tau = vf2tau(vf, strategy=self.levelcut_strategy)
elif tau is not None:
self.tau = tau
self.vf = tau2vf(tau, strategy=self.levelcut_strategy)
else:
print('Either expected volume fraction or level set value must be given.')
def reseed(self, seed=None):
self.GRF.reseed(seed)
#--------------------------------------------------------------------------
# Sampling
#--------------------------------------------------------------------------
### Generate a realization
def sample(self, noise=None):
field = self.GRF.sample(noise=noise)
if self.levelcut_strategy is 'abs': field = np.abs(field)
field = levelcut(field, self.tau)
return field
### Generate a family of realizations
def generate_samples(self, nsamples=1, path=None, output_format="png", append=False):
output = False if path is None else True
if output:
if not append or not hasattr(self, 'sample_count'):
os.system('rm -f ' + path + 'sample_*')
self.sample_count = 0
time_start = time()
expected_vf = 0
for isample in tqdm(range(nsamples)):
phase = self.sample()
expected_vf += phase.mean()
if output:
self.sample_count += 1
filename = path + 'sample_{0:d}'.format(self.sample_count)
if self.ndim==2 and output_format is "png": self.save_png(phase, filename)
elif self.ndim==3 or output_format is "vtk": self.save_vtk(phase, filename)
expected_vf /= nsamples
print('All samples generation time: {0} s'.format(time()-time_start))
print('Volume fraction: {0}'.format(expected_vf))
#--------------------------------------------------------------------------
# EXPORTS
#--------------------------------------------------------------------------
def save_png(self, phase, filename):
misc.imsave(filename, (1-phase))
def save_vtk(self, phase, filename):
exportVTK(filename, cellData = {'phase' : phase})
#--------------------------------------------------------------------------
# TESTS
#--------------------------------------------------------------------------
def test_Covariance(self, nsamples=1000):
return self.GRF.test_Covariance(nsamples)
def test_VolumeFraction(self, nsamples=1000):
from RandomMaterial.utilities import compute_ProbaDist, fit_ProbaDist, vf2tau, tau2vf
data = []
for isample in tqdm(range(nsamples)):
phase = self.sample()
vf = phase.mean()
data.append(vf)
p, x = compute_ProbaDist(data)
m, sigma, p_fit = fit_ProbaDist(x, p, type='LogNormal')
print('m={0}, s={1}'.format(exp(m), sigma))
print('expected vf = ', np.mean(data))
plt.plot(x,p)
plt.plot(x,p_fit)
plt.axvline(x=self.vf, color='black')
plt.legend(['vf pdf', 'Fit'])
plt.show()
return 0
def test_TwoPointProbability(self, nsamples=1000):
from RandomMaterial.utilities import autocorrelation
from RandomMaterial.reconstruction import RadialAverage
from utilities.image_statistics import LevelSetGaussian as LSG
C = np.zeros(self.Nd)
for isample in tqdm(range(nsamples)):
phase = self.sample()
C += autocorrelation(phase)
C /= nsamples
S2, Var = RadialAverage(C)
h = 1/self.N
Slope = (S2[1]-S2[0])/h
nu = self.GRF.Covariance.nu
rho = self.GRF.Covariance.corr_len[0]
Slope0 = LSG.S2_slope_at_zero_Matern(self.tau, nu, rho)
print("nu = ", nu)
print("Slope = ", Slope)
print("Slope (analytic) = ", Slope0)
return 0
#######################################################################################################
#######################################################################################################
# Run as main (for testing)
#######################################################################################################
if __name__ == "__main__":
import importlib
config = importlib.import_module(sys.argv[1])
RM = RandomMaterial(config)
|
4acda681d69881e2ebff9fd618f84c4e2e50e3ee
|
2337351b228818e41be3002bd38f68f77c2aa074
|
/services/web/base/docinline.py
|
5cd7941ed422c92715f2c6e03dee72d494c99ef4
|
[
"BSD-3-Clause"
] |
permissive
|
nocproject/noc
|
57d40c680a1499374463e472434f9595ed6d1374
|
6e6d71574e9b9d822bec572cc629a0ea73604a59
|
refs/heads/master
| 2023-08-31T01:11:33.544573
| 2023-08-30T17:31:11
| 2023-08-30T17:31:11
| 107,815,776
| 105
| 33
|
BSD-3-Clause
| 2023-07-31T07:57:45
| 2017-10-21T21:04:33
|
Python
|
UTF-8
|
Python
| false
| false
| 15,282
|
py
|
docinline.py
|
# ---------------------------------------------------------------------
# DocInline
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Python modules
from functools import reduce
# Third-party modules
from mongoengine.fields import StringField, IntField, BooleanField, GeoPointField
from mongoengine.queryset import Q
from mongoengine.errors import NotUniqueError
from bson import ObjectId
# NOC modules
from noc.sa.interfaces.base import (
BooleanParameter,
IntParameter,
InterfaceTypeError,
DocumentParameter,
)
from noc.core.validators import is_int
from noc.core.mongo.fields import PlainReferenceField, ForeignKeyField
from noc.core.comp import smart_text
class DocInline(object):
# HTTP Result Codes
OK = 200
CREATED = 201
DELETED = 204
BAD_REQUEST = 400
FORBIDDEN = 401
NOT_FOUND = 404
CONFLICT = 409
NOT_HERE = 410
INTERNAL_ERROR = 500
NOT_IMPLEMENTED = 501
THROTTLED = 503
# Recognized GET parameters
ignored_params = ["_dc"]
page_param = "__page"
start_param = "__start"
limit_param = "__limit"
sort_param = "__sort"
format_param = "__format" # List output format
query_param = "__query"
only_param = "__only"
query_fields = [] # Use all unique fields by default
query_condition = "startswith" # Match method for string fields
int_query_fields = [] # Query integer fields for exact match
pk_field_name = None # Set by constructor
clean_fields = {} # field name -> Parameter instance
custom_fields = {} # name -> handler, populated automatically
def __init__(self, model):
self.model = model
self.app = None
self.pk_field_name = "id"
# Prepare field converters
self.clean_fields = self.clean_fields.copy() # name -> Parameter
for name, f in self.model._fields.items():
if isinstance(f, BooleanField):
self.clean_fields[name] = BooleanParameter()
elif isinstance(f, IntField):
self.clean_fields[name] = IntParameter()
elif isinstance(f, PlainReferenceField):
self.clean_fields[name] = DocumentParameter(f.document_type)
#
if not self.query_fields:
self.query_fields = [
"%s__%s" % (n, self.query_condition)
for n, f in self.model._fields.items()
if f.unique and isinstance(f, StringField)
]
# Find field_* and populate custom fields
self.custom_fields = {}
for fn in [n for n in dir(self) if n.startswith("field_")]:
h = getattr(self, fn)
if callable(h):
self.custom_fields[fn[6:]] = h
def contribute_to_class(self, app, name):
# Add List handler
app.add_view(
"api_%s_list" % name,
self.api_list,
method=["GET"],
url="^(?P<parent>[^/]+)/%s/$" % name,
access="read",
api=True,
)
# Add Create handler
app.add_view(
"api_%s_create" % name,
self.api_create,
method=["POST"],
url="^(?P<parent>[^/]+)/%s/$" % name,
access="create",
api=True,
)
# Add Read Handler
app.add_view(
"api_%s_read" % name,
self.api_read,
method=["GET"],
url="^(?P<parent>[^/]+)/%s/(?P<id>[^/]+)/?$" % name,
access="read",
api=True,
)
# Add Update Handler
app.add_view(
"api_%s_update" % name,
self.api_update,
method=["PUT"],
url="^(?P<parent>[^/]+)/%s/(?P<id>[^/]+)/?$" % name,
access="update",
api=True,
)
# Add Delete Handler
app.add_view(
"api_%s_delete" % name,
self.api_delete,
method=["DELETE"],
url="^(?P<parent>[^/]+)/%s/(?P<id>[^/]+)/?$" % name,
access="delete",
api=True,
)
def set_app(self, app):
self.app = app
self.logger = app.logger
self.parent_model = self.app.model
self.parent_rel = None
for name in self.model._fields:
f = self.model._fields[name]
if isinstance(f, PlainReferenceField):
if f.document_type_obj == self.parent_model:
self.parent_rel = name
break
assert self.parent_rel
def get_custom_fields(self):
from noc.main.models.customfield import CustomField
return list(CustomField.table_fields(self.model._meta.db_table))
def get_Q(self, request, query):
"""
Prepare Q statement for query
"""
def get_q(f):
if "__" not in f:
return "%s__%s" % (f, self.query_condition)
else:
return f
q = reduce(
lambda x, y: x | Q(**{get_q(y): query}),
self.query_fields[1:],
Q(**{get_q(self.query_fields[0]): query}),
)
if self.int_query_fields and is_int(query):
v = int(query)
for f in self.int_query_fields:
q |= Q(**{f: v})
return q
def queryset(self, request, query=None):
"""
Filter records for lookup
"""
if query and self.query_fields:
return self.model.objects.filter(self.get_Q(request, query))
else:
return self.model.objects.all()
def clean(self, data, parent):
"""
Clean up input data
:param data: dict of parameters
:type data: dict
:return: dict of cleaned parameters of raised InterfaceTypeError
:rtype: dict
"""
# Delete id
if "id" in data:
del data["id"]
# Forcefully set parent
data[self.parent_rel] = parent.id
# Clean up fields
for f in self.clean_fields:
if f in data and f != self.parent_rel:
if data[f] == "":
data[f] = None
else:
data[f] = self.clean_fields[f].clean(data[f])
# Clone data
return {str(k): data[k] for k in data}
def cleaned_query(self, q):
nq = {}
for p in q:
if "__" in p:
np, lt = p.split("__", 1)
else:
np, lt = p, None
# Skip ignored params
if np in self.ignored_params or p in (
self.limit_param,
self.page_param,
self.start_param,
self.format_param,
self.sort_param,
self.query_param,
self.only_param,
):
continue
v = q[p]
if v == "\x00":
v = None
# Pass through interface cleaners
if lt == "referred":
# Unroll __referred
app, fn = v.split("__", 1)
model = self.app.site.apps[app].model
extra_where = '%s."%s" IN (SELECT "%s" FROM %s)' % (
self.model._meta.db_table,
self.model._meta.pk.name,
model._meta.get_field(fn).attname,
model._meta.db_table,
)
if None in nq:
nq[None] += [extra_where]
else:
nq[None] = [extra_where]
continue
elif lt and hasattr(self, "lookup_%s" % lt):
# Custom lookup
getattr(self, "lookup_%s" % lt)(nq, np, v)
continue
elif np in self.fk_fields and lt:
# dereference
try:
nq[np] = self.fk_fields[np].objects.get(**{lt: v})
except self.fk_fields[np].DoesNotExist:
nq[np] = 0 # False search
continue
elif np in self.clean_fields: # @todo: Check for valid lookup types
v = self.clean_fields[np].clean(v)
# Write back
nq[p] = v
return nq
def instance_to_dict(self, o, fields=None):
r = {}
for n, f in o._fields.items():
if fields and n not in fields:
continue
v = getattr(o, n)
if v is not None:
v = f.to_python(v)
if v is not None:
if isinstance(f, GeoPointField):
pass
elif isinstance(f, ForeignKeyField):
r["%s__label" % f.name] = smart_text(v)
v = v.id
elif isinstance(f, PlainReferenceField):
r["%s__label" % f.name] = smart_text(v)
if hasattr(v, "id"):
v = str(v.id)
else:
v = str(v)
elif not isinstance(v, int) and not isinstance(v, str) and not isinstance(v, bool):
if hasattr(v, "id"):
v = v.id
else:
v = smart_text(v)
r[n] = v
# Add custom fields
for f in self.custom_fields:
r[f] = self.custom_fields[f](o)
return r
def list_data(self, request, formatter, parent=None):
"""
Returns a list of requested object objects
"""
# Todo: Fix
q = {str(k): v[0] if len(v) == 1 else v for k, v in request.GET.lists()}
limit = q.get(self.limit_param)
# page = q.get(self.page_param)
start = q.get(self.start_param)
format = q.get(self.format_param)
query = q.get(self.query_param)
only = q.get(self.only_param)
if only:
only = only.split(",")
ordering = []
if format == "ext" and self.sort_param in q:
for r in self.app.deserialize(q[self.sort_param]):
if r["direction"] == "DESC":
ordering += ["-%s" % r["property"]]
else:
ordering += [r["property"]]
q = self.cleaned_query(q)
if parent:
q[self.parent_rel] = ObjectId(parent)
if None in q:
ew = q.pop(None)
data = self.queryset(request, query).filter(**q).extra(where=ew)
else:
data = self.queryset(request, query).filter(**q)
if hasattr(data, "_as_sql"): # For Models only
data = data.select_related()
# Apply sorting
if ordering:
data = data.order_by(*ordering)
if format == "ext":
total = data.count()
if start is not None and limit is not None:
data = data[int(start) : int(start) + int(limit)]
out = [formatter(o, fields=only) for o in data]
if format == "ext":
out = {"total": total, "success": True, "data": out}
return self.app.response(out, status=self.OK)
def api_list(self, request, parent):
return self.list_data(request, self.instance_to_dict, parent=str(parent))
def api_create(self, request, parent):
parent = self.app.get_object_or_404(self.parent_model, id=ObjectId(parent))
try:
attrs = self.clean(self.app.deserialize(request.body), parent)
except ValueError as e:
return self.app.render_json(
{"status": False, "message": "Bad request", "traceback": str(e)},
status=self.app.BAD_REQUEST,
)
try:
# Exclude callable values from query
# (Django raises exception on pyRules)
# @todo: Check unique fields only?
qattrs = {k: attrs[k] for k in attrs if not callable(attrs[k])}
# Check for duplicates
self.queryset(request).get(**qattrs)
return self.app.render_json(
{"status": False, "message": "Duplicated record"}, status=self.CONFLICT
)
except self.model.MultipleObjectsReturned:
return self.app.render_json(
{"status": False, "message": "Duplicated record"}, status=self.CONFLICT
)
except self.model.DoesNotExist:
attrs[self.parent_rel] = parent
o = self.model(**attrs)
try:
o.save()
except NotUniqueError:
return self.app.render_json(
{"status": False, "message": "Integrity error"}, status=self.CONFLICT
)
format = request.GET.get(self.format_param)
if format == "ext":
r = {"success": True, "data": self.instance_to_dict(o)}
else:
r = self.instance_to_dict(o)
return self.app.response(r, status=self.CREATED)
def api_read(self, request, parent, id):
"""
Returns dict with object's fields and values
"""
try:
o = self.queryset(request).get(id=int(id), parent=ObjectId(parent))
except self.model.DoesNotExist:
return self.app.response("", status=self.NOT_FOUND)
only = request.GET.get(self.only_param)
if only:
only = only.split(",")
return self.app.response(self.instance_to_dict(o, fields=only), status=self.OK)
def api_update(self, request, parent, id):
parent = self.app.get_object_or_404(self.parent_model, id=ObjectId(parent))
try:
attrs = self.clean(self.app.deserialize(request.body), parent)
except ValueError as e:
return self.app.render_json(
{"status": False, "message": "Bad request", "traceback": str(e)},
status=self.BAD_REQUEST,
)
except InterfaceTypeError as e:
return self.app.render_json(
{"status": False, "message": "Bad request", "traceback": str(e)},
status=self.BAD_REQUEST,
)
try:
o = self.queryset(request).get(id=ObjectId(id))
except self.model.DoesNotExist:
return self.app.response("", status=self.NOT_FOUND)
attrs[self.parent_rel] = parent
for k, v in attrs.items():
setattr(o, k, v)
try:
o.save()
except NotUniqueError:
return self.app.render_json(
{"status": False, "message": "Integrity error"}, status=self.CONFLICT
)
return self.app.response(status=self.OK)
def api_delete(self, request, parent, id):
try:
q = {"id": ObjectId(id), self.parent_rel: ObjectId(parent)}
o = self.queryset(request).get(**q)
except self.model.DoesNotExist:
return self.app.render_json(
{"status": False, "message": "Not found"}, status=self.NOT_FOUND
)
o.delete() # @todo: Detect errors
return self.app.response("", status=self.DELETED)
|
67947e9837c168176436adcc4258adb9232f818b
|
fbbe424559f64e9a94116a07eaaa555a01b0a7bb
|
/Sklearn_scipy_numpy/source/sklearn/utils/metaestimators.py
|
a131315320608da4c5d46941eb652fa0b98f8b5c
|
[
"MIT"
] |
permissive
|
ryfeus/lambda-packs
|
6544adb4dec19b8e71d75c24d8ed789b785b0369
|
cabf6e4f1970dc14302f87414f170de19944bac2
|
refs/heads/master
| 2022-12-07T16:18:52.475504
| 2022-11-29T13:35:35
| 2022-11-29T13:35:35
| 71,386,735
| 1,283
| 263
|
MIT
| 2022-11-26T05:02:14
| 2016-10-19T18:22:39
|
Python
|
UTF-8
|
Python
| false
| false
| 2,353
|
py
|
metaestimators.py
|
"""Utilities for meta-estimators"""
# Author: Joel Nothman
# Andreas Mueller
# Licence: BSD
from operator import attrgetter
from functools import update_wrapper
__all__ = ['if_delegate_has_method']
class _IffHasAttrDescriptor(object):
"""Implements a conditional property using the descriptor protocol.
Using this class to create a decorator will raise an ``AttributeError``
if the ``attribute_name`` is not present on the base object.
This allows ducktyping of the decorated method based on ``attribute_name``.
See https://docs.python.org/3/howto/descriptor.html for an explanation of
descriptors.
"""
def __init__(self, fn, attribute_name):
self.fn = fn
self.get_attribute = attrgetter(attribute_name)
# update the docstring of the descriptor
update_wrapper(self, fn)
def __get__(self, obj, type=None):
# raise an AttributeError if the attribute is not present on the object
if obj is not None:
# delegate only on instances, not the classes.
# this is to allow access to the docstrings.
self.get_attribute(obj)
# lambda, but not partial, allows help() to work with update_wrapper
out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs)
# update the docstring of the returned function
update_wrapper(out, self.fn)
return out
def if_delegate_has_method(delegate):
"""Create a decorator for methods that are delegated to a sub-estimator
This enables ducktyping by hasattr returning True according to the
sub-estimator.
>>> from sklearn.utils.metaestimators import if_delegate_has_method
>>>
>>>
>>> class MetaEst(object):
... def __init__(self, sub_est):
... self.sub_est = sub_est
...
... @if_delegate_has_method(delegate='sub_est')
... def predict(self, X):
... return self.sub_est.predict(X)
...
>>> class HasPredict(object):
... def predict(self, X):
... return X.sum(axis=1)
...
>>> class HasNoPredict(object):
... pass
...
>>> hasattr(MetaEst(HasPredict()), 'predict')
True
>>> hasattr(MetaEst(HasNoPredict()), 'predict')
False
"""
return lambda fn: _IffHasAttrDescriptor(fn, '%s.%s' % (delegate, fn.__name__))
|
f9e47a65e3f564e67e5ec509fbca86e6d1a47dad
|
6b3cc22e7b8d356b01d638dffc820322312da3e4
|
/pkg_pytorch/blendtorch/btt/file.py
|
29cdbb31542794b02daa5dea077db94b08d21f53
|
[
"MIT"
] |
permissive
|
cheind/pytorch-blender
|
911961f760dde82a591f7cb26c0c648b120ad570
|
d2386df70e14c190669509e28009f46aed561c88
|
refs/heads/develop
| 2023-04-08T01:44:09.341680
| 2022-04-03T09:37:17
| 2022-04-03T09:37:17
| 169,447,021
| 509
| 43
|
MIT
| 2023-03-20T03:06:22
| 2019-02-06T17:32:38
|
Python
|
UTF-8
|
Python
| false
| false
| 4,628
|
py
|
file.py
|
import io
import pickle
import logging
import numpy as np
from pathlib import Path
_logger = logging.getLogger("blendtorch")
class FileRecorder:
"""Provides raw message recording functionality.
`FileRecorder` stores received pickled messages into a single file.
This file consists of a header and a sequence of messages received.
Upon closing, the header is updated to match the offsets of pickled
messages in the file. The offsets allow `FileReader` to quickly
read and unpickle a specific message stored in this file.
This class is meant to be used as context manager.
Params
------
outpath: str
File path to write to
max_messages: int
Only up to `max_messages` can be stored.
"""
def __init__(
self, outpath="blendtorch.mpkl", max_messages=100000, update_header=10000
):
outpath = Path(outpath)
outpath.parent.mkdir(parents=True, exist_ok=True)
self.outpath = outpath
self.capacity = max_messages
self.update_header = update_header
_logger.info(
f"Recording configured for path {outpath}, max_messages {max_messages}."
)
def save(self, data, is_pickled=False):
"""Save new data if there is still capacity left.
Params
------
data : object
Pickled bytes or unpickled message.
is_pickled: bool
Whether or not the input is already in pickled
represenation.
"""
if self.num_messages < self.capacity:
offset = self.file.tell()
self.offsets[self.num_messages] = offset
self.num_messages += 1
if not is_pickled:
self.pickler.dump(data)
else:
self.file.write(data)
if self.num_messages % self.update_header == 0:
self._update_offsets()
def __enter__(self):
self.file = io.open(self.outpath, "wb", buffering=0)
# We currently cannot use the highest protocol but use a version
# compatible with Python 3.7 (Blender version).
# TODO even if we set this to highest (-1) and only run the tests
# we get an error when loading data from stream. We should ensure
# that what we do here is actually OK, independent of the protocol.
self.pickler = pickle.Pickler(self.file, protocol=3)
self.offsets = np.full(self.capacity, -1, dtype=np.int64)
self.num_messages = 0
self.pickler.dump(self.offsets) # We fix this once we update headers.
return self
def __exit__(self, *args):
self._update_offsets()
self.file.close()
self.file = None
def _update_offsets(self):
off = self.file.tell()
self.file.seek(0)
pickle.Pickler(self.file, protocol=3).dump(self.offsets)
self.file.seek(off)
@staticmethod
def filename(prefix, worker_idx):
"""Return a unique filename for the given prefix and worker id."""
return f"{prefix}_{worker_idx:02d}.btr"
class FileReader:
"""Read items from file.
Assumes file was written by `FileRecorder`.
Params
------
path: str
File path to read.
"""
def __init__(self, path):
self.path = path
self.offsets = FileReader.read_offsets(path)
self._file = None
def __len__(self):
"""Returns number of items stored."""
return len(self.offsets)
def __getitem__(self, idx):
"""Read message associated with index `idx`."""
if self._file is None:
# Lazly creating file object here to ensure PyTorch
# multiprocessing compatibility (i.e num_workers > 0)
self._create()
self._file.seek(self.offsets[idx])
return self._unpickler.load()
def _create(self):
self._file = io.open(self.path, "rb", buffering=0)
self._unpickler = pickle.Unpickler(self._file)
def close(self):
"""Close the reader."""
if self._file is not None:
self._file.close()
self._file = None
@staticmethod
def read_offsets(fname):
"""Returns the offset header of file refered to by `fname`."""
assert Path(fname).exists(), f"Cannot open {fname} for reading."
with io.open(fname, "rb") as f:
unpickler = pickle.Unpickler(f)
offsets = unpickler.load()
num_messages = len(offsets)
m = np.where(offsets == -1)[0]
if len(m) > 0:
num_messages = m[0]
return offsets[:num_messages]
|
0545c7c38adab0c1a993b8717f9e833dbbaa6609
|
2a1b8a671aceda6bc446f8ce26400aa84fa444a6
|
/Packs/FeedCyrenThreatInDepth/Scripts/CyrenThreatInDepthRandomHunt/CyrenThreatInDepthRandomHunt.py
|
36606bbba8af85c1f58004c5617e4707b67503d7
|
[
"MIT"
] |
permissive
|
demisto/content
|
6d4722d46f0ff0beea2748e9f7de585bf91a78b4
|
890def5a0e0ae8d6eaa538148249ddbc851dbb6b
|
refs/heads/master
| 2023-09-04T00:02:25.618032
| 2023-09-03T21:56:22
| 2023-09-03T21:56:22
| 60,525,392
| 1,023
| 1,921
|
MIT
| 2023-09-14T20:55:24
| 2016-06-06T12:17:02
|
Python
|
UTF-8
|
Python
| false
| false
| 3,166
|
py
|
CyrenThreatInDepthRandomHunt.py
|
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
from enum import Enum
from random import randrange
import yaml
class FeedName(str, Enum):
IP_REPUTATION = "ip_reputation"
PHISHING_URLS = "phishing_urls"
MALWARE_URLS = "malware_urls"
MALWARE_FILES = "malware_files"
def simple_result(text):
return CommandResults(readable_output=text)
def create_random_hunt_incident(args):
indicator_type = args.get("indicator_type")
incident_type = args.get("incident_type", "Hunt")
assignee = args.get("assignee")
query_parts = [
"lastseenbysource:>=\"7 days ago\"",
"sourceBrands:CyrenThreatInDepth ",
"investigationIDs:\"\"",
"cyrensourcetags:primary",
"-cyrensourcetags:related",
"cyrenfeedaction:add",
"cyrenfeedrelationships.timestamp:>=\"2000-01-01T00:00:00 +0100\"",
]
if indicator_type == FeedName.IP_REPUTATION:
query_parts.append("type:IP")
query_parts.append("cyreniprisk:>80")
elif indicator_type == FeedName.MALWARE_URLS:
query_parts.append("tags:malware")
query_parts.append("type:URL")
elif indicator_type == FeedName.PHISHING_URLS:
query_parts.append("tags:phishing")
query_parts.append("type:URL")
elif indicator_type == FeedName.MALWARE_FILES:
query_parts.append("type:File")
query = " ".join(query_parts)
random_page = randrange(10) + 1
res = demisto.executeCommand("findIndicators", dict(query=query, size=1, page=random_page))
if isError(res[0]):
raise DemistoException(f"Could not find any indicators: {res}")
indicators = res[0]["Contents"]
if not any(indicators):
return simple_result(f"Could not find any indicators for \"{query}\"!")
incident = dict(name="Cyren Threat InDepth Threat Hunt",
type=incident_type,
details=yaml.dump(indicators[0]))
if assignee:
incident["owner"] = assignee
else:
res = demisto.executeCommand("getUsers", dict(current=True))
if not isError(res[0]):
current_user = res[0]["Contents"][0]
current_user_id = current_user.get("id")
incident["owner"] = current_user_id
res = demisto.executeCommand("createNewIncident", incident)
if isError(res[0]):
raise DemistoException(f"Could not create new incident: {res}")
created_incident = res[0]
id = created_incident.get("EntryContext", dict()).get("CreatedIncidentID")
data = f"Successfully created incident {incident['name']}.\n" \
f"Click here to investigate: [{id}](#/incident/{id})."
res = demisto.executeCommand("investigate", dict(id=id))
if isError(res[0]):
data = data + "\n(An investigation has not been started.)"
return simple_result(text=data)
def main(args):
try:
return_results(create_random_hunt_incident(args))
except Exception as e:
return_error(f"Failed to execute CyrenThreatInDepthRandomHunt. Error: {str(e)}")
if __name__ in ("__main__", "__builtin__", "builtins"):
main(demisto.args())
|
37a87e1a02790109b22c5da09f9e3c78efc8930f
|
b1a6c925f0d570463e46e7331ae95fdc0ef49211
|
/setup.py
|
ad6812afb77a13f52595078189242fb52c073791
|
[
"MIT"
] |
permissive
|
EthanRosenthal/spacecutter
|
e35c55bb416bdaaae1e89fdb2fb360e7469e28c7
|
063fe875f5122063e6f616512cffd9ffa4df1974
|
refs/heads/master
| 2022-05-01T04:30:43.120191
| 2022-03-23T02:13:52
| 2022-03-23T02:13:52
| 160,105,172
| 112
| 13
|
MIT
| 2022-03-23T02:13:53
| 2018-12-02T23:05:01
|
Python
|
UTF-8
|
Python
| false
| false
| 1,233
|
py
|
setup.py
|
import os
from setuptools import setup, find_packages
from spacecutter import __version__
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
long_description = f.read()
with open(os.path.join(here, 'requirements.txt')) as f:
requirements = f.read().splitlines()
with open(os.path.join(here, 'test-requirements.txt')) as f:
test_requirements = f.read().splitlines()
setup(
name='spacecutter',
version=__version__,
description='Ordinal regression models in PyTorch',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/EthanRosenthal/spacecutter',
author='Ethan Rosenthal',
author_email='ethanrosenthal@gmail.com',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Scientific/Engineering :: Information Analysis',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
],
keywords='machine learning statistics',
packages=find_packages(exclude=['tests']),
install_requires=requirements,
extras_require={
'test': test_requirements,
},
)
|
c91f25679d754f837ba2fd83f9c323c0b14d784b
|
c268dcf432f3b7171be6eb307aafbe1bd173285a
|
/reddit2telegram/channels/~inactive/frontlinegirls/app.py
|
99df2a97921f488d1da05dd0837f66af7c254c7e
|
[
"MIT"
] |
permissive
|
Fillll/reddit2telegram
|
a7162da2cc08c81bcc8078ea4160d4ee07461fee
|
5d8ee3097e716734d55a72f5a16ce3d7467e2ed7
|
refs/heads/master
| 2023-08-09T10:34:16.163262
| 2023-07-30T18:36:19
| 2023-07-30T18:36:19
| 67,726,018
| 258
| 205
|
MIT
| 2023-09-07T02:36:36
| 2016-09-08T17:39:46
|
Python
|
UTF-8
|
Python
| false
| false
| 163
|
py
|
app.py
|
#encoding:utf-8
subreddit = 'girlsfrontline+tacticaldolls'
t_channel = '@frontlinegirls'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
75cf313857aaa2e89105d465741a73364d5aa23f
|
c75920a2967bcc5855fcd30abd581a1a527c11e6
|
/bin/bamsurgeon/mutableseq.py
|
a4428340590ddbc184bb1637a758a68956bf3ddd
|
[
"MIT"
] |
permissive
|
adamewing/bamsurgeon
|
23f607c8316ae34c6774967ba5b84c0220e9cef1
|
1885dacdde61c0e18bb30fa6af1af6507e975e1c
|
refs/heads/master
| 2023-08-24T15:05:08.920899
| 2023-08-17T08:19:38
| 2023-08-17T08:19:38
| 4,290,471
| 216
| 86
|
MIT
| 2023-06-08T12:27:06
| 2012-05-10T22:18:31
|
Python
|
UTF-8
|
Python
| false
| false
| 2,756
|
py
|
mutableseq.py
|
#!i/usr/bin/env python
'''
Methods for making mutations in a sequence
'''
import operator
from bamsurgeon.common import rc
def dist(seq1, seq2):
''' Hamming distance '''
assert len(seq1) == len(seq2)
if seq1 == seq2:
return 0
return sum([c1 != c2 for c1, c2 in zip(seq1, seq2)])
class MutableSeq:
def __init__(self,seq):
self.seq = str.upper(seq.strip())
def __str__(self):
return self.seq
def find_site(self, site, left_trim=0, right_trim=0):
''' find closest occurance of site in self.seq '''
left, right = site.split('^')
site = left+right
assert len(site) <= len(self.seq)
d = [dist(self.seq[start:start+len(site)], site) for start in range(left_trim,len(self.seq)-len(site)-right_trim+1)]
min_i, min_d = min(enumerate(d), key=operator.itemgetter(1))
return min_i + len(left)
def length(self):
return len(self.seq)
def subseq(self, start, end):
start = int(start)
end = int(end)
assert start < end
return self.seq[start:end]
def deletion(self, start, end):
''' deletes between start and end, bases at positions corresponding to start and end are kept '''
start = int(start)
end = int(end)
assert start < end
self.seq = self.seq[:start] + self.seq[end:]
def insertion(self, loc, seq, tsdlen=0):
''' inserts seq after position loc, adds taret site duplication (tsd) if tsdlen > 0 '''
loc = int(loc)
tsd = self.seq[loc:loc+tsdlen]
self.seq = self.seq[:loc] + tsd + seq + self.seq[loc:]
def inversion(self, start, end):
''' inverts sequence between start and end, bases at start and end positions are not affected '''
start = int(start)
end = int(end)
assert start < end
invseq = rc(self.seq[start:end])
self.seq = self.seq[:start] + invseq + self.seq[end:]
def duplication(self,start,end,fold=1):
''' duplicates sequence between start and end, bases at start and end positions are not included '''
start = int(start)
end = int(end)
assert start < end
dupseq = self.seq[start:end]
for i in range(fold):
dupseq = dupseq + self.seq[start:end]
self.seq = self.seq[:start] + dupseq + self.seq[end:]
def fusion(self, loc1, other, loc2, flip1=False, flip2=False):
loc1 = int(loc1)
loc2 = int(loc2)
loc1_seq = self.seq[:loc1]
loc2_seq = other.seq[loc2:]
if flip1:
loc1_seq = rc(self.seq[loc1:])
if flip2:
loc2_seq = rc(other.seq[:loc2])
self.seq = loc1_seq + loc2_seq
|
3c795135d6c0abc06800e6098bfb43fa6bcd36ba
|
88c4d5b462998a9c0411a0243ab95ee05ffee60a
|
/tests/execution/test_defer.py
|
241a53b3745586b34468c5933a66ac4efaba7476
|
[
"MIT"
] |
permissive
|
graphql-python/graphql-core
|
606f3f3d479d576a4bdcd7d7995c0fddc486282f
|
0c93b8452eed38d4f800c7e71cf6f3f3758cd1c6
|
refs/heads/main
| 2023-09-04T09:22:45.162575
| 2023-06-09T22:13:10
| 2023-06-09T22:13:10
| 143,207,933
| 259
| 101
|
MIT
| 2023-06-09T22:13:11
| 2018-08-01T20:57:07
|
Python
|
UTF-8
|
Python
| false
| false
| 28,846
|
py
|
test_defer.py
|
from asyncio import sleep
from typing import Any, Dict, List, NamedTuple
from pytest import mark, raises
from graphql.error import GraphQLError
from graphql.execution import (
ExecutionContext,
ExecutionResult,
ExperimentalIncrementalExecutionResults,
IncrementalDeferResult,
InitialIncrementalExecutionResult,
SubsequentIncrementalExecutionResult,
execute,
experimental_execute_incrementally,
)
from graphql.execution.execute import DeferredFragmentRecord
from graphql.language import DocumentNode, parse
from graphql.pyutils import Path
from graphql.type import (
GraphQLField,
GraphQLID,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
)
friend_type = GraphQLObjectType(
"Friend", {"id": GraphQLField(GraphQLID), "name": GraphQLField(GraphQLString)}
)
class Friend(NamedTuple):
name: str
id: int
friends = [Friend("Han", 2), Friend("Leia", 3), Friend("C-3PO", 4)]
async def resolve_slow(_obj, _info) -> str:
"""Simulate a slow async resolver returning a value."""
await sleep(0)
return "slow"
async def resolve_bad(_obj, _info) -> str:
"""Simulate a bad async resolver raising an error."""
raise RuntimeError("bad")
def resolve_null_sync(_obj, _info) -> None:
"""Simulate a resolver returning a null value synchronously."""
return None
async def resolve_null_async(_obj, _info) -> None:
"""Simulate a resolver returning a null value asynchronously."""
return None
hero_type = GraphQLObjectType(
"Hero",
{
"id": GraphQLField(GraphQLID),
"name": GraphQLField(GraphQLString),
"slowField": GraphQLField(GraphQLString, resolve=resolve_slow),
"errorField": GraphQLField(GraphQLString, resolve=resolve_bad),
"nonNullErrorField": GraphQLField(
GraphQLNonNull(GraphQLString), resolve=resolve_null_sync
),
"asyncNonNullErrorField": GraphQLField(
GraphQLNonNull(GraphQLString), resolve=resolve_null_async
),
"friends": GraphQLField(
GraphQLList(friend_type), resolve=lambda _obj, _info: friends
),
},
)
hero = Friend("Luke", 1)
query = GraphQLObjectType(
"Query", {"hero": GraphQLField(hero_type, resolve=lambda _obj, _info: hero)}
)
schema = GraphQLSchema(query)
async def complete(document: DocumentNode, root_value: Any = None) -> Any:
result = experimental_execute_incrementally(schema, document, root_value)
if isinstance(result, ExperimentalIncrementalExecutionResults):
results: List[Any] = [result.initial_result.formatted]
async for patch in result.subsequent_results:
results.append(patch.formatted)
return results
assert isinstance(result, ExecutionResult)
return result.formatted
def modified_args(args: Dict[str, Any], **modifications: Any) -> Dict[str, Any]:
return {**args, **modifications}
def describe_execute_defer_directive():
def can_format_and_print_incremental_defer_result():
result = IncrementalDeferResult()
assert result.formatted == {"data": None}
assert str(result) == "IncrementalDeferResult(data=None, errors=None)"
result = IncrementalDeferResult(
data={"hello": "world"},
errors=[GraphQLError("msg")],
path=["foo", 1],
label="bar",
extensions={"baz": 2},
)
assert result.formatted == {
"data": {"hello": "world"},
"errors": [{"message": "msg"}],
"extensions": {"baz": 2},
"label": "bar",
"path": ["foo", 1],
}
assert (
str(result) == "IncrementalDeferResult(data={'hello': 'world'},"
" errors=[GraphQLError('msg')], path=['foo', 1], label='bar',"
" extensions={'baz': 2})"
)
# noinspection PyTypeChecker
def can_compare_incremental_defer_result():
args: Dict[str, Any] = {
"data": {"hello": "world"},
"errors": [GraphQLError("msg")],
"path": ["foo", 1],
"label": "bar",
"extensions": {"baz": 2},
}
result = IncrementalDeferResult(**args)
assert result == IncrementalDeferResult(**args)
assert result != IncrementalDeferResult(
**modified_args(args, data={"hello": "foo"})
)
assert result != IncrementalDeferResult(**modified_args(args, errors=[]))
assert result != IncrementalDeferResult(**modified_args(args, path=["foo", 2]))
assert result != IncrementalDeferResult(**modified_args(args, label="baz"))
assert result != IncrementalDeferResult(
**modified_args(args, extensions={"baz": 1})
)
assert result == tuple(args.values())
assert result == tuple(args.values())[:4]
assert result == tuple(args.values())[:3]
assert result == tuple(args.values())[:2]
assert result != tuple(args.values())[:1]
assert result != ({"hello": "world"}, [])
assert result == args
assert result == dict(list(args.items())[:2])
assert result == dict(list(args.items())[:3])
assert result != dict(list(args.items())[:2] + [("path", ["foo", 2])])
assert result != {**args, "label": "baz"}
def can_format_and_print_initial_incremental_execution_result():
result = InitialIncrementalExecutionResult()
assert result.formatted == {"data": None, "hasNext": False}
assert (
str(result) == "InitialIncrementalExecutionResult(data=None, errors=None)"
)
result = InitialIncrementalExecutionResult(has_next=True)
assert result.formatted == {"data": None, "hasNext": True}
assert (
str(result)
== "InitialIncrementalExecutionResult(data=None, errors=None, has_next)"
)
incremental = [IncrementalDeferResult(label="foo")]
result = InitialIncrementalExecutionResult(
data={"hello": "world"},
errors=[GraphQLError("msg")],
incremental=incremental,
has_next=True,
extensions={"baz": 2},
)
assert result.formatted == {
"data": {"hello": "world"},
"errors": [GraphQLError("msg")],
"incremental": [{"data": None, "label": "foo"}],
"hasNext": True,
"extensions": {"baz": 2},
}
assert (
str(result) == "InitialIncrementalExecutionResult("
"data={'hello': 'world'}, errors=[GraphQLError('msg')], incremental[1],"
" has_next, extensions={'baz': 2})"
)
def can_compare_initial_incremental_execution_result():
incremental = [IncrementalDeferResult(label="foo")]
args: Dict[str, Any] = {
"data": {"hello": "world"},
"errors": [GraphQLError("msg")],
"incremental": incremental,
"has_next": True,
"extensions": {"baz": 2},
}
result = InitialIncrementalExecutionResult(**args)
assert result == InitialIncrementalExecutionResult(**args)
assert result != InitialIncrementalExecutionResult(
**modified_args(args, data={"hello": "foo"})
)
assert result != InitialIncrementalExecutionResult(
**modified_args(args, errors=[])
)
assert result != InitialIncrementalExecutionResult(
**modified_args(args, incremental=[])
)
assert result != InitialIncrementalExecutionResult(
**modified_args(args, has_next=False)
)
assert result != InitialIncrementalExecutionResult(
**modified_args(args, extensions={"baz": 1})
)
assert result == tuple(args.values())
assert result == tuple(args.values())[:4]
assert result == tuple(args.values())[:3]
assert result == tuple(args.values())[:2]
assert result != tuple(args.values())[:1]
assert result != ({"hello": "foo"}, [])
assert result == {
"data": {"hello": "world"},
"errors": [GraphQLError("msg")],
"incremental": incremental,
"hasNext": True,
"extensions": {"baz": 2},
}
assert result == {
"data": {"hello": "world"},
"errors": [GraphQLError("msg")],
"incremental": incremental,
"hasNext": True,
}
assert result != {
"data": {"hello": "world"},
"errors": [GraphQLError("msg")],
"incremental": incremental,
"hasNext": False,
"extensions": {"baz": 2},
}
def can_format_and_print_subsequent_incremental_execution_result():
result = SubsequentIncrementalExecutionResult()
assert result.formatted == {"hasNext": False}
assert str(result) == "SubsequentIncrementalExecutionResult()"
result = SubsequentIncrementalExecutionResult(has_next=True)
assert result.formatted == {"hasNext": True}
assert str(result) == "SubsequentIncrementalExecutionResult(has_next)"
incremental = [IncrementalDeferResult(label="foo")]
result = SubsequentIncrementalExecutionResult(
incremental=incremental,
has_next=True,
extensions={"baz": 2},
)
assert result.formatted == {
"incremental": [{"data": None, "label": "foo"}],
"hasNext": True,
"extensions": {"baz": 2},
}
assert (
str(result) == "SubsequentIncrementalExecutionResult(incremental[1],"
" has_next, extensions={'baz': 2})"
)
def can_compare_subsequent_incremental_execution_result():
incremental = [IncrementalDeferResult(label="foo")]
args: Dict[str, Any] = {
"incremental": incremental,
"has_next": True,
"extensions": {"baz": 2},
}
result = SubsequentIncrementalExecutionResult(**args)
assert result == SubsequentIncrementalExecutionResult(**args)
assert result != SubsequentIncrementalExecutionResult(
**modified_args(args, incremental=[])
)
assert result != SubsequentIncrementalExecutionResult(
**modified_args(args, has_next=False)
)
assert result != SubsequentIncrementalExecutionResult(
**modified_args(args, extensions={"baz": 1})
)
assert result == tuple(args.values())
assert result == tuple(args.values())[:2]
assert result != tuple(args.values())[:1]
assert result != (incremental, False)
assert result == {
"incremental": incremental,
"hasNext": True,
"extensions": {"baz": 2},
}
assert result == {"incremental": incremental, "hasNext": True}
assert result != {
"incremental": incremental,
"hasNext": False,
"extensions": {"baz": 2},
}
def can_print_deferred_fragment_record():
context = ExecutionContext.build(schema, parse("{ hero { id } }"))
assert isinstance(context, ExecutionContext)
record = DeferredFragmentRecord(None, None, None, context)
assert str(record) == "DeferredFragmentRecord(path=[])"
record = DeferredFragmentRecord(
"foo", Path(None, "bar", "Bar"), record, context
)
assert (
str(record) == "DeferredFragmentRecord("
"path=['bar'], label='foo', parent_context)"
)
record.data = {"hello": "world"}
assert (
str(record) == "DeferredFragmentRecord("
"path=['bar'], label='foo', parent_context, data)"
)
@mark.asyncio
async def can_defer_fragments_containing_scalar_types():
document = parse(
"""
query HeroNameQuery {
hero {
id
...NameFragment @defer
}
}
fragment NameFragment on Hero {
id
name
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1"}}, "hasNext": True},
{
"incremental": [
{"data": {"id": "1", "name": "Luke"}, "path": ["hero"]}
],
"hasNext": False,
},
]
@mark.asyncio
async def can_disable_defer_using_if_argument():
document = parse(
"""
query HeroNameQuery {
hero {
id
...NameFragment @defer(if: false)
}
}
fragment NameFragment on Hero {
name
}
"""
)
result = await complete(document)
assert result == {
"data": {
"hero": {
"id": "1",
"name": "Luke",
},
},
}
@mark.asyncio
async def does_not_disable_defer_with_null_if_argument():
document = parse(
"""
query HeroNameQuery($shouldDefer: Boolean) {
hero {
id
...NameFragment @defer(if: $shouldDefer)
}
}
fragment NameFragment on Hero {
name
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1"}}, "hasNext": True},
{
"incremental": [{"data": {"name": "Luke"}, "path": ["hero"]}],
"hasNext": False,
},
]
@mark.asyncio
async def throws_an_error_for_defer_directive_with_non_string_label():
document = parse(
"""
query Deferred {
... @defer(label: 42) { hero { id } }
}
"""
)
result = await complete(document)
assert result == {
"data": None,
"errors": [
{
"locations": [{"column": 33, "line": 3}],
"message": "Argument 'label' has invalid value 42.",
}
],
}
@mark.asyncio
async def can_defer_fragments_on_the_top_level_query_field():
document = parse(
"""
query HeroNameQuery {
...QueryFragment @defer(label: "DeferQuery")
}
fragment QueryFragment on Query {
hero {
id
}
}
"""
)
result = await complete(document)
assert result == [
{"data": {}, "hasNext": True},
{
"incremental": [
{"data": {"hero": {"id": "1"}}, "path": [], "label": "DeferQuery"}
],
"hasNext": False,
},
]
@mark.asyncio
async def can_defer_fragments_with_errors_on_the_top_level_query_field():
document = parse(
"""
query HeroNameQuery {
...QueryFragment @defer(label: "DeferQuery")
}
fragment QueryFragment on Query {
hero {
errorField
}
}
"""
)
result = await complete(document)
assert result == [
{"data": {}, "hasNext": True},
{
"incremental": [
{
"data": {"hero": {"errorField": None}},
"errors": [
{
"message": "bad",
"locations": [{"column": 17, "line": 7}],
"path": ["hero", "errorField"],
}
],
"path": [],
"label": "DeferQuery",
}
],
"hasNext": False,
},
]
@mark.asyncio
async def can_defer_a_fragment_within_an_already_deferred_fragment():
document = parse(
"""
query HeroNameQuery {
hero {
id
...TopFragment @defer(label: "DeferTop")
}
}
fragment TopFragment on Hero {
name
...NestedFragment @defer(label: "DeferNested")
}
fragment NestedFragment on Hero {
friends {
name
}
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1"}}, "hasNext": True},
{
"incremental": [
{
"data": {
"friends": [
{"name": "Han"},
{"name": "Leia"},
{"name": "C-3PO"},
]
},
"path": ["hero"],
"label": "DeferNested",
},
{
"data": {"name": "Luke"},
"path": ["hero"],
"label": "DeferTop",
},
],
"hasNext": False,
},
]
@mark.asyncio
async def can_defer_a_fragment_that_is_also_not_deferred_with_deferred_first():
document = parse(
"""
query HeroNameQuery {
hero {
id
...TopFragment @defer(label: "DeferTop")
...TopFragment
}
}
fragment TopFragment on Hero {
name
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1", "name": "Luke"}}, "hasNext": True},
{
"incremental": [
{
"data": {"name": "Luke"},
"path": ["hero"],
"label": "DeferTop",
},
],
"hasNext": False,
},
]
@mark.asyncio
async def can_defer_a_fragment_that_is_also_not_deferred_with_non_deferred_first():
document = parse(
"""
query HeroNameQuery {
hero {
id
...TopFragment
...TopFragment @defer(label: "DeferTop")
}
}
fragment TopFragment on Hero {
name
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1", "name": "Luke"}}, "hasNext": True},
{
"incremental": [
{
"data": {"name": "Luke"},
"path": ["hero"],
"label": "DeferTop",
},
],
"hasNext": False,
},
]
@mark.asyncio
async def can_defer_an_inline_fragment():
document = parse(
"""
query HeroNameQuery {
hero {
id
... on Hero @defer(label: "InlineDeferred") {
name
}
}
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1"}}, "hasNext": True},
{
"incremental": [
{
"data": {"name": "Luke"},
"path": ["hero"],
"label": "InlineDeferred",
},
],
"hasNext": False,
},
]
@mark.asyncio
async def handles_errors_thrown_in_deferred_fragments():
document = parse(
"""
query HeroNameQuery {
hero {
id
...NameFragment @defer
}
}
fragment NameFragment on Hero {
errorField
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1"}}, "hasNext": True},
{
"incremental": [
{
"data": {"errorField": None},
"path": ["hero"],
"errors": [
{
"message": "bad",
"locations": [{"line": 9, "column": 15}],
"path": ["hero", "errorField"],
}
],
},
],
"hasNext": False,
},
]
@mark.asyncio
async def handles_non_nullable_errors_thrown_in_deferred_fragments():
document = parse(
"""
query HeroNameQuery {
hero {
id
...NameFragment @defer
}
}
fragment NameFragment on Hero {
nonNullErrorField
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1"}}, "hasNext": True},
{
"incremental": [
{
"data": None,
"path": ["hero"],
"errors": [
{
"message": "Cannot return null for non-nullable field"
" Hero.nonNullErrorField.",
"locations": [{"line": 9, "column": 15}],
"path": ["hero", "nonNullErrorField"],
}
],
},
],
"hasNext": False,
},
]
@mark.asyncio
async def handles_non_nullable_errors_thrown_outside_deferred_fragments():
document = parse(
"""
query HeroNameQuery {
hero {
nonNullErrorField
...NameFragment @defer
}
}
fragment NameFragment on Hero {
id
}
"""
)
result = await complete(document)
assert result == {
"data": {"hero": None},
"errors": [
{
"message": "Cannot return null for non-nullable field"
" Hero.nonNullErrorField.",
"locations": [{"line": 4, "column": 17}],
"path": ["hero", "nonNullErrorField"],
}
],
}
@mark.asyncio
async def handles_async_non_nullable_errors_thrown_in_deferred_fragments():
document = parse(
"""
query HeroNameQuery {
hero {
id
...NameFragment @defer
}
}
fragment NameFragment on Hero {
asyncNonNullErrorField
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1"}}, "hasNext": True},
{
"incremental": [
{
"data": None,
"path": ["hero"],
"errors": [
{
"message": "Cannot return null for non-nullable field"
" Hero.asyncNonNullErrorField.",
"locations": [{"line": 9, "column": 15}],
"path": ["hero", "asyncNonNullErrorField"],
}
],
},
],
"hasNext": False,
},
]
@mark.asyncio
async def returns_payloads_in_correct_order():
document = parse(
"""
query HeroNameQuery {
hero {
id
...NameFragment @defer
}
}
fragment NameFragment on Hero {
slowField
friends {
...NestedFragment @defer
}
}
fragment NestedFragment on Friend {
name
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1"}}, "hasNext": True},
{
"incremental": [
{
"data": {"slowField": "slow", "friends": [{}, {}, {}]},
"path": ["hero"],
}
],
"hasNext": True,
},
{
"incremental": [
{
"data": {"name": "Han"},
"path": ["hero", "friends", 0],
},
{
"data": {"name": "Leia"},
"path": ["hero", "friends", 1],
},
{
"data": {"name": "C-3PO"},
"path": ["hero", "friends", 2],
},
],
"hasNext": False,
},
]
@mark.asyncio
async def returns_payloads_from_synchronous_data_in_correct_order():
document = parse(
"""
query HeroNameQuery {
hero {
id
...NameFragment @defer
}
}
fragment NameFragment on Hero {
name
friends {
...NestedFragment @defer
}
}
fragment NestedFragment on Friend {
name
}
"""
)
result = await complete(document)
assert result == [
{"data": {"hero": {"id": "1"}}, "hasNext": True},
{
"incremental": [
{
"data": {"name": "Luke", "friends": [{}, {}, {}]},
"path": ["hero"],
},
],
"hasNext": True,
},
{
"incremental": [
{
"data": {"name": "Han"},
"path": ["hero", "friends", 0],
},
{
"data": {"name": "Leia"},
"path": ["hero", "friends", 1],
},
{
"data": {"name": "C-3PO"},
"path": ["hero", "friends", 2],
},
],
"hasNext": False,
},
]
@mark.asyncio
async def original_execute_function_throws_error_if_deferred_and_all_is_sync():
document = parse(
"""
query Deferred {
... @defer { hero { id } }
}
"""
)
with raises(GraphQLError) as exc_info:
await execute(schema, document, {}) # type: ignore
assert str(exc_info.value) == (
"Executing this GraphQL operation would unexpectedly produce"
" multiple payloads (due to @defer or @stream directive)"
)
@mark.asyncio
async def original_execute_function_throws_error_if_deferred_and_not_all_is_sync():
document = parse(
"""
query Deferred {
hero { slowField }
... @defer { hero { id } }
}
"""
)
result = await execute(schema, document, {}) # type: ignore
assert result == (
None,
[
{
"message": "Executing this GraphQL operation would unexpectedly"
" produce multiple payloads (due to @defer or @stream directive)"
}
],
)
|
c820c97d25274268611320ea7dca055f47b0c84b
|
091e97bcfe5acc0635bd601aa8497e377b74d41a
|
/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/repoquery.py
|
ba608c4ddda63d1123a3a8cd231085dc4b4a009c
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
openshift/openshift-tools
|
d59b63778f25cb8fb3c7a0253afe22a173e72f9d
|
e342f6659a4ef1a188ff403e2fc6b06ac6d119c7
|
refs/heads/prod
| 2023-08-30T01:52:04.108978
| 2022-03-23T21:07:28
| 2022-03-23T21:07:28
| 36,827,699
| 170
| 254
|
Apache-2.0
| 2022-06-16T12:11:51
| 2015-06-03T20:09:22
|
Python
|
UTF-8
|
Python
| false
| false
| 36
|
py
|
repoquery.py
|
../../lib_utils/library/repoquery.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.