def get_sdk_for_schedule(scheduled_plan_id: int) -> sdk.methods.LookerSDK: sdk = client.setup() plan = sdk.scheduled_plan(scheduled_plan_id) sdk.login_user(plan.user_id) return sdk
def home(): if request.method == 'POST': base_url = os.environ['LOOKERSDK_BASE_URL'] = request.form['host'] os.environ['LOOKERSDK_CLIENT_ID'] = request.form['clientid'] os.environ['LOOKERSDK_CLIENT_SECRET'] = request.form['clientsecret'] sdk = client.setup() #just check the SDK is initiated me = sdk.me() print(me) # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit an empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('process', filename=filename)) return render_template('upload.html')
def __init__(self, config, plugin_config): logging.basicConfig(level=logging.INFO, format='dss-plugin-looker-query %(levelname)s - %(message)s') self.logger = logging.getLogger() Connector.__init__(self, config, plugin_config) # pass the parameters to the base class self.base_url = self.plugin_config["Looker API"]["baseurl"] self.client_id = self.plugin_config["Looker API"]["clientid"] self.client_secret = self.plugin_config["Looker API"]["clientsecret"] self.look_id = int(self.config["lookid"]) #self.limit = int(self.config["limit"]) print(self.plugin_config) if not (self.base_url and self.client_id and self.client_secret): self.logger.error('Connection params: {}'.format( {'Client ID:' : self.client_id, 'Client secret:' : '#' * len(self.client_secret), 'Base URL:' : self.base_url}) ) raise ValueError("Client ID, Client secret and Base URL must be filled") if not self.look_id: raise ValueError("Look ID was not set") #if self.limit is None or self.limit = 0: # self.limit = 500 file = open("looker.ini", "w") line_list = ["[Looker]", "api_version=3.1", "base_url=" + self.base_url, "client_id=" + self.client_id, "client_secret=" + self.client_secret, "verify_ssl=True"] file.write('\n'.join(line_list) + '\n') file.close() self.looker_client = client.setup("looker.ini") print(self.looker_client)
def register_user(*, hackathon: str, first_name: str, last_name: str, email: str) -> str: sdk = client.setup() user = find_or_create_user(sdk=sdk, first_name=first_name, last_name=last_name, email=email) assert user.id if not user.credentials_email: create_email_credentials(sdk=sdk, user_id=user.id, email=email) if user.credentials_api3: client_id = user.credentials_api3[0].client_id else: client_id = create_api3_credentials(sdk=sdk, user_id=user.id).client_id set_user_group(sdk=sdk, user_id=user.id, hackathon=hackathon) set_user_attributes(sdk=sdk, user_id=user.id, hackathon=hackathon) disable_user(sdk=sdk, user_id=user.id) assert client_id return client_id
def enable_users_by_hackathons(hackathons: Sequence[str]) -> Dict[str, str]: global LOOKER_GROUP_PREFIX sdk = client.setup() groups = {g.name: g.id for g in sdk.all_groups(fields="id,name")} ret = {} for hackathon in hackathons: try: group_id = groups[f"{LOOKER_GROUP_PREFIX}{hackathon}"] except KeyError: raise RegisterError(f"No group found for hackathon: '{hackathon}'") for user in sdk.search_users(group_id=group_id): assert user.id assert user.email sdk.update_user(user_id=user.id, body=models.WriteUser(is_disabled=False)) password_reset_url = sdk.create_user_credentials_email_password_reset( user_id=user.id, expires=False).password_reset_url assert password_reset_url setup = re.sub("password/reset", "account/setup", password_reset_url) ret[user.email] = setup return ret
from looker_sdk import client, models from looker_sdk.rtl import transport import configparser import json import sys import csv from pprint import pprint config_file = "looker.ini" sdk = client.setup(config_file) def get_base_url(): """ Pull base url from looker.ini, remove port """ config = configparser.ConfigParser() config.read(config_file) full_base_url = config.get("Looker", "base_url") base_url = sdk.auth.settings.base_url[:full_base_url.index(":19999")] return base_url def join_content(match_list, left_key, iterator, right_key): """ Given a list of sdk objects and a list of dictionaries, join on a common value """ joined_data = next( i for i in match_list if str(getattr(i, left_key)) == str(iterator[right_key])) return joined_data def get_unused_content(days):
# Get new query's info new_query = sdk_new_instance.create_query(body=create_query) # Build Look's body look_body = models.WriteLookWithQuery(title=old_look.title, is_run_on_load=True, query_id=new_query.id, space_id=new_folder_id, user_id=user_id, query=create_query) # Create Look _ = sdk_new_instance.create_look(body=look_body) print(f"Congratulation for moving Look: {look_id} to the new instance") # Configure SDK Client for the old_instance sdk_old_instance = client.setup("dcl.ini") # Configure SDK Client for the new_instance sdk_new_instance = client.setup("local.ini") config = configparser.ConfigParser() config.read('dcl.ini') for look in look_ids: main(sdk_old_instance=sdk_old_instance, sdk_new_instance=sdk_new_instance, look_id=look)
def me(): sdk = client.setup() return sdk.me()
def looker_sdk() -> methods.LookerSDK: looker_sdk = client.setup("looker.ini") return looker_sdk
import sys import textwrap import time import exceptions from looker_sdk import client, models sdk = client.setup("../looker.ini") def main(): """Given a look title, find the corresponding look id and use it to render its image. $ python download_look.py "A good look" 1024 768 png """ look_title = sys.argv[1] if len(sys.argv) > 1 else "" image_width = int(sys.argv[2]) if len(sys.argv) > 2 else 545 image_height = int(sys.argv[3]) if len(sys.argv) > 3 else 842 image_format = sys.argv[4] if len(sys.argv) > 4 else "png" if not look_title: raise exceptions.ArgumentError( textwrap.dedent(""" Please provide: <lookTitle> [<img_width>] [<img_height>] [<img_format>] img_width defaults to 545 img_height defaults to 842 img_format defaults to 'png'""")) look = get_look(look_title) download_look(look, image_format, image_width, image_height)
def __init__(self, looker_credentials_file): self.__sdk = client.setup(looker_credentials_file)
def get_sdk_all_access() -> sdk.methods.LookerSDK: sdk = client.setup() return sdk
def looker_client(): return client.setup("../looker.ini")
import json from looker_sdk import client, models, error # client calls will now automatically authenticate using the # api3credentials specified in 'looker.ini' sdk = client.setup("looker.ini") looker_api_user = sdk.me() def update_and_run_query(query_id, changes): # Get old query old_query = sdk.query(query_id) # Make new query new_query = update_query_filters(old_query, changes) # create a new query in looker with the new filter new_api_query = sdk.create_query(new_query) # get the new query ID new_query_id = new_api_query.id # Returns JSON data return sdk.run_query(new_query_id, "json") def update_query_filters(api_query, changes): # Get the JSON version of the query query = api_query.__dict__ # In order to create a new query, read_only fields need to be removed # Filter config also needs to be removed otherwise it will override the filter options in the ui read_only_fields = [ "id",
from looker_sdk import client, models import sys sdk = client.setup() def main(): broken_content_prod = sdk.content_validation().content_with_errors name = parse_dev_branch_name(sys.argv[1]) user_id = get_user_id(name[0], name[1]) print(user_id) sdk.login_user(user_id) checkout_dev_branch() broken_content_dev = sdk.content_validation().content_with_errors # Assert no new errors introduced in dev branch assert len(broken_content_dev) - len(broken_content_prod) <= 0, """ Uh oh. you just introduced a new content error!""" def parse_dev_branch_name(dev_branch): name = dev_branch.split('-') if dev_branch.startswith('dev'): first_name = name[1] last_name = name[2] else: print(len(name)) if len(name) < 3: raise Exception(""" Branch name is not formatted correctly. Branch should begin with dev-firstName-lastName or firstName-lastName """)
from looker_sdk import client, models import re import requests sdk = client.setup('looker.ini') #just delete all the groups that aren't the All Users and User groups existing_groups = {group.id for group in sdk.all_groups() if group.id > 2} print(existing_groups) for id in existing_groups: sdk.delete_group(id) existing_users = {user.id for user in sdk.all_users() if user.id > 2} for id in existing_users: sdk.delete_user(id) existing_user_attributes = { ua.id for ua in sdk.all_user_attributes() if ua.id > 13 } for id in existing_user_attributes: sdk.delete_user_attribute(id)
def get_client(ini, env): sdk = client.setup(config_file=ini, section=env) return sdk
def sdk(): sdk = client.setup("../looker.ini") yield sdk sdk.logout()
def sdk(): sdk = client.setup() yield sdk sdk.logout()