Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save drewgillson/295c216e2cfd3c2dd73db2bb64b89a71 to your computer and use it in GitHub Desktop.
Save drewgillson/295c216e2cfd3c2dd73db2bb64b89a71 to your computer and use it in GitHub Desktop.
"""
This is a Google Cloud Function, it can be deployed like this:
gcloud functions deploy download_full_look --env-vars-file .env.yaml --runtime python37 --trigger-http --allow-unauthenticated
You need a requirements.txt in the same directory, to specify the Flask
and Looker SDK versions. You also need a .env.yaml file to contain
environment variable values for the Looker SDK!
Read logs like this:
gcloud functions logs read download_full_look
"""
import looker_sdk
from looker_sdk import models
from flask import send_file
from tempfile import mktemp
def download_full_look(request):
sdk = looker_sdk.init31()
request_args = request.args # flask.Request object provided by GCP
if request_args and 'product.name' in request_args:
name = request_args['product.name']
else:
name = 'banana'
look = sdk.look(1)
query = look.query
query.fields.append('product.quantity_on_order')
filters = {}
filters['product.name'] = name
request = create_query_request(query, filters)
results = sdk.run_inline_query("csv", request, cache=False)
return(file_for_results(results))
def file_for_results(results):
fn = mktemp()
with open(fn, "w") as f:
f.write(results)
return send_file(
fn,
mimetype="text/csv",
attachment_filename="results.csv",
as_attachment=True,
)
def create_query_request(q: models.Query, filters) -> models.WriteQuery:
return models.WriteQuery(
model=q.model,
view=q.view,
fields=q.fields,
pivots=q.pivots,
fill_fields=q.fill_fields,
filters=filters,
sorts=q.sorts,
limit=q.limit,
column_limit=q.column_limit,
total=q.total,
row_total=q.row_total,
subtotals=q.subtotals,
dynamic_fields=q.dynamic_fields,
query_timezone=q.query_timezone,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment