def delete_workbook(server, auth_token, site_id, workbook_id):
"""
Deletes the workbook from the source project.
'server' specified server address
'auth_token' authentication token that grants user access to API calls
'site_id' ID of the site that the user is signed into
'workbook_id' ID of workbook to delete
"""
# Builds the request to delete workbook from the source project on server
url = server + "/api/{0}/sites/{1}/workbooks/{2}".format(VERSION, site_id, workbook_id)
server_response = requests.delete(url, headers={'x-tableau-auth': auth_token})
_check_status(server_response, 204)
python类VERSION的实例源码
def sign_in(server, username, password, site=""):
"""
Signs in to the server specified with the given credentials
'server' specified server address
'username' is the name (not ID) of the user to sign in as.
Note that most of the functions in this example require that the user
have server administrator permissions.
'password' is the password for the user.
'site' is the ID (as a string) of the site on the server to sign in to. The
default is "", which signs in to the default site.
Returns the authentication token and the site ID.
"""
url = server + "/api/{0}/auth/signin".format(VERSION)
# Builds the request
xml_request = ET.Element('tsRequest')
credentials_element = ET.SubElement(xml_request, 'credentials', name=username, password=password)
ET.SubElement(credentials_element, 'site', contentUrl=site)
xml_request = ET.tostring(xml_request)
# Make the request to server
server_response = requests.post(url, data=xml_request)
_check_status(server_response, 200)
# ASCII encode server response to enable displaying to console
server_response = _encode_for_display(server_response.text)
# Reads and parses the response
parsed_response = ET.fromstring(server_response)
# Gets the auth token and site ID
token = parsed_response.find('t:credentials', namespaces=xmlns).get('token')
site_id = parsed_response.find('.//t:site', namespaces=xmlns).get('id')
user_id = parsed_response.find('.//t:user', namespaces=xmlns).get('id')
return token, site_id, user_id
def sign_out(server, auth_token):
"""
Destroys the active session and invalidates authentication token.
'server' specified server address
'auth_token' authentication token that grants user access to API calls
"""
url = server + "/api/{0}/auth/signout".format(VERSION)
server_response = requests.post(url, headers={'x-tableau-auth': auth_token})
_check_status(server_response, 204)
return
def add_new_permission(server, auth_token, site_id, workbook_id, user_id, permission_name, permission_mode):
"""
Adds the specified permission to the workbook for the desired user.
'server' specified server address
'auth_token' authentication token that grants user access to API calls
'site_id' ID of the site that the user is signed into
'workbook_id' ID of workbook to audit permission in
'user_id' ID of the user to audit
'permission_name' name of permission to add or update
'permission_mode' mode to set the permission
"""
url = server + "/api/{0}/sites/{1}/workbooks/{2}/permissions".format(VERSION, site_id, workbook_id)
# Build the request
xml_request = ET.Element('tsRequest')
permissions_element = ET.SubElement(xml_request, 'permissions')
ET.SubElement(permissions_element, 'workbook', id=workbook_id)
grantee_element = ET.SubElement(permissions_element, 'granteeCapabilities')
ET.SubElement(grantee_element, 'user', id=user_id)
capabilities_element = ET.SubElement(grantee_element, 'capabilities')
ET.SubElement(capabilities_element, 'capability', name=permission_name, mode=permission_mode)
xml_request = ET.tostring(xml_request)
server_request = requests.put(url, data=xml_request, headers={'x-tableau-auth': auth_token})
_check_status(server_request, 200)
print("\tSuccessfully added/updated permission")
return
def sign_in(server, username, password, site=""):
"""
Signs in to the server specified with the given credentials
'server' specified server address
'username' is the name (not ID) of the user to sign in as.
Note that most of the functions in this example require that the user
have server administrator permissions.
'password' is the password for the user.
'site' is the ID (as a string) of the site on the server to sign in to. The
default is "", which signs in to the default site.
Returns the authentication token and the site ID.
"""
url = server + "/api/{0}/auth/signin".format(VERSION)
# Builds the request
xml_request = ET.Element('tsRequest')
credentials_element = ET.SubElement(xml_request, 'credentials', name=username, password=password)
ET.SubElement(credentials_element, 'site', contentUrl=site)
xml_request = ET.tostring(xml_request)
# Make the request to server
server_response = requests.post(url, data=xml_request)
_check_status(server_response, 200)
# ASCII encode server response to enable displaying to console
server_response = _encode_for_display(server_response.text)
# Reads and parses the response
parsed_response = ET.fromstring(server_response)
# Gets the auth token and site ID
token = parsed_response.find('t:credentials', namespaces=xmlns).get('token')
site_id = parsed_response.find('.//t:site', namespaces=xmlns).get('id')
user_id = parsed_response.find('.//t:user', namespaces=xmlns).get('id')
return token, site_id, user_id
def sign_out(server, auth_token):
"""
Destroys the active session and invalidates authentication token.
'server' specified server address
'auth_token' authentication token that grants user access to API calls
"""
url = server + "/api/{0}/auth/signout".format(VERSION)
server_response = requests.post(url, headers={'x-tableau-auth': auth_token})
_check_status(server_response, 204)
return
def add_permission(server, auth_token, site_id, workbook_id, user_id, permission_name, permission_mode):
"""
Adds the specified permission to the workbook for the desired user.
'server' specified server address
'auth_token' authentication token that grants user access to API calls
'site_id' ID of the site that the user is signed into
'workbook_id' ID of workbook to update permission in
'user_id' ID of the user to update
'permission_name' name of permission to add or update
'permission_mode' mode to set the permission
"""
url = server + "/api/{0}/sites/{1}/workbooks/{2}/permissions".format(VERSION, site_id, workbook_id)
# Build the request
xml_request = ET.Element('tsRequest')
permissions_element = ET.SubElement(xml_request, 'permissions')
ET.SubElement(permissions_element, 'workbook', id=workbook_id)
grantee_element = ET.SubElement(permissions_element, 'granteeCapabilities')
ET.SubElement(grantee_element, 'user', id=user_id)
capabilities_element = ET.SubElement(grantee_element, 'capabilities')
ET.SubElement(capabilities_element, 'capability', name=permission_name, mode=permission_mode)
xml_request = ET.tostring(xml_request)
server_request = requests.put(url, data=xml_request, headers={'x-tableau-auth': auth_token})
_check_status(server_request, 200)
return
def sign_in(server, username, password, site):
"""
Signs in to the server specified with the given credentials
'server' specified server address
'username' is the name (not ID) of the user to sign in as.
Note that most of the functions in this example require that the user
have server administrator permissions.
'password' is the password for the user.
'site' is the ID (as a string) of the site on the server to sign in to. The
default is "", which signs in to the default site.
Returns the authentication token and the site ID.
"""
url = server + "/api/{0}/auth/signin".format(VERSION)
# Builds the request
xml_request = ET.Element('tsRequest')
credentials_element = ET.SubElement(xml_request, 'credentials', name=username, password=password)
ET.SubElement(credentials_element, 'site', contentUrl=site)
xml_request = ET.tostring(xml_request)
# Make the request to server
server_response = requests.post(url, data=xml_request)
_check_status(server_response, 200)
# ASCII encode server response to enable displaying to console
server_response = _encode_for_display(server_response.text)
# Reads and parses the response
parsed_response = ET.fromstring(server_response)
# Gets the auth token and site ID
token = parsed_response.find('t:credentials', namespaces=XMLNS).get('token')
site_id = parsed_response.find('.//t:site', namespaces=XMLNS).get('id')
# user_id = parsed_response.find('.//t:user', namespaces=XMLNS).get('id')
return token, site_id
def sign_out(server, auth_token):
"""
Destroys the active session and invalidates authentication token.
'server' specified server address
'auth_token' authentication token that grants user access to API calls
"""
url = server + "/api/{0}/auth/signout".format(VERSION)
server_response = requests.post(url, headers={'x-tableau-auth': auth_token})
_check_status(server_response, 204)
return
def get_users_in_group_count(server, auth_token, site_id, group_id):
"""
Find out how many users are available in the group
GET /api/api-version/sites/site-id/groups/group-id/users
"""
url = server + "/api/{0}/sites/{1}/groups/{2}/users".format(VERSION, site_id, group_id)
server_response = requests.get(url, headers={'x-tableau-auth': auth_token})
#_check_status(server_response, 200)
xml_response = ET.fromstring(_encode_for_display(server_response.text))
total_available = xml_response.find('.//t:pagination', namespaces=XMLNS).attrib['totalAvailable']
# Note! Need to convert "total_available" to integer
total_available = int(total_available)
return total_available
def sign_in(server, username, password, site=""):
"""
Signs in to the server specified with the given credentials
'server' specified server address
'username' is the name (not ID) of the user to sign in as.
Note that most of the functions in this example require that the user
have server administrator permissions.
'password' is the password for the user.
'site' is the ID (as a string) of the site on the server to sign in to. The
default is "", which signs in to the default site.
Returns the authentication token and the site ID.
"""
url = server + "/api/{0}/auth/signin".format(VERSION)
# Builds the request
xml_request = ET.Element('tsRequest')
credentials_element = ET.SubElement(xml_request, 'credentials', name=username, password=password)
ET.SubElement(credentials_element, 'site', contentUrl=site)
xml_request = ET.tostring(xml_request)
# Make the request to server
server_response = requests.post(url, data=xml_request)
_check_status(server_response, 200)
# ASCII encode server response to enable displaying to console
server_response = _encode_for_display(server_response.text)
# Reads and parses the response
parsed_response = ET.fromstring(server_response)
# Gets the auth token and site ID
token = parsed_response.find('t:credentials', namespaces=xmlns).get('token')
site_id = parsed_response.find('.//t:site', namespaces=xmlns).get('id')
return token, site_id
def sign_out(server, auth_token):
"""
Destroys the active session and invalidates authentication token.
'server' specified server address
'auth_token' authentication token that grants user access to API calls
"""
url = server + "/api/{0}/auth/signout".format(VERSION)
server_response = requests.post(url, headers={'x-tableau-auth': auth_token})
_check_status(server_response, 204)
return
def get_default_project_id(server, auth_token, site_id):
"""
Returns the project ID for the 'default' project on the Tableau server.
'server' specified server address
'auth_token' authentication token that grants user access to API calls
'site_id' ID of the site that the user is signed into
"""
page_num, page_size = 1, 100 # Default paginating values
# Builds the request
url = server + "/api/{0}/sites/{1}/projects".format(VERSION, site_id)
paged_url = url + "?pageSize={0}&pageNumber={1}".format(page_size, page_num)
server_response = requests.get(paged_url, headers={'x-tableau-auth': auth_token})
_check_status(server_response, 200)
xml_response = ET.fromstring(_encode_for_display(server_response.text))
# Used to determine if more requests are required to find all projects on server
total_projects = int(xml_response.find('t:pagination', namespaces=xmlns).get('totalAvailable'))
max_page = int(math.ceil(total_projects / page_size))
projects = xml_response.findall('.//t:project', namespaces=xmlns)
# Continue querying if more projects exist on the server
for page in range(2, max_page + 1):
paged_url = url + "?pageSize={0}&pageNumber={1}".format(page_size, page)
server_response = requests.get(paged_url, headers={'x-tableau-auth': auth_token})
_check_status(server_response, 200)
xml_response = ET.fromstring(_encode_for_display(server_response.text))
projects.extend(xml_response.findall('.//t:project', namespaces=xmlns))
# Look through all projects to find the 'default' one
for project in projects:
if project.get('name') == 'default' or project.get('name') == 'Default':
return project.get('id')
raise LookupError("Project named 'default' was not found on server")
def initUI(self):
"""
Description: Simply shows the dialog
Arguments: None
Returns: Nothing
"""
global conf
self.resize(450, 150)
# About image
filename = 'imgs/about.png'
image = QImage(filename)
imageLabel = QLabel()
imageLabel.setPixmap(QPixmap.fromImage(image))
imageLabel.setAlignment(Qt.AlignCenter)
# Labels for info
lab_appname = QLabel("<font color='#0000FF'>" + _('apptitle') + ' ' + VERSION + "</font>")
lab_appname.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
lab_desc = QLabel(_('appdesc'))
lab_desc.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
lab_desc.setWordWrap(True)
lab_author = QLabel(_('written_by') + ' nKn (<a href=\'http://github.com/nkovacne\'>http://github.com/nkovacne</a>)')
lab_author.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
lab_unoff = QLabel('<b>' + _('unofficial_project') + '</b>')
lab_unoff.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
lab_unoff.setWordWrap(True)
# OK button
okButton = QPushButton(_("ok"))
okButton.setMaximumWidth(100)
okButton.setDefault(True)
okButton.clicked.connect(self.done)
# Grid layout with all the elements
grid = QGridLayout()
grid.addWidget(imageLabel, 1, 0, 4, 1) # About image
grid.addWidget(lab_appname, 1, 1, 1, 2) # Several QLabels
grid.addWidget(lab_desc, 2, 1, 1, 2)
grid.addWidget(lab_author, 3, 1, 1, 2)
grid.addWidget(lab_unoff, 4, 1, 1, 2)
grid.addWidget(okButton, 6, 1) # Button
self.setLayout(grid)
self.setModal(True)
self.center()
self.setWindowTitle(_('about'))
self.show()
def __init__(self, server):
print 'Logs will be written to %s' % self.LOG_FOLDER
self.USERNAME = DEFAULT_USERNAME
self.PASSWORD = DEFAULT_PASSWORD
if not os.path.exists(self.LOG_FOLDER):
os.makedirs(self.LOG_FOLDER)
self.log_folder = self.LOG_FOLDER
self.server = server
self.hostname = socket.gethostname()
self.ip = socket.gethostbyname(socket.gethostname())
self.container = JobContainer(self.log_folder, server)
self.status_changed = True
self.info = cpuinfo.get_cpu_info()
self.s = requests.Session()
self.first_update = True
self.need_restart = False
self.cpu_percent = 0.0
# Log File Logger
self.logger = logging.getLogger('JobClientLogger')
self.logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(os.path.join(self.log_folder, 'JobClient.log'))
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
self.logger.addHandler(handler)
# Console handler
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
self.logger.addHandler(ch)
self.logger.info('Launching JobClient (Code Version %d)' % VERSION)
try:
import vhtrack
self.cuda_device_count = vhtrack.query_cuda_device_count()
except:
self.cuda_device_count = 0
self.logger.info('%d CUDA GPU Detected' % self.cuda_device_count)
self.available_job_classes = create_available_job_list(self.logger)
def phone_home(self):
payload = {
'machine_name': self.hostname,
'ip_address': self.ip,
'status': 'accepting',
'restarted': self.first_update,
'code_version': VERSION,
'running_jobs': self.container.running_jobs.keys(),
'running_jobs_progress': [(key,self.container.running_jobs[key][1].status) for key in self.container.running_jobs],
'finished_jobs': [j.result for j in self.container.finished_jobs.values()],
'system' : platform.system(),
'system_bits' : self.info['bits'],
'cpu_brand' : self.info['brand'],
'cpu_cores' : self.info['count'],
'cuda_device_count' : self.cuda_device_count,
'available_jobs' : self.available_job_classes,
'cpu_percent' : self.cpu_percent
}
for j in payload['finished_jobs']:
self.logger.info('Job Finished: %s' % (j))
r = self.s.post('%s/jobs/client_discover/' % self.server, json=payload, auth=(self.USERNAME, self.PASSWORD), verify=False)
if (r.status_code==200):
self.first_update = False
# Purge local list of finished jobs
for x in payload['finished_jobs']:
del self.container.finished_jobs[x['job_id']]
# Launch new jobs we just recieved
try:
data = r.json()
if 'req_restart' in data and data['req_restart']:
if not self.need_restart:
self.logger.info('Received Restart Request')
self.need_restart = True
if 'jobs' in data:
for new_job in data['jobs']:
self.logger.info('Job recieved: #%d %s' % (new_job['job_id'], new_job['job_class']))
self.container.submit_job(**new_job)
self.status_changed = True
if 'jobs_to_kill' in data:
for job_id in data['jobs_to_kill']:
self.container.terminate_job(job_id)
except Exception as e:
self.logger.error('Recieved invalid data from server. %s' % e)
else:
self.logger.error("Unexpected return code while contacting server %s (%d)" % (self.server, r.status_code))
self.logger.error(r.text)