简体   繁体   中英

how to create a table using the following python bigquery api?

Hello I cloned the following repository:

https://github.com/tylertreat/BigQuery-Python

I was reading the documentation about creating a table as follows:

schema = [
    {'name': 'foo', 'type': 'STRING', 'mode': 'nullable'},
    {'name': 'bar', 'type': 'FLOAT', 'mode': 'nullable'}
]
created = client.create_table('dataset', 'my_table', schema)

I tried to execute the same in my console as follows:

>>> schema = [
...     {'name': 'foo', 'type': 'STRING', 'mode': 'nullable'},
...     {'name': 'bar', 'type': 'FLOAT', 'mode': 'nullable'}
... ]
>>> created = client.create_table('data_set_course', 'my_table_testing', schema)

I only got 'False' and when I check the visual interface there is no table.

>>> print(created)
False
>>> 

I dont have any idea about the issue, I really frustrated since I just what to create one table, so I really would like to appreciate the support to overcome this task.

I have tested this code and it works for me:

from bigquery import get_client

# JSON key provided by Google
json_key = 'key.json'

client = get_client(json_key_file=json_key, readonly=False)

schema = [
    {'name': 'foo', 'type': 'STRING', 'mode': 'nullable'},
    {'name': 'bar', 'type': 'FLOAT', 'mode': 'nullable'}
]
created = client.create_table(dataset='yourDataset', table='tableToCreate', schema=schema)

You need to check 2 things:

  1. readonly parameter in the get_client method is set to False . Otherwise BigQuery access is read-only.

  2. The service account or user provided in the key.json file has been granted with the permissions to create a BigQuery table . At least it must have the roles/bigquery.dataEditor role granted. To do it run the following command:

gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/bigquery.dataEditor"


Anyway I recommend you to use the official Python Client for Google BigQuery , you will have better documentation and functionality. As well as a huge amount of code examples in the BigQuery official documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM