I am trying to download file from google drive with pydrive. code is modified from Automating pydrive verification process
And it is giving following error.
$ python driveDownload.py a a.xls
Google Drive Token Expired, Refreshing
Traceback (most recent call last):
File "driveDownload.py", line 26, in <module>
gauth.Refresh()
File "build/bdist.linux-x86_64/egg/pydrive/auth.py", line 369, in Refresh
pydrive.auth.RefreshError: No refresh_token found.Please set access_type of OAuth to offline.
Hence I followed instructions as per stackoverflow here
Unable to get it working. Am I missing something basic ?
my settings.yaml is below
client_config_backend: settings
client_config:
client_id: ###
client_secret: ###
save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json
get_refresh_token: True
oauth_scope:
- https://www.googleapis.com/auth/drive.file
- https://www.googleapis.com/auth/drive.install
I am getting following error :
$ python driveDownload.py a a.xls
Google Drive Token Expired, Refreshing
Traceback (most recent call last):
File "driveDownload.py", line 26, in <module>
gauth.Refresh()
File "build/bdist.linux-x86_64/egg/pydrive/auth.py", line 369, in Refresh
pydrive.auth.RefreshError: No refresh_token found.Please set access_type of OAuth to offline.
my code is driveDownload.py :
from pydrive.auth import GoogleAuth
import os
from pydrive.drive import GoogleDrive
import sys
#USAGE: python driveDownload.py googleDriveName localFileName
#authentication via the browser
#note... client_secrets.json is required for this that leads
#to the user authentication
fileName2Download = sys.argv[1]
#myLocalPath is hard coded and
myLocalPath = sys.argv[2]
# gauth = GoogleAuth()
gauth = GoogleAuth()
# Try to load saved client credentials
gauth.LoadCredentialsFile("GoogleDriveCredentials.txt")
if gauth.credentials is None:
# Authenticate if they're not there
gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
# Refresh them if expired
print "Google Drive Token Expired, Refreshing"
gauth.Refresh()
else:
# Initialize the saved creds
gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("GoogleDriveCredentials.txt")
#accessing the drive
drive = GoogleDrive(gauth)
# Auto-iterate through all files that matches this query
file_list = drive.ListFile().GetList()
for file1 in file_list:
#download the file hello.txt ad myDownload.txt
print 'title: %s, id: %s , mimeType = %s' % (file1['title'], file1['id'],file1['mimeType'])
if file1['title'] == fileName2Download:
print ' file Title identiefied :%s'% (file1['title'])
# contentString = file1.GetContentString()
# print 'contentString : %s' % (contentString)
myFile = drive.CreateFile({'id': file1['id']})
if os.path.exists(myLocalPath):
os.remove(myLocalPath)
myFile.GetContentFile(myLocalPath,mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
print '%s downloaded ' %(myLocalPath)
break
Related
I downloaded the gsuite developers python code from :
(https://github.com/gsuitedevs/python-samples)
I then enabled api access and downloaded the credentials.json file and ran the quickstart.py in:
(python-samples-master/slides/quickstart) and it worked and outputted
The presentation contains 5 slides:
- Slide #1 contains 4 elements.
- Slide #2 contains 11 elements.
- Slide #3 contains 9 elements.
- Slide #4 contains 5 elements.
- Slide #5 contains 12 elements.
So it worked. Then I tried to run test_snippets.py in:
(python-samples-master/slides/snippets)
And I get an error
======================================================================
ERROR: setUpClass (__main__.SnippetsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "~/anaconda3/lib/python3.7/site-packages/oauth2client/client.py", line 1228, in _implicit_credentials_from_files
credentials_filename)
File "~/anaconda3/lib/python3.7/site-packages/oauth2client/client.py", line 1397, in _get_application_default_credential_from_file
AUTHORIZED_USER + "' or '" + SERVICE_ACCOUNT + "' values)")
oauth2client.client.ApplicationDefaultCredentialsError: 'type' field should be defined (and have one of the 'authorized_user' or 'service_account' values)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test_snippets.py", line 32, in setUpClass
super(SnippetsTest, cls).setUpClass()
File "~/Desktop/python-samples-master/slides/snippets/base_test.py", line 27, in setUpClass
cls.credentials = cls.create_credentials()
File "~/Desktop/python-samples-master/slides/snippets/base_test.py", line 44, in create_credentials
credentials = GoogleCredentials.get_application_default()
File "~/anaconda3/lib/python3.7/site-packages/oauth2client/client.py", line 1271, in get_application_default
return GoogleCredentials._get_implicit_credentials()
File "~/anaconda3/lib/python3.7/site-packages/oauth2client/client.py", line 1256, in _get_implicit_credentials
credentials = checker()
File "~/anaconda3/lib/python3.7/site-packages/oauth2client/client.py", line 1231, in _implicit_credentials_from_files
extra_help, error)
File "~/anaconda3/lib/python3.7/site-packages/oauth2client/client.py", line 1429, in _raise_exception_for_reading_json
credential_file + extra_help + ': ' + str(error))
oauth2client.client.ApplicationDefaultCredentialsError: An error was encountered while reading json file: ~/Documents/credentials/credentials.json (pointed to by GOOGLE_APPLICATION_CREDENTIALS environment variable): 'type' field should be defined (and have one of the 'authorized_user' or 'service_account' values)
I definitely have a GOOGLE_APPLICATION_CREDENTIALS that points to the same credentials that successfully ran quickstart.py.
Is there something else I need or do I need to change some code to load the credentials data in?
It seems like GoogleCredentials.get_application_default() call is the one that is erroring
def create_credentials(cls):
credentials = GoogleCredentials.get_application_default()
scope = [
'https://www.googleapis.com/auth/drive',
]
return credentials.create_scoped(scope)
The file pointed to the environment variable GOOGLE_APPLICATION_CREDENTIALS is not a valid service account json file.
Open your service account json file. The beginning of the file should look similar to this:
{
"type": "service_account",
"project_id": "development-123456",
"private_key_id": "19c38bac6560abcdef01234567ac4da7991cbaad",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANB
code:
import twitter
consumer_key = 'xyz'
consumer_secret = 'xyz'
access_token = 'xyz-xyz'
access_token_secret = 'xyz'
my_api = twitter.Api(consumer_key='consumer_key',
consumer_secret='consumer_secret',
access_token_key='access_token',
access_token_secret='access_token_secret')
users = my_api.GetFriends()
print([u.name for u in users])
when I run my python script I am getting below error, I have verified the access token key and it as per the details I generated over twitter app.
error:
C:\Python\twitter_api>python twit_it_up.py
Traceback (most recent call last):
File "twit_it_up.py", line 13, in <module>
users = my_api.GetFriends()
File "C:\Python27\lib\site-packages\twitter\api.py", line 2776, in
GetFriends
include_user_entities)
File "C:\Python27\lib\site-packages\twitter\api.py", line 2671, in
_GetFriendsFollowers
include_user_entities)
File "C:\Python27\lib\site-packages\twitter\api.py", line 2499, in
_GetFriendsFollowersPaged
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
File "C:\Python27\lib\site-packages\twitter\api.py", line 4908, in
_ParseAndCheckTwitter
self._CheckForTwitterError(data)
File "C:\Python27\lib\site-packages\twitter\api.py", line 4928, in
_CheckForTwitterError
raise TwitterError(data['errors'])
twitter.error.TwitterError: [{u'message': u'Invalid or expired token.',
u'code': 89}]
I am trying to enumerate Azure AD users from an azure subscription, with this code:
WORKING_DIRECTORY = os.getcwd()
TENANT_ID = "REDACTED_AZURE_ID_OF_MY_AZURE_AD_USER"
AZURE_AUTH_LOCATION = os.path.join(WORKING_DIRECTORY, "mycredentials.json") # from: az ad sp create-for-rbac --sdk-auth > mycredentials.json
# I've tried with get_client_from_cli_profile() while logged in azure CLI
# I've tried with and without parameters auth_path and tenant_id
rbac_client = get_client_from_auth_file(GraphRbacManagementClient,auth_path=AZURE_AUTH_LOCATION, tenant_id=TENANT_ID)
# Try to list users
for user in rbac_client.users.list():
pprint(user.__dict__)
As I've detailed in the comments, I've tried to fix the issue with a couple of unsuccessful attempts, here is the stacktrace
/home/guillaumedsde/.virtualenvs/champollion/bin/python /home/guillaumedsde/PycharmProjects/champollion/champollion/champollion.py
Traceback (most recent call last):
File "/home/guillaumedsde/PycharmProjects/champollion/champollion/champollion.py", line 582, in <module>
gitlab_project_member.access_level)
File "/home/guillaumedsde/PycharmProjects/champollion/champollion/champollion.py", line 306, in create_role_assignment
"principal_id": get_user_azure_id(user)} # get_user_azure_id(user)} # TODO
File "/home/guillaumedsde/PycharmProjects/champollion/champollion/champollion.py", line 329, in get_user_azure_id
for user in rbac_client.users.list():
File "/home/guillaumedsde/.virtualenvs/champollion/lib/python3.6/site-packages/msrest/paging.py", line 131, in __next__
self.advance_page()
File "/home/guillaumedsde/.virtualenvs/champollion/lib/python3.6/site-packages/msrest/paging.py", line 117, in advance_page
self._response = self._get_next(self.next_link)
File "/home/guillaumedsde/.virtualenvs/champollion/lib/python3.6/site-packages/azure/graphrbac/operations/users_operations.py", line 158, in internal_paging
raise models.GraphErrorException(self._deserialize, response)
azure.graphrbac.models.graph_error.GraphErrorException: Operation returned an invalid status code 'Not Found'
Process finished with exit code 1
Was a bug fixed in azure-common 1.1.13
https://pypi.org/project/azure-common/1.1.13/
You can now simply do that (with no tenant ID)
rbac_client = get_client_from_auth_file(GraphRbacManagementClient,auth_path=AZURE_AUTH_LOCATION)
I took this opportunity to fix the CLI version of this method as well.
(I own this code at MS)
I am trying to build on a test Twilio script in order that the POST request can just use values returned by method is a script.
The values are set as environmental variables and I have checked that they are correct in the Python shell using the same command as the script.
Python 2.7 being used.
The environmental variables are stored as strings and return as such.
from twilio.rest import TwilioRestClient
import os
ACCOUNT_SID = os.environ['ACCOUNT_SID']
AUTH_TOKEN = os.environ['AUTH_TOKEN']
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
def target_number():
return os.environ['TARGET_NUMBER']
def my_number():
return os.environ['MY_NUMBER']
message = client.messages.create(
body="foo bar", # Message body, if any
to=target_number(),
from_=my_number(),
)
print message.body
I am getting the following error:
python my_twilio_testing_script.py
Traceback (most recent call last):
File "my_twilio_testing_script.py", line 19, in <module>
to=target_number(),
File "my_twilio_testing_script.py", line 9, in target_number
return os.environ['TARGET_NUMBER']
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: 'TARGET_NUMBER'
Twilio developer evangelist here.
It appears that some of your environment variables are working, otherwise the script would blow up when you set the account SID and auth token.
So it seems that maybe TARGET_NUMBER is perhaps not set. In the terminal window in which you run the script, are you able to perform the following bash command:
$ echo $TARGET_NUMBER
Does that show the number you expect? If not, you may need to export the environment variable again.
I have already looked at and tried the resolutions to this question that others have posted. One user said that to try and change my setup.py file from:
from distutils.core import setup
import py2exe
setup(console=["dev.py"])
to
from distutils.core import setup
import py2exe
setup(service=["dev.py"])
I got the following results:
running py2exe
*** searching for required modules ***
Traceback (most recent call last):
File "C:\Python27\Scripts\distutils-setup.py", line 5, in <module>
setup(service=["C:\Python27\Scripts\dev.py"])
File "C:\Python27\lib\distutils\core.py", line 152, in setup
dist.run_commands()
File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands
self.run_command(cmd)
File "C:\Python27\lib\distutils\dist.py", line 972, in run_command
cmd_obj.run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 243, in run
self._run()
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 296, in _run
self.find_needed_modules(mf, required_files, required_modules)
File "C:\Python27\lib\site-packages\py2exe\build_exe.py", line 1274, in
find_needed_modules
mf.import_hook(mod)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 719, in import_hook
return Base.import_hook(self,name,caller,fromlist,level)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 136, in import_hook
q, tail = self.find_head_package(parent, name)
File "C:\Python27\lib\site-packages\py2exe\mf.py", line 204, in find_head_package
raise ImportError, "No module named " + qname
ImportError: No module named dev
Now, when I run py2exe with "console" in my setup script it works fine, but the service doesn't start and I get the error. When I run py2exe with "service" in my setup script py2exe doesn't run and tells me it can't find my module.
I have tried to re-install py2exe to no resolution. I have also tried to change:
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
to
def SvcDoRun(self):
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
Didn't make a difference either. CAN ANYONE HELP ME PLEASE? Here is what I am working on. It monitors a server and spits back a text file every 60 seconds which I use to monitor my servers at any given minute. Any help you guys and gals can give would be great.
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import wmi
import _winreg
from time import sleep
import os
class SrvMonSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "SrvMonSvc"
_svc_display_name_ = "Server Monitor"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
host = wmi.WMI(namespace="root/default").StdRegProv
try:
result, api = host.GetStringValue(
hDefKey = _winreg.HKEY_LOCAL_MACHINE,
sSubKeyName = "SOFTWARE\Server Monitor",
sValueName = "API")
if api == None:
raise Exception
else:
pass
except:
exit()
while 1 == 1:
with open("C:/test.txt", "wb") as b:
computer = wmi.WMI(computer="exsan100")
for disk in computer.Win32_LogicalDisk (DriveType=3):
name = disk.caption
size = round(float(disk.Size)/1073741824, 2)
free = round(float(disk.FreeSpace)/1073741824, 2)
used = round(float(size), 2) - round(float(free), 2)
for mem in computer.Win32_OperatingSystem():
a_mem = (int(mem.FreePhysicalMemory)/1024)
for me in computer.Win32_ComputerSystem():
t_mem = (int(me.TotalPhysicalMemory)/1048576)
u_mem = t_mem - a_mem
for cpu in computer.Win32_Processor():
load = cpu.LoadPercentage
print >>b, api
print >>b, name
print >>b, size
print >>b, used
print >>b, t_mem
print >>b, u_mem
print >>b, load
b.close()
date_list = []
stamp = time.strftime("%c",time.localtime(time.time()))
date_list.append(stamp)
name = re.sub(r"[^\w\s]", "",date_list[0])
os.rename("C:/test.txt", ("C:/%s.txt" % name))
try:
sleep(60.00)
except:
exit()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(SrvMonSvc)
Have you progressed from your original problem. I had similar problem with a python service and found out that it was missing DLLs since the 'System Path' (not the user path) was not complete.
Running pythonservice.exe with -debug from the command prompt was not a problem because it used correct PATH environment variable, but if your service is installed as a System service it's worth checking out if the System Path variable has all the paths for the required DLLs (MSVC, Python, System32). For me it was missing the python DLLs path, after that it worked again.