-
Notifications
You must be signed in to change notification settings - Fork 447
Description
import os
import csv
import tempfile
from datetime import datetime
from tableauserverclient import Server, PersonalAccessTokenAuth
import json
import boto3
Function to read AWS credentials from a configuration file
def read_aws_credentials(config_file_path):
with open(config_file_path, 'r') as file:
config = json.load(file)
return config['aws_access_key_id'], config['aws_secret_access_key'], config['region']
Path to the configuration file
config_file_path = 'C:/Users/Downloads/prd.json'
Read AWS credentials from the configuration file
aws_access_key_id, aws_secret_access_key, region = read_aws_credentials(config_file_path)
Initialize Tableau Server client
server_url = 'https://tableau.com/'
token_name = 'TABPRD'
token_value = 'XXXXXXX'
auth = PersonalAccessTokenAuth(token_name, token_value)
server = Server(server_url, auth)
Initialize S3 client
s3_client = boto3.client('s3', region_name=region, aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key)
with server.auth.sign_in(auth):
site_id = 'prod'
project_name = 'Management'
project_id = None
# Get all projects
all_projects, _ = server.projects.get()
# Iterate through the list of projects to find the one with the matching name
for project in all_projects:
if project.name == project_name:
project_id = project.id
break
if project_id is None:
print(f"Project '{project_name}' not found.")
else:
print(f"Found project '{project_name}' with ID {project_id}")
# Verify the workbook ID
workbook_id = '9946-d6ca6dbd0a11' # Workbook ID
try:
workbook = server.workbooks.get_by_id(workbook_id)
if workbook is None:
print(f"Workbook with ID {workbook_id} not found.")
else:
print(f"Found workbook '{workbook.name}'")
# Try to get the view by name
view_name = 'Balance - Desktop'
view = next((v for v in workbook.views if v.name == view_name), None)
if view is None:
print(f"View '{view_name}' not found in workbook '{workbook.name}'.")
else:
print(f"Found view '{view_name}'")
# Download the CSV
server.views.populate_csv(view)
current_date = datetime.now().strftime('%Y-%m-%d')
# Use os.path.join to handle file paths properly
download_dir = 'C:/Users/Downloads'
csv_file_path = os.path.join(download_dir, f"BAL_{current_date}.csv")
with open(csv_file_path, 'wb') as f:
f.write(b''.join(view.csv))
print(f"CSV file saved to: {csv_file_path}")
# Upload CSV file to S3
bucket_name = 'prod'
subfolder = 'TABLEAU/'
s3_object_key = f"{subfolder}BAL_{current_date}.csv"
try:
s3_client.upload_file(csv_file_path, bucket_name, s3_object_key)
print(f"CSV file uploaded to S3 bucket: {bucket_name}, key: {s3_object_key}")
except Exception as e:
print(f"Error uploading file to S3: {e}")
except Exception as e:
print(f"Error retrieving workbook with ID {workbook_id}: {e}")