Error using OAuth2 to connect to dropbox in Python - python-2.7

On my Raspberry Pi running raspbian jessie I tried to go through the OAuth2 flow to connect a program to my dropbox using the dropbox SDK for Python which I installed via pip.
For a test, I copied the code from the documentation (and defined the app-key and secret, of course):
from dropbox import DropboxOAuth2FlowNoRedirect
auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET)
authorize_url = auth_flow.start()
print "1. Go to: " + authorize_url
print "2. Click \"Allow\" (you might have to log in first)."
print "3. Copy the authorization code."
auth_code = raw_input("Enter the authorization code here: ").strip()
try:
access_token, user_id = auth_flow.finish(auth_code)
except Exception, e:
print('Error: %s' % (e,))
return
dbx = Dropbox(access_token)
I was able to get the URL and to click allow. When I then entered the authorization code however, it printed the following error:
Error: 'str' object has no attribute 'copy'
Using format_exc from the traceback-module, I got the following information:
Traceback (most recent call last):
File "test.py", line 18, in <module>
access_token, user_id = auth_flow.finish(auth_code)
File "/usr/local/lib/python2.7/dist-packages/dropbox/oauth.py", line 180, in finish
return self._finish(code, None)
File "/usr/local/lib/python2.7/dist-packages/dropbox/oauth.py", line 50, in _finish
url = self.build_url(Dropbox.HOST_API, '/oauth2/token')
File "/usr/local/lib/python2.7/dist-packages/dropbox/oauth.py", line 111, in build_url
return "https://%s%s" % (self._host, self.build_path(target, params))
File "/usr/local/lib/python2.7/dist-packages/dropbox/oauth.py", line 89, in build_path
params = params.copy()
AttributeError: 'str' object has no attribute 'copy'
It seems the build_path method expects a dict 'params' and receives a string instead. Any ideas?

Thanks to smarx for his comment. The error is a known issue and will be fixed in version 3.42 of the SDK. source

Related

How to take multiple screenshots through Selenium in Python?

GECKODRIVER_PATH = 'F:/geckodriver.exe'
firefox_options = Options()
firefox_options .add_argument("-headless")
driver = webdriver.Firefox(executable_path=CHROMEDRIVER_PATH, firefox_options = firefox_options )
test = []
test.append('http://google.com')
test.append('http://stackoverflow.com')
for x in test:
print x
driver.get(x)
driver.set_page_load_timeout(20)
filename = str(x)+'.png'
driver.save_screenshot( filename )
driver.close()
Now, how can I take multiple screenshots and save them in the different filename? As you can see I am trying to save the filename according to domain URL but failed.
See the error below:
http://google.com
http://card.com
Traceback (most recent call last):
File "F:\AutoRecon-master\test.py", line 125, in <module>
driver.get(x)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 326, in get
self.execute(Command.GET, {'url': url})
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Tried to run command without establishing a connection
Can anyone please tell me what is the exact problem is? Will be a big help.
Try to move driver.close() out of loop:
for x in test:
print x
driver.get(x)
driver.set_page_load_timeout(20)
filename = str(x)+'.png'
driver.save_screenshot( filename )
driver.close()
Also note that x is already a string, so there is no need in str(x)
P.S. I'm not sure that http://stackoverflow.com.png filename is acceptable, you might need to use:
filename = x.split('//')[-1] + '.png'
Tried to run command without establishing a connection
you are closing the browser within your for loop... so the 2nd time through the loop it fails with the error above (since the browser is closed, the connection to geckodriver has already been terminated).
other issues:
you are setting the page_load_timeout after you have already fetched the page, so it is not doing anything useful.
using CHROMEDRIVER_PATH as the name for Geckodriver is just confusing. Chromedriver is not used at all here.

How to fix this python code that performs login to website

am novice in python.Extracted below code to login to website from an online post, but getting error.
Please help to fix it and an explanation will help me
import requests
with requests.Session() as c:
EMAIL = 'noob.python#gmail.com'
PASSWORD = 'Dabc#123'
URL = 'https://www.linkedin.com/'
c.get(URL)
token = c.cookies['CsrfParam']
# This is the form data that the page sends when logging in
login_data = {loginCsrfParam:token, session_key:EMAIL, session_password:PASSWORD}
# Authenticate
r = c.post(URL, data=login_data)
# Try accessing a page that requires you to be logged in
r = c.get('https://www.linkedin.com/feed/')
print r.content
Am stuck with below Error:
C:\Python27>python website.py
Traceback (most recent call last):
File "website.py", line 8, in <module>
token = c.cookies['CsrfParam']
File "C:\Python27\lib\site-packages\requests\cookies.py", line 329, in __getitem__
return self._find_no_duplicates(name)
File "C:\Python27\lib\site-packages\requests\cookies.py", line 400, in _find_no_duplicates
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='CsrfParam', domain=None, path=None"
The reason you're getting the error is that you're calling a value from a list which is empty. To call the first item in the list you say list[0]. In this case the list you're calling is empty so the first value doesn't exist hence the error.
I've ran your code and there is no #id value of 'recaptcha-token' which is why the code is returning an empty list. The only place a recaptcha token is needed is for signing up so I would suggest trying to log in without creating the authenticity_token.

Error while accessing Google Contacts Groups by API

I want get list of all groups in my contacts. I use that code:
import gdata.gauth
import gdata.contacts.client
token = gdata.gauth.OAuth2Token(client_id = "***.apps.googleusercontent.com",
client_secret = "***",
scope = "https://www.google.com/m8/feeds/",
user_agent = "GC")
gd_client = gdata.contacts.client.ContactsClient(source = 'GCv0.1')
gd_client = token.authorize(gd_client)
gd_client.GetGroups()
But got error:
Traceback (most recent call last):
File "F:/Yandex/Sites/GoogleContacts/cli_contacts.py", line 27, in <module>
gd_client.GetGroups()
File "C:\Users\Ishayahu\27Gdata\lib\site-packages\gdata\contacts\client.py", line 218, in get_groups
return self.get_feed(uri, desired_class=desired_class, auth_token=auth_token, **kwargs)
File "C:\Users\Ishayahu\27Gdata\lib\site-packages\gdata\client.py", line 640, in get_feed
**kwargs)
File "C:\Users\Ishayahu\27Gdata\lib\site-packages\gdata\client.py", line 319, in request
RequestError)
gdata.client.RequestError: Server responded with: 400,
enter code here
I have no idea what a reason and I can't find any clue how to solve it.
UPD: It looks like I should somehow put acess_token or refresh_token into OAuth2Token, but I can't understand how
so it send headers
{'GData-Version': '3', 'Authorization': 'Bearer None', 'User-Agent': 'gdata-py/2.0.17'}
UPD2: by the way, if I test in in OAuth2Playground, it shows me a page with request access to my contacts. That script doesn't ask for it. Maybe that's the problem? How can I change it? I thought, it connect with url_redirect, but I can't uderstand, how to use it
UPD3: I was right: if I add access_token, which I get manualy from Playground, all works. But how should I get it in script?!

Exception when trying to create bigquery table via python API

