Google Sheets API Won't Authorize - Python - python-3.x

Hi StackOverflow Community,
Thanks in advance for your help.
I have set up a Python script to make some requests to the Google Sheets API. The code for my script is below:
from googleapiclient import discovery
credentials ='https://www.googleapis.com/auth/spreadsheets' #Should give read/write scope to my spreadsheets
service = discovery.build('sheets', 'v4', credentials=credentials)
spreadsheet_id ='1z2QzPf9Kc02roOwTJUYab4k2dwYu1n-nIbJ5yzWF3YE' #COPY
ranges=['A1:C10']
include_grid_data = False
request = service.spreadsheets().get(spreadsheetId=spreadsheet_id,
ranges=ranges, includeGridData=include_grid_data)
response = request.execute()
The problem is that when I run this I get the following error:
File "C:\Users\evank\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\googleapiclient\_auth.py", line 92, in authorized_http
return credentials.authorize(build_http())
builtins.AttributeError: 'str' object has no attribute 'authorize'
The full code of this file listed in the error is located here: https://github.com/google/google-api-python-client/blob/master/googleapiclient/_auth.py
I'm working on this for an assignment and can't figure out why this error is occurring. Please help!
Thanks,
evank28

I had problems with this.
This link should help: https://medium.com/#rqaiserr/how-to-connect-to-google-sheets-with-python-83d0b96eeea6
Make sure to also read this: https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html
Just note that you need to add this line of code to your project after following the instructions above:
from oauth2client.service_account import ServiceAccountCredentials
and also run this in terminal:
pip install oauth2client
The code will look something like this:
from oauth2client.service_account import ServiceAccountCredentials
import gspread
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
sheet = client.open_by_url("spreadsheetlink.com")
worksheet = sheet.get_worksheet(0)
Also make sure that you share the client_email with editing access (you will see what I mean after reading the articles).
If you have any questions, feel free to reply to me.

Related

Asana Python Connector - Get dataframe of all tasks for all projects

I am trying to get the information of all the tasks for all the projects in a certain workspace in python so i get generate some graphs. I am struggling to get any information on how to achieve this online or on https://github.com/Asana/python-asana. This is as far as i got.
import asana
personal_access_token = 'xxxxxxxxxxxx'
client = asana.Client.access_token(personal_access_token)
I would really appreciate some help on this.
Use this Code in Python 3:
import asana
from oauth2client.service_account import ServiceAccountCredentials
client = asana.Client.basic_auth('0/xxxxxxxxxxxxxxxxxxxxx')
me = client.users.me()
For Your Workspace Details:
workspace_id = me['workspaces'][0]['gid']
To find all projects name in workspace:
proj= client.projects.find_all({'workspace': a_workspace_id,"opt_fields":{"this.name"}})

Integrating python-decouple with PRAW?

I've been trying to see if I can use python-decouple to place my bot credentials on a separate .env file.
Auth method is basically right off the praw doc:
reddit = praw.Reddit(
client_id=config('CLIENT_ID'),
client_secret=config('CLIENT_SECRET'),
password=config('PASSWORD'),
user_agent=config('USER_AGENT'),
username=config('USERNAME')
)
However, whenever I try it, it seems to return an 403 auth error. I work my way back, replacing the decouple configs with strings of the actual details, but it doesn't seem to follow through, and the errors that occur seem random depending on what and when things I take out.
Is this a problem with how decouple functions?
Thanks.
I've been trying to see if I can use python-decouple to place my bot credentials on a separate .env file.
Why not use a praw.ini file? This is documented here in PRAW documentation. It's a format for storing Reddit credentials in a separate file from your code. For example, a praw.ini file may look like:
[bot1]
client_id=Y4PJOclpDQy3xZ
client_secret=UkGLTe6oqsMk5nHCJTHLrwgvHpr
password=pni9ubeht4wd50gk
username=fakebot1
[bot2]
client_id=6abrJJdcIqbclb
client_secret=Kcn6Bj8CClyu4FjVO77MYlTynfj
password=mi1ky2qzpiq8s59j
username=fakebot2
You then use specific credentials in your code like so:
import praw
reddit = praw.Reddit('bot2', user_agent='myBot v0.1')
print('Logged in as', reddit.user.me())
I think this is the best solution for working with PRAW credentials.
However, if you really want to do it with python-decouple, here's a working example:
Contents of file .env:
username=k8IA
password=REDACTED
client_id=REDACTED
client_secret=REDACTED
Contents of file connect.py:
import praw
from decouple import config
reddit = praw.Reddit(username=config('username'),
password=config('password'),
client_id=config('client_id'),
client_secret=config('client_secret'),
user_agent='myBot v0.1')
print('Logged in as', reddit.user.me())
Output when running python3 connect.py:
Logged in as k8IA

OAuth request_token for Etsy problem with URL construction

I am trying to create an app to access Etsy api using python3, I am testing my very basic code in idle3, I need to get an oauth token, I have looked at the etsy documentation here but all is described for php.
below is my code in idle3 (I have changed my keys);
>>>payload = { 'api_key' : 'pvhkg9y4e7', 'shared_secret' : 'ib5msimmo', 'scope' : 'transactions_r,listings_w,billing_r,treasury_r'}
>>> url = "https://openapi.etsy.com/v2/oauth/request_token"
>>> r = requests.get(url, params=payload)
>>> print(r.url)
https://openapi.etsy.com/v2/oauth/request_token?api_key=pvhkg9y4e7&scope=transactions_r%2Clistings_w%2Cbilling_r%2Ctreasury_r&shared_secret=ib5msimmo
>>> r.text
>>>'oauth_problem=parameter_absent&oauth_parameters_absent=oauth_consumer_key%26oauth_signature%26oauth_signature_method%26oauth_nonce%26oauth_timestamp
I need help in creating the correct URL I think I need to change my payload wording to oauth_consumer_key, oauth_signature, but I do not understand how to include oauth_signature_method (I am using request.get) or the oauth_timestamp, and I don't know what oauth_nonce is?
I intend to incorporate the whole into a flask app, so I have looked at flask_oauth here but I am not sure if this will give me the timestamp and nonce.
All advice greatly appreciated, I am following the flask tutorial by miguel grinberg, I need one like that for my etsy app! any suggestions
I also tried request_oauthlib but got this;
>>> from requests_oauthlib import OAuth1
>>>Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
from requests_oauthlib import OAuth1
ImportError: No module named 'requests_oauthlib'
Regards
Paul
I wrote to etsy developers, who came back with some php code, I know very little python but no PHP,
So I went back to searching google, and went back to here and used the following code;
import requests
from requests_oauthlib import OAuth1
request_token_url = 'https://openapi.etsy.com/v2/oauth/request_token?scope=transactions_r&listings_w&billing_r&treasury_r'
consumer_key = 'api_key'
consumer_secret = 'secret_key'
oauth = OAuth1(consumer_key, client_secret=consumer_secret)
r = requests.post(url=request_token_url, auth=oauth)
r.content
login_url=https%6%3fthe%26address%26you%2fwant%34goodluck
and it worked!!!!!! I am so happpppy!!!
If you get any other noobs like me perhaps they can be help them with this code.
In terminal I created a virtualenv, I then pip installed requests and request_oauthlib, then in python shell executed the above script.
regards paul

Writing Pandas DataFrames to Google sheets: no such file or directory .oauth/drive.json

I've been trying to find a way to read and write data between Pandas and Google sheets for a while now. I found the library df2gspread which seems perfect for the job. Been spending a while now trying to get it to work.
As instructed, I used the Google API console to create my client secrets file and saved it as ~/.gdrive_private. Now, I'm trying to download the contents of a Google spreadsheet as follows:
workbook = [local filepath to workbook in Google Drive folder]
df = g2d.download(workbook, 'Sheet1', col_names = True, row_names = True)
When I run this, it is successfully opening a browser window asking to give my app access to my Google sheets. However, when I click allow, an iPython error is coming up:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/samlilienfeld/.oauth/drive.json'
What is this file supposed to contain? I've tried creating the folder and including my client secrets again there as drive.json, but this does not work.
I did a work around for the time being by passing a pre-authenticated credential file to the g2d call.
I made a gist here (for Python2x but should work for 3x) to save the credential file by passing the secret file (basically ~/.gdrive_private) and the resulting authenticated credential filename to save.
Use the above gist in an standalone script with appropriate filenames and run it from a terminal console. A browser window will open to perform the OAuth authentication via Google, and should give you a token which you can copy paste into the terminal prompt. Here's a quick example:
from gdrive_creds import create_creds
# Copy Paste whatever shows up in the browser in the console.
create_creds('./.gdrive_private', './authenticated_creds')
You can then use the file to authenticate for df2gspread calls.
Once you create the cred file using the gist method, try something like this to get access to your GDrive:
from oauth2client.file import Storage
from df2gspread import gspread2df as g2d
# Read the cred file
creds = Storage('./authenticated_creds').get()
# Pass it to g2df (Trimmed for brevity)
workbook = [local filepath to workbook in Google Drive folder]
df = g2d.download(workbook, 'Sheet1', col_names = True, credentials=creds)
df.head()
This worked for me.
Here the two functioning ways as of 2019:
1.DateFrame data to Google sheet:
#Import libraries
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
# Connection to googlesheet
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# From dataframe to google sheet
from df2gspread import df2gspread as d2g
# Configure the connection
scope = ['https://spreadsheets.google.com/feeds']
# Add the JSON file you downloaded from Google Cloud to your working directory
# the JSON file in this case is called 'service_account_gs.json' you can rename as you wish
credentials =ServiceAccountCredentials.from_json_keyfile_name('service_account_gs.json',
scope
)
# Authorise your Notebook with credentials just provided above
gc = gspread.authorize(credentials)
# The spreadsheet ID, you see it in the URL path of your google sheet
spreadsheet_key = '1yr6LwGQzdNnaonn....'
# Create the dataframe within your notebook
df = pd.DataFrame({'number': [1,2,3],'letter': ['a','b','c']})
# Set the sheet name you want to upload data to and the start cell where the upload data begins
wks_name = 'Sheet1'
cell_of_start_df = 'A1'
# upload the dataframe
d2g.upload(df,
spreadsheet_key,
wks_name,
credentials=credentials,
col_names=True,
row_names=False,
start_cell = cell_of_start_df,
clean=False)
print ('Successfully updated')
2.Google sheet to DataFrame
from df2gspread import gspread2df as g2d
df = g2d.download(gfile='1yr6LwGQzdNnaonn....',
credentials=credentials,
col_names=True,
row_names=False)
df
It seems like this issue was because /User/***/.oauth folder wasn't created automatically by oauth2client package (e.g. issue). One of possible solutions is to create this folder manually or you can update df2gspread, issue should be fixed in last version.

Twython basic, helpm please , can it get easier than this?

This script is giving ma a 500 Error, any ideas?
I am taking the script from a page from python samples and also using the path given to me by my hosting company (and I know it works because I have another script that does work.)
The file has 755 permissions as well as it's directory:
#!/home3/master/bin/python
import sys
sys.path.insert(1,'/home3/master/lib/python2.6/site-packages')
from twython import Twython
twitter = Twython()
trends = twitter.getCurrentTrends()
print trends
There are two problems with this code. The first is you have not included any OAuth data, so the Twitter API will reject whatever you send. The second is there is no getCurrentTrends() attribute in Twython. Did you mean get_available_trends or get_closest_trends?

Resources