Skip to content

Commit

Permalink
fix: remove custom Exceptions and assert to make scripts executable…
Browse files Browse the repository at this point in the history
… at the simplest possible setup. (#780)
  • Loading branch information
lanlooker authored Aug 30, 2021
1 parent e6c67d1 commit 0126ad9
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 96 deletions.
9 changes: 2 additions & 7 deletions examples/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ The full details of all Looker API endpoints are listed in Looker Docs: [Version
- [Soft delete dashboard](soft_delete_dashboard.py)

## Query : Run and Manage Queries
- [Killing all running queries](kill_queries.py)
- [Kill all running queries](kill_queries.py)

## RenderTask : Manage Render Tasks

Expand All @@ -35,9 +35,4 @@ The full details of all Looker API endpoints are listed in Looker Docs: [Version

## User : Manage Users

- [Disable all active user sessions](logout_all_users.py)





- [Disable all active user sessions](logout_all_users.py)
Binary file not shown.
40 changes: 21 additions & 19 deletions examples/python/download_dashboard_pdf.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
"""Given a dashboard title, search all dashboards to retrieve its id, render and export the dashboard to pdf.
$ python download_dashboard_pdf.py <title> <dashboard_filters> <dashboard_style> <pdf_width> <pdf_height>
Note: dashboard_style defaults to "tiled", pdf_width defaults to 545, pdf_height defaults to 842
Examples:
$ python download_dashboard_pdf.py "A Test Dashboard"
$ python download_dashboard_pdf.py "A Test Dashboard" '{"filter1": "value1, value2", "filter2": "value3"}'
$ python download_dashboard_pdf.py "A Test Dashboard" {} "single_column"
Last modified: August 25, 2021
"""

import json
import urllib
import sys
Expand All @@ -8,28 +21,18 @@
import looker_sdk
from looker_sdk import models

import sdk_exceptions

sdk = looker_sdk.init31("../../looker.ini")
sdk = looker_sdk.init40("../../looker.ini")


def main():
"""Given a dashboard title, search all dashboards to retrieve its id and use
it to render the dashboard's pdf.
Examples of how to use this:
$ python download_dashboard_pdf.py "A Test Dashboard"
$ python download_dashboard_pdf.py "A Test Dashboard" '{"filter1": "value1, value2", "filter2": "value3"}'
$ python download_dashboard_pdf.py "A Test Dashboard" {} "single_column"
"""
dashboard_title = sys.argv[1] if len(sys.argv) > 1 else ""
filters = json.loads(sys.argv[2]) if len(sys.argv) > 2 else None
pdf_style = sys.argv[3] if len(sys.argv) > 3 else "tiled"
pdf_width = int(sys.argv[4]) if len(sys.argv) > 4 else 545
pdf_height = int(sys.argv[5]) if len(sys.argv) > 5 else 842

if not dashboard_title:
raise sdk_exceptions.ArgumentError(
raise Exception(
textwrap.dedent(
"""
Please provide: <dashboard_title> [<dashboard_filters>] [<dashboard_style>] [<pdf_width>] [<pdf_height>]
Expand All @@ -48,8 +51,7 @@ def get_dashboard(title: str) -> Optional[models.Dashboard]:
title = title.lower()
dashboard = next(iter(sdk.search_dashboards(title=title)), None)
if not dashboard:
raise sdk_exceptions.NotFoundError(f'dashboard "{title}" not found')
assert isinstance(dashboard, models.Dashboard)
raise Exception(f'dashboard "{title}" not found')
return dashboard


Expand All @@ -59,10 +61,10 @@ def download_dashboard(
width: int = 545,
height: int = 842,
filters: Optional[Dict[str, str]] = None,
):
):

"""Download specified dashboard as PDF"""
assert dashboard.id
id = int(dashboard.id)
id = dashboard.id
task = sdk.create_dashboard_render_task(
id,
"pdf",
Expand All @@ -75,7 +77,7 @@ def download_dashboard(
)

if not (task and task.id):
raise sdk_exceptions.RenderTaskError(
raise Exception(
f'Could not create a render task for "{dashboard.title}"'
)

Expand All @@ -86,7 +88,7 @@ def download_dashboard(
poll = sdk.render_task(task.id)
if poll.status == "failure":
print(poll)
raise sdk_exceptions.RenderTaskError(
raise Exception(
f'Render failed for "{dashboard.title}"'
)
elif poll.status == "success":
Expand Down
30 changes: 16 additions & 14 deletions examples/python/download_look.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
""" Given a look title, search all looks to retrieve its id, render and export the look to png or jpg.
$ python download_look.py <title> <image_width> <image_height> <image_format>
img_width defaults to 545, img_height defaults to 842, img_format defaults to png
Examples:
$ python download_look.py "A simple look"
$ python download_look.py "A simple look" 545 842 png
Last modified: August 25, 2021
"""

import sys
import textwrap
import time

import looker_sdk
from looker_sdk import models

import sdk_exceptions

sdk = looker_sdk.init31("../../looker.ini")

sdk = looker_sdk.init40("../../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 sdk_exceptions.ArgumentError(
raise Exception(
textwrap.dedent(
"""
Please provide: <lookTitle> [<img_width>] [<img_height>] [<img_format>]
Expand All @@ -40,14 +44,12 @@ def get_look(title: str) -> models.Look:
title = title.lower()
look = next(iter(sdk.search_looks(title=title)), None)
if not look:
raise sdk_exceptions.NotFoundError(f"look '{title}' was not found")
assert isinstance(look, models.Look)
raise Exception(f"look '{title}' was not found")
return look


def download_look(look: models.Look, result_format: str, width: int, height: int):
"""Download specified look as png/jpg"""
assert look.id
id = int(look.id)
task = sdk.create_look_render_task(id, result_format, width, height,)

Expand All @@ -63,7 +65,7 @@ def download_look(look: models.Look, result_format: str, width: int, height: int
poll = sdk.render_task(task.id)
if poll.status == "failure":
print(poll)
raise sdk_exceptions.RenderTaskError(f"Render failed for '{look.title}'")
raise Exception(f"Render failed for '{look.title}'")
elif poll.status == "success":
break
time.sleep(delay)
Expand Down
25 changes: 13 additions & 12 deletions examples/python/query_task.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
"""Given a model, view, and fields, create a query, and then a query task to asynchronously execute.
$ python query_task.py <model_name> <view_name> <field_1> <field_2> ...
Examples:
$ python query_task.py thelook users users.first_name users.last_name ...
Last modified: August 25
"""

import sys
import textwrap
import time
Expand All @@ -6,8 +16,6 @@
import looker_sdk
from looker_sdk import models40 as models

import sdk_exceptions

sdk = looker_sdk.init40("../../looker.ini")


Expand All @@ -19,7 +27,6 @@ def main_models(model: str, view: str, fields: List[str]) -> str:
body=models.WriteQuery(model=model, view=view, fields=fields)
)
# WriteCreateQueryTask.result_format is an enum
assert query.id
create_query_task = models.WriteCreateQueryTask(
query_id=query.id, result_format=models.ResultFormat.csv
)
Expand All @@ -30,11 +37,10 @@ def main_models(model: str, view: str, fields: List[str]) -> str:
elapsed = 0.0
delay = 0.5 # wait .5 seconds
while True:
assert task.id
poll = sdk.query_task(query_task_id=task.id)
if poll.status == "failure" or poll.status == "error":
print(poll)
raise sdk_exceptions.RenderTaskError("Query failed")
raise Exception("Query failed")
elif poll.status == "complete":
break
time.sleep(delay)
Expand Down Expand Up @@ -71,7 +77,7 @@ def main_dictionaries(model, view, fields):
poll = sdk.query_task(query_task_id=task["id"])
if poll["status"] == "error":
print(poll)
raise sdk_exceptions.RenderTaskError("Query failed")
raise Exception("Query failed")
elif poll["status"] == "complete":
break
time.sleep(delay)
Expand All @@ -82,17 +88,12 @@ def main_dictionaries(model, view, fields):


def main():
"""Given a model, view, and fields create a query, and then a query task
to asynchronously execute.
$ python query_task.py thelook users users.first_name [users.last_name users.email ...]
"""
model = sys.argv[1] if len(sys.argv) > 1 else ""
view = sys.argv[1] if len(sys.argv) > 1 else ""
try:
model, view, *fields = sys.argv[1:]
except ValueError:
raise sdk_exceptions.ArgumentError(
raise Exception(
textwrap.dedent(
"""
Please provide: <model> <view> <field1> [<field2> ...]
Expand Down
33 changes: 17 additions & 16 deletions examples/python/run_look_with_filters.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,33 @@
""" Given a look id, get the query behind the look, run the query with the desire filter values.
$ python run_look_with_filters.py <look_id> <filter_1> <filter_value_1> <filter_2> <filter_value_2>
Examples:
$ python run_look_with_filters.py 1 category.name socks users.gender m
Notes: See examples of how filters are defined in the posted body at
https://docs.looker.com/reference/api-and-integration/api-reference/v4.0/query#implementation_notes_9
Last modified: August 25, 2021
"""

import json
import sys
from typing import cast, Dict, List, Union

import looker_sdk
from looker_sdk import models, error

import sdk_exceptions

sdk = looker_sdk.init31("../../looker.ini")
sdk = looker_sdk.init40("../../looker.ini")


def main() -> None:
"""Given a look id, obtain the query behind it and run it with the desired
filter values.
https://docs.looker.com/reference/api-and-integration/api-reference/v3.1/query#implementation_notes_9 # noqa: B950
shows an example of how filters are defined in the posted body. To set the
same filter in this example, the script needs to be run as follows:
$ python run_look_with_filters.py 5 category.name socks
"""
look_id = sys.argv[1] if len(sys.argv) > 1 else ""
filter_args = iter(sys.argv[2:])
filters: Dict[str, str] = {}

if not (look_id and len(sys.argv[2:]) > 0 and len(sys.argv[2:]) % 2 == 0):
raise sdk_exceptions.ArgumentError(
raise Exception(
"Please provide: <lookId> <filter_1> <filter_value_1> "
"<filter_2> <filter_value_2> ..."
)
Expand All @@ -44,10 +46,9 @@ def get_look_query(id: int) -> models.Query:
try:
look = sdk.look(id)
except error.SDKError:
raise sdk_exceptions.NotFoundError(f"Error getting Look {id}")
raise Exception(f"Error getting Look {id}")
else:
query = look.query
assert isinstance(query, models.Query)
return query


Expand All @@ -60,7 +61,7 @@ def run_query_with_filter(query: models.Query, filters: Dict[str, str]) -> TJson
try:
json_ = sdk.run_inline_query("json", request, cache=False)
except error.SDKError:
raise sdk_exceptions.RunInlineQueryError("Error running query")
raise Exception("Error running query")
else:
json_resp = cast(TJson, json.loads(json_))
return json_resp
Expand Down
18 changes: 0 additions & 18 deletions examples/python/sdk_exceptions.py

This file was deleted.

25 changes: 15 additions & 10 deletions examples/python/test_connection.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
""" Given a connection name, obtain all supported tests, and run these test
$ python test_connection.py <connection_name>
Example:
$ python test_connection.py thelook
Notes: Connections to Looker's internal database cannot be tested.
Last modified: August 25, 2021
"""

from functools import reduce
import sys
from typing import cast, MutableSequence, Sequence

import looker_sdk
from looker_sdk import models

import sdk_exceptions

sdk = looker_sdk.init31("../../looker.ini")

sdk = looker_sdk.init40("../../looker.ini")

def main():
"""Given a connection, obtain its supported tests and run them. Example:
$ python test_connection.py thelook
"""
connection_name = sys.argv[1] if len(sys.argv) > 1 else ""

if not connection_name:
raise sdk_exceptions.ArgumentError("Please provide a connection name")
raise Exception("Please provide a connection name")
elif connection_name in ["looker", "looker__internal__analytics"]:
raise sdk_exceptions.ArgumentError(
raise Exception(
f"Connection '{connection_name}' is internal and cannot be tested."
)

Expand Down

0 comments on commit 0126ad9

Please sign in to comment.