I'm working on an app that will stream events into BQ. Since Streamed Inserts require the table to pre-exist, I'm running the following code to check if the table exists, and then to create it if it doesn't:
TABLE_ID = "data" + single_date.strftime("%Y%m%d")
exists = False;
request = bigquery.tables().list(projectId=PROJECT_ID,
datasetId=DATASET_ID)
response = request.execute()
while response is not None:
for t in response.get('tables', []):
if t['tableReference']['tableId'] == TABLE_ID:
exists = True
break
request = bigquery.tables().list_next(request, response)
if request is None:
break
if not exists:
print("Creating Table " + TABLE_ID)
dataset_ref = {'datasetId': DATASET_ID,
'projectId': PROJECT_ID}
table_ref = {'tableId': TABLE_ID,
'datasetId': DATASET_ID,
'projectId': PROJECT_ID}
schema_ref = SCHEMA
table = {'tableReference': table_ref,
'schema': schema_ref}
table = bigquery.tables().insert(body=table, **dataset_ref).execute(http)
I'm running python 2.7, and have installed the google client API through PIP.
When I try to run the script, I get the following error:
No handlers could be found for logger "oauth2client.util"
Traceback (most recent call last):
File "do_hourly.py", line 158, in <module>
main()
File "do_hourly.py", line 101, in main
body=table, **dataset_ref).execute(http)
File "build/bdist.linux-x86_64/egg/oauth2client/util.py", line 142, in positional_wrapper
File "/usr/lib/python2.7/site-packages/googleapiclient/http.py", line 721, in execute
resp, content = http.request(str(self.uri), method=str(self.method),
AttributeError: 'module' object has no attribute 'request'
I tried researching the issue, but all I could find was info about confusing between urllib, urllib2 and Python 2.7 / 3.
I'm not quite sure how to continue with this, and will appreciate all help.
Thanks!
Figured out that the issue was in the following line, which I took from another SO thread:
table = bigquery.tables().insert(body=table, **dataset_ref).execute(http)
Once I removed the "http" variable, which doesn't exist in my scope, the exception dissappeared

cant get the facebook-tornado connection

i've a problem, am a beginer and i try to make a simple asynchronous program that posts to facebook, i use the tornado example and the tornado-facebook-sdk, here is the code:
class MainHandler(BaseHandler, tornado.auth.FacebookGraphMixin):
#tornado.web.authenticated
#tornado.web.asynchronous
def get(self):
self.facebook_request("/me/home", self.print_callback, access_token=self.current_user["access_token"])
a = self.current_user["access_token"]
#print a
def print_callback(data):
print data
ioloop.stop()
graph.get_object('/facebook', callback=print_callback)
and i get this error:
TypeError: print_callback() takes exactly 1 argument (2 given)
because i want to understand this example to get the token, and then use the example:
def callback(response):
# ...
graph.put_object('me', 'feed', message="Maoe!!", callback=callback)
to write something on my facebook's wall, i did it with the synchronous library, but sadly this is blocking!
UPDATE: still getting and error:
class MainHandler(BaseHandler, tornado.auth.FacebookGraphMixin):
#tornado.web.authenticated
#tornado.web.asynchronous
def get(self):
self.facebook_request("/me/home", self.print_callback, access_token=self.current_user["access_token"])
a = self.current_user["access_token"]
print a
def print_callback(self, data):
graph.post_wall(self, "heloooooooo")
and got this error:
[E 121009 14:28:47 web:1108] Uncaught exception GET / (::1)
HTTPRequest(.....)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\tornado-2.4.post1-py2.7.egg\tornado\web.py", line 1043, in _stack_context_handle_exception
raise_exc_info((type, value, traceback))
File "C:\Python27\lib\site-packages\tornado-2.4.post1 py2.7.egg\tornado\stack_context.py", line 237, in _nested
yield vars
File "C:\Python27\lib\site-packages\tornado-2.4.post1-py2.7.egg\tornado\stack_context.py", line 210, in wrapped
callback(*args, **kwargs)
File "C:\Python27\lib\site-packages\tornado-2.4.post1-py2.7.egg\tornado\gen.py", line 405, in inner self.set_result(key, result)
File "C:\Python27\lib\site-packages\tornado-2.4.post1-py2.7.egg\tornado\gen.py", line 335, in set_result
self.run()
File "C:\Python27\lib\site-packages\tornado-2.4.post1-py2.7.egg\tornado\gen.py", line 365, in run
yielded = self.gen.send(next)
File "build\bdist.win-amd64\egg\facebook\graphapi.py", line 129, in _make_request
raise GraphAPIError(data)
GraphAPIError: (#200) This API call requires a valid app_id.
and when i go to Facebook, i see that it's a valide key that i'm using, i even use the generated Token (here the a variable), and pasting it to Api Debug, and i got everything works fine:
Valid : True
Origin : Web
Scopes : create_note photo_upload publish_actions publish_stream read_stream share_item status_update video_upload
Add self to print_callback.
def print_callback(self, data):
print data
ioloop.stop()
graph.get_object('/facebook', callback=print_callback)