"""Query flow. Provides functions to sync over queries from main looker instance to client looker instance. This is essential for both looks and dashboards sync, since those rely on queries. The first step is to get look/dashboard json and pass it as an argument to get_original_entity_query_id. """ import requests from looker_updater import config def get_original_looker_entity_query_id(entity_json): """Gets query_id of a look or a dashboard. Needed for further sync over the query, which will then be a base for the look or the dashboard sync. Args: entity_json (dict): json representation of the look or the dashboard. Returns: int: id of a query on main looker instance. """ return entity_json.get('query_id') def get_main_instance_query_json(query_id): """Gets query content from the main looker instance. Args: query_id (int): id of a query from main looker instance. Comes as a return value of get_original_look_query_id function. Returns: dict: json representation of a query. """ response = requests.get( f'{config.LOOKER_MAIN_INSTANCE_URL}/queries/{query_id}', headers=config.LOOKER_MAIN_VALIDATION ) if response.status_code == 200: return response.json() return False def post_query_to_client_instance(query_json): """Creates a query on client looker instance. Args: query_json (dict): json representation of a query. Comes as a return value of get_main_instance_query_json function. Returns: int: id of a newly created query on client instance (needs to be passed as client_instance_query_id parameter to adjust_look_data function from look_tools.py module. bool: False if something went wrong and http response is anything but 200. """ response = requests.post( f'{config.LOOKER_CLIENT_INSTANCE_URL}/queries', headers=config.LOOKER_CLIENT_VALIDATION, json=query_json ) if response.status_code == 200: return response.json()['id'] return False def sync_query(entity_json): """Sync query. Calls all the necessary functions in the right order, eventually creating a query on client instance. Args: entity_json (dict): json representation of a look or a dashboard. Returns: calls post_query_to_client_instance function. """ query_id = get_original_looker_entity_query_id(entity_json) query_json = get_main_instance_query_json(query_id) return post_query_to_client_instance(query_json)