{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Access Public Data from BigQuery\n", "\n", "This example illustrates how to create a Google cloud credentials object from your Data Observatory enabled CARTO account." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from cartoframes.auth import Credentials\n", "\n", "creds = Credentials.from_file('creds.json')" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from google.oauth2.credentials import Credentials as GoogleCredentials\n", "\n", "gcloud_project, gcloud_token = creds.get_gcloud_credentials()\n", "gcloud_credentials = GoogleCredentials(gcloud_token)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "from google.cloud import bigquery, storage\n", "\n", "bq_client = bigquery.Client(project=gcloud_project, credentials=gcloud_credentials)\n", "gcs_client = storage.Client(project=gcloud_project, credentials=gcloud_credentials)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As an example, the following code shows how to use the Google BigQuery client to access to a public dataset from Data Observatory:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "from cartoframes.data.observatory import Dataset\n", "\n", "dataset = Dataset.get('acs_sociodemogr_8c2655e0')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'carto-do-public-data.usa_acs.demographics_sociodemographics_usa_county_2015_5yrs_20132017'" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dataset.id" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "query_job = bq_client.query('SELECT * FROM `{}` LIMIT 1'.format(dataset.id))\n", "results = query_job.result()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[SchemaField('geoid', 'STRING', 'NULLABLE', None, (), None),\n", " SchemaField('do_date', 'DATE', 'NULLABLE', None, (), None),\n", " SchemaField('total_pop', 'FLOAT', 'NULLABLE', None, (), None)]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "results.schema[0:3]" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "18025 10598.0\n" ] } ], "source": [ "for row in results:\n", " print(row['geoid'], row['total_pop'])" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.5" } }, "nbformat": 4, "nbformat_minor": 4 }