Google Drive Python API:添加多个属性 [英] Google Drive Python API: Adding Multiple Properties

查看:125
本文介绍了Google Drive Python API:添加多个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与问题有关.

我想在文件的properties元数据字段中添加多个条目,以便可以使用files().list()对该文件建立索引.这是我的代码:

I would like to add multiple entries into the properties metadata field for a file so that the file is indexable using files().list(). Here is my code:

# define read and write permissions

SCOPES = ['https://www.googleapis.com/auth/drive.file']

# check if the user's access and refresh tokens already exist

import pickle
import os

if os.path.exists('token.pickle'):
    with open('token.pickle','rb') as f:
        creds = pickle.load(f)
else:
    creds = None

"""
If the user's access and refresh tokens don't exist, or they are no longer valid, then create them and save them. This will not work if the credentials.json file is not in the user's working directory.
"""

from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    
    with open('token.pickle', 'wb') as f:
        pickle.dump(creds,f)

"""
check that the authentication flow worked. This should be the same as the string in the "client_id" field in the credentials.json file. Additionally, if the access and refresh tokens did not already exist, then a token.pickle file should now be in the user's working directory.
"""

print('client_id is: {}'.format(creds.client_id))

# create a drive object to directly interface with the user's Google Drive.

from googleapiclient.discovery import build

drive = build('drive', 'v3',credentials=creds)

# create a folder in the root directory of the user's Google Drive.

folder_metadata = {
    
    'name': 'TestFolder',
    'mimeType': 'application/vnd.google-apps.folder'
    
}

folder = drive.files().create(body = folder_metadata, fields = 'id,name').execute()

# upload a file with indexable properties to the created folder

# first create the file
with open('HelloWorld.txt','w') as f:
    f.write('Hello World!')

# then define metadata
property1 = {'key' : 'day_of_week', 'value' : 'Monday'}
property2 = {'key' : 'patient_num', 'value' : '001'}

file_metadata = {
    'name': 'HelloWorld.txt',
    'parents': [folder['id']],
    'properties':[property1,property2]
}

# finally upload
from googleapiclient.http import MediaFileUpload

media = MediaFileUpload('HelloWorld.txt',chunksize = -1,resumable = False)
file = drive.files().create(body = file_metadata, media_body = media, fields = 'name,properties').execute()

# try to search for the file

query = "properties has {key = 'patient_num' and value = '001'}"

files_list = drive.files().list(q = query, fields = 'files(name,properties)').execute()

当我执行此代码时,files_list包含{'files': []}.这样做的原因是因为file变量包含:

When I execute this code, files_list contains {'files': []}. The reason for this is because the file variable contains:

{'name': 'HelloWorld.txt',
 'properties': {'value': 'Monday', 'key': 'day_of_week'}}

很显然,即使在file_metadata词典中明确定义了'patient_num'属性,也没有将它添加到properties字段中.我知道这个问题关于堆栈溢出,但是我认为所提出的解决方案效率低下.如何将多个属性添加到文件,以便可以同时使用day_of_week属性或patient_num属性或同时使用这两个属性对其进行索引?另外,一旦我能做到这一点,应该如何修改query以便能够同时使用多个属性进行索引?

Clearly, the 'patient_num' property was not added to the properties field, even though it was explicitly defined in the file_metadata dictionary. I am aware of this question on Stack Overflow, but I feel that the proposed solution is inefficient. How do I add multiple properties to a file so that it is indexable using either the day_of_week property or the patient_num property or both properties at the same time? Also, once I can do this, how should I modify query so that I am able to index using multiple properties simultaneously?

非常感谢您的帮助.

推荐答案

如果有人需要,这里是多种属性的正确查询格式.

Here is the correct query format for multiple properties in case anyone needs it.

# try to search for the file

query = "properties has {key = 'day_of_week' and value = 'Monday'} and properties has {key = 'patient_num' and value = '001'}"

files_list = drive.files().list(q = query, fields = 'files(name,properties)').execute()

完整的工作代码为:

# define read and write permissions

SCOPES = ['https://www.googleapis.com/auth/drive.file']

# check if the user's access and refresh tokens already exist

import pickle
import os

if os.path.exists('token.pickle'):
    with open('token.pickle','rb') as f:
        creds = pickle.load(f)
else:
    creds = None

"""
If the user's access and refresh tokens don't exist, or they are no longer valid, then create them and save them. This will not work if the credentials.json file is not in the user's working directory.
"""

from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    
    with open('token.pickle', 'wb') as f:
        pickle.dump(creds,f)

"""
check that the authentication flow worked. This should be the same as the string in the "client_id" field in the credentials.json file. Additionally, if the access and refresh tokens did not already exist, then a token.pickle file should now be in the user's working directory.
"""

print('client_id is: {}'.format(creds.client_id))

# create a drive object to directly interface with the user's Google Drive.

from googleapiclient.discovery import build

drive = build('drive', 'v3',credentials=creds)

# create a folder in the root directory of the user's Google Drive.

folder_metadata = {
    
    'name': 'TestFolder',
    'mimeType': 'application/vnd.google-apps.folder'
    
}

folder = drive.files().create(body = folder_metadata, fields = 'id,name').execute()

# upload a file with indexable properties to the created folder

# first create the file
with open('HelloWorld.txt','w') as f:
    f.write('Hello World!')

# then define metadata

properties = {
    'day_of_week' : 'Monday',
    'patient_num' : '001'
}

file_metadata = {
    'name' : 'HelloWorld.txt',
    'parents' : [folder['id']],
    'properties' : properties
}

# finally upload
from googleapiclient.http import MediaFileUpload

media = MediaFileUpload('HelloWorld.txt',chunksize = -1,resumable = False)
file = drive.files().create(body = file_metadata, media_body = media, fields = 'name,properties').execute()

# try to search for the file

query = "properties has {key = 'day_of_week' and value = 'Monday'} and properties has {key = 'patient_num' and value = '001'}"

files_list = drive.files().list(q = query, fields = 'files(name,properties)').execute()

请注意,同时查询多个属性的一般格式为:

Note that the general format to query multiple properties at the same time is:

"properties has {key = 'key1' and value = 'value1'} and properties has {key = 'key2' and value = 'value2'} and properties has {key = 'key3' and value = 'value3'} and ..."

希望这会有所帮助.

这篇关于Google Drive Python API:添加多个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