-
-
Save samkit5495/ff8e2a6644363cadaec3fa22ddf38c90 to your computer and use it in GitHub Desktop.
from __future__ import print_function | |
import httplib2 | |
import os | |
from apiclient import discovery | |
from oauth2client import client | |
from oauth2client import tools | |
from oauth2client.file import Storage | |
try: | |
import argparse | |
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() | |
except ImportError: | |
flags = None | |
# If modifying these scopes, delete your previously saved credentials | |
# at ~/.credentials/people.googleapis.com-python-quickstart.json | |
SCOPES = 'https://www.googleapis.com/auth/contacts' | |
CLIENT_SECRET_FILE = 'client_secret.json' | |
APPLICATION_NAME = 'People API Python Quickstart' | |
def get_credentials(): | |
"""Gets valid user credentials from storage. | |
If nothing has been stored, or if the stored credentials are invalid, | |
the OAuth2 flow is completed to obtain the new credentials. | |
Returns: | |
Credentials, the obtained credential. | |
""" | |
home_dir = os.path.expanduser('./') | |
credential_dir = os.path.join(home_dir, '.credentials') | |
if not os.path.exists(credential_dir): | |
os.makedirs(credential_dir) | |
credential_path = os.path.join(credential_dir, | |
'people.googleapis.com-python-quickstart.json') | |
store = Storage(credential_path) | |
credentials = store.get() | |
if not credentials or credentials.invalid: | |
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) | |
flow.user_agent = APPLICATION_NAME | |
if flags: | |
credentials = tools.run_flow(flow, store, flags) | |
else: # Needed only for compatibility with Python 2.6 | |
credentials = tools.run(flow, store) | |
print('Storing credentials to ' + credential_path) | |
return credentials | |
credentials = get_credentials() | |
http = credentials.authorize(httplib2.Http()) | |
service = discovery.build('people', 'v1', http=http, | |
discoveryServiceUrl='https://people.googleapis.com/$discovery/rest') | |
service.people().createContact(body={ | |
"names": [ | |
{ | |
"givenName": "Samkit" | |
} | |
], | |
"phoneNumbers": [ | |
{ | |
'value': "8600086024" | |
} | |
], | |
"emailAddresses": [ | |
{ | |
'value': '[email protected]' | |
} | |
] | |
}).execute() |
check if client_secret.json file is present in the same folder, if its there share your code so w can validate further
check if client_secret.json file is present in the same folder, if its there share your code so w can validate further
Thanks
def get_credentials():
Upon Def is ok.
But the
service.people().createContact(parent='people/me', body={ "names": [ { "givenName": "Samkit" } ], "phoneNumbers": [ { 'value': "8600086024" } ], "emailAddresses": [ { 'value': '[email protected]' } ] }).execute() @techmodule
This code can not run
File "/Users/nguyenngoclinh/.conda/envs/1z_vietnam/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
return wrapped(*args, **kwargs)
Full code
from __future__ import print_function
import httplib2
from oauth2client import tools
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from apiclient import discovery
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# Set up a Flow object to be used if we need to authenticate. This
# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
# the information it needs to authenticate. Note that it is called
# the Web Server Flow, but it can also handle the flow for
# installed applications.
#
# Go to the Google API Console, open your application's
# credentials page, and copy the client ID and client secret.
# Then paste them into the following code.
FLOW = OAuth2WebServerFlow(
client_id='592262365202-h6qu4mrf2b043e2gv2qf5grjg0j532s5.apps.googleusercontent.com',
client_secret='VVxrBm9SE1ONzyX1oIEwSfB2',
scope='https://www.googleapis.com/auth/contacts',
user_agent='contact_cms/YOUR_APPLICATION_VERSION')
# If the Credentials don't exist or are invalid, run through the
# installed application flow. The Storage object will ensure that,
# if successful, the good Credentials will get written back to a
# file.
def get_credentials(FLOW):
storage = Storage('info.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = tools.run_flow(FLOW, storage)
return credentials
# Create an httplib2.Http object to handle our HTTP requests and
# authorize it with our good Credentials.
def get_http(credentials):
http = httplib2.Http()
http = credentials.authorize(http)
return http
# Build a service object for interacting with the API. To get an API key for
# your application, visit the Google API Console
# and look at your application's credentials page.
def print_list_google_contact_with_number_of_contacts(creds, numberofcontact):
# Call the People API
service = build('people', 'v1', credentials=creds)
print('Ban dang in ra ', numberofcontact, ' danh ba')
results = service.people().connections().list(
resourceName='people/me',
pageSize=numberofcontact,
personFields='names,emailAddresses,phoneNumbers,emailAddresses,addresses').execute()
connections = results.get('connections', [])
# for person in connections:
# names = person.get('names', [])
# if names:
# name = names[0].get('displayName')
# print(name)
for person in connections:
names = person.get('names', [])
if names:
name = names[0].get('displayName')
else:
name = None
phoneNumbers = person.get('phoneNumbers', [])
if phoneNumbers:
phoneNumber = phoneNumbers[0].get('value')
else:
phoneNumber = None
Cities = person.get('addresses', [])
if Cities:
City = Cities[0].get('city')
else:
City = None
emails = person.get('emailAddresses', [])
if emails:
email = emails[0].get('value')
else:
email = None
print(f'{name}: {phoneNumber}: {City}: {email}')
def creat_a_google_contact(http):
service = discovery.build('people', 'v1', http=http, discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
service.people().createContact(parent='people/me', body={
"names": [
{
'givenName': "Samkafafsafsafit"
}
],
"phoneNumbers": [
{
'value': "8600086024"
}
],
"emailAddresses": [
{
'value': "[email protected]"
}
]
}).execute()
def main():
creds=get_credentials(FLOW)
http=get_http(creds)
printout=print_list_google_contact_with_number_of_contacts(creds,10)
creat_a_google_contact(http)
return print(printout)
if __name__ == '__main__':
main()
Problems for this cod
def creat_a_google_contact(http):
service = discovery.build('people', 'v1', http=http, discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
service.people().createContact(parent='people/me', body={
"names": [
{
'givenName': "Samkafafsafsafit"
}
],
"phoneNumbers": [
{
'value': "8600086024"
}
],
"emailAddresses": [
{
'value': "[email protected]"
}
]
}).execute()
Logs of Errors
Traceback (most recent call last):
File "/Users/nguyenngoclinh/cms/cmsproject/google_contacts_cms/setup_your_app.py", line 116, in <module>
main()
File "/Users/nguyenngoclinh/cms/cmsproject/google_contacts_cms/setup_your_app.py", line 113, in main
creat_a_google_contact(http)
File "/Users/nguyenngoclinh/cms/cmsproject/google_contacts_cms/setup_your_app.py", line 104, in creat_a_google_contact
'value': "[email protected]"
File "/Users/nguyenngoclinh/.conda/envs/1z_vietnam/lib/python3.7/site-packages/googleapiclient/discovery.py", line 840, in method
raise TypeError('Got an unexpected keyword argument "%s"' % name)
TypeError: Got an unexpected keyword argument "parent"
Relate for this error
def method(self, **kwargs):
# Don't bother with doc string, it will be over-written by createMethod.
for name in six.iterkeys(kwargs):
if name not in parameters.argmap:
raise TypeError('Got an unexpected keyword argument "%s"' % name)
Remove parent='people/me', from function its a change from google APIs end, its depricated.
Thank you So Much
It worked
def creat_a_google_contact(http):
service = discovery.build('people', 'v1', http=http, discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
service.people().createContact(body={
"names": [
{
'givenName': "Samkafafsafsafit"
}
],
"phoneNumbers": [
{
'value': "8600086024"
}
],
"emailAddresses": [
{
'value': "[email protected]"
}
]
}).execute()
Hi
i also make the delete fuction but it is not work :(
def delete_contacts_with_resourceName(creds,http,number_of_contact):
# Call the People API
service = build('people', 'v1', credentials=creds)
print('Ban dang xoa', number_of_contactcontact, 'contacts')
results = service.people().connections().list(
resourceName='people/me',
pageSize=number_of_contactofcontact,
personFields='names,emailAddresses,phoneNumbers,emailAddresses,addresses').execute()
service = discovery.build('people', 'v1', http=http,
discoveryServiceUrl='https://people.googleapis.com/$discovery/rest')
connections = results.get('connections', [])
for person in connections:
abcd = person.get('resourceName')
service.people().deleteContact(resourceName={abcd}).execute()
Dear, i used your new code in my localhost is ok? but after i deploy to server, it can not run? the link to authithencate not open in brower
It's not developed for the remote servers, we can use this for console applications.
I try that but see
Traceback (most recent call last):
File "/Users/nguyenngoclinh/cms/cmsproject/google_contacts_cms/setup_your_app.py", line 117, in
main()
File "/Users/nguyenngoclinh/cms/cmsproject/google_contacts_cms/setup_your_app.py", line 113, in main
creat_a_google_contact(http)
File "/Users/nguyenngoclinh/cms/cmsproject/google_contacts_cms/setup_your_app.py", line 91, in creat_a_google_contact
service = discovery.build('people', 'v1', http=http, discoveryServiceUrl='https://people.googleapis.com/v1/people:createContact')
File "/Users/nguyenngoclinh/.conda/envs/1z_vietnam/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Users/nguyenngoclinh/.conda/envs/1z_vietnam/lib/python3.7/site-packages/googleapiclient/discovery.py", line 264, in build
raise e
File "/Users/nguyenngoclinh/.conda/envs/1z_vietnam/lib/python3.7/site-packages/googleapiclient/discovery.py", line 246, in build
requested_url, discovery_http, cache_discovery, cache, developerKey
File "/Users/nguyenngoclinh/.conda/envs/1z_vietnam/lib/python3.7/site-packages/googleapiclient/discovery.py", line 308, in _retrieve_discovery_doc
raise HttpError(resp, content, uri=actual_url)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://people.googleapis.com/v1/people:createContact returned "personFields mask is required. Please specify one or more valid paths. Valid paths are documented at https://developers.google.com/people/api/rest/v1/people/get.">
Process finished with exit code 1