Authenticate Tableau REST API using Python 2.7 - python

I'm having a similar issue to this recently answered question: Authenticate & Embed Tableau Rest API using python 2.7
I'm using the same code, but getting a different error. Confirmed that I am calling the correct API version for my Tableau server version.
from urllib2 import urlopen, Request
import xml.etree.ElementTree as ET # for parsing XML responses
server_name = "http://dashboard.myorg.org"
user_name = "abc"
password = "abc"
site_url_id = ""
signin_url = "{server}/api/2.4/auth/signin".format(server=server_name)
request_xml = ET.Element('tsRequest')
credentials = ET.SubElement(request_xml, 'credentials',
name=user_name, password=password)
site_element = ET.SubElement(credentials, 'site',
contentUrl=site_url_id)
request_data = ET.tostring(request_xml)
req = Request(signin_url, data=request_data)
req = urlopen(req)
server_response = req.read
response_xml = ET.fromstring(server_response)
token = response_xml.find('.//t:credentials',
namespaces={'t': "http://tableau.com/api"}).attrib['token']
site_id = response_xml.find('.//t:site',
namespaces={'t': "http://tableau.com/api"}).attrib['id']
print('Sign in successful!')
print('/tToken: {token}'.format(token=token))
print('/tSite ID: {site_id}'.format(site_id=site_id))
headers = {'X-tableau-auth': token}
signout_url = "{server}/api/2.4/auth/signout".format(server=server_name)
req = Request(signout_url, headers=headers, data=b'')
req = urlopen(req)
print('Sign out successful!')
My error is:
Traceback (most recent call last):
File "api_call.py", line 20, in <module>
response_xml = ET.fromstring(server_response)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1311, in XML
parser.feed(text)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1311, in feed
self._parser.Parse(data, 0)
TypeError: Parse() argument 1 must be string or read-only buffer, not instancemethod

As mentioned by #mzjn, issue is resolved by updating
server_response = req.read
to
server_response = req.read()

Related

Authorisation Error while trying to use Reddit Api

I am trying to connect with Reddit API to get data for analysis, but am meeting a roadblock of not being able to retrieve the "access_token". Below is the code I have written, I really need the solution to this problem, below is the code
client_id = 'r7L-BcPLzoXkPl4*****'
secret = 'E1uNURdvTwu6kT09ertNNqo5*****'
import requests
auth = requests.auth.HTTPBasicAuth(client_id, secret)
with open('password.txt', 'r') as fp:
pwd = fp.read()
data = {'grant_type': 'password',
'username': 'josehope',
'password': pwd}
headers = {'User-Agent': 'Hitan/0.0.1'}
res = requests.post('https://www.reddit.com/api/v1/access_token',
auth=auth, data=data, headers=headers)
res
output ---> <Response [200]>
token = res.json()["access_token"]
This is the error I get after running the above code
KeyError Traceback (most recent call last)
<ipython-input-18-e2a3bbd5aa7e> in <module>
----> 1 token = res.json()["access_token"]
KeyError: 'access_token'

In python, how can we connect to API using a certificate, subscription key?

I am trying to connect to an api for which I was provided with link, certificate(.p12) and subscription key.
Having some issue while giving the certificate details. I am trying in the following 2 ways:
1.
import json
from requests_pkcs12 import get,post
url = 'https://....'
pkcs12_filename = '<certificate file path>'
pkcs12_password = '<certificate password>'
headers = {
# Request headers
'Subscription-Key': '<subscription key>',}
response = post(url, headers=headers, verify=False, pkcs12_filename=pkcs12_filename,pkcs12_password=pkcs12_password)
print(response.status_code)
import http.client, urllib.request, urllib.parse, urllib.error, base64
#file = "<certificate path>"
headers = {
'Subscription-Key': '<subscriptionkey>',
#'cert' : crypto.load_pkcs12(open(file, 'rb').read(), "<password>").get_certificate(),
'file' : '<certificate path>',
'password':'<certificate password>',}
params = urllib.parse.urlencode({
})
conn = http.client.HTTPSConnection('<api main link>')
conn.request("GET", "<api remaining link>" , params, headers)
response = conn.getresponse()
data = response.read()
print("Status: {} and reason: {}".format(response.status, response.reason))
conn.close()
I am new to API concept. Will someone help me over this?
Refered to this link: How to use .p12 certificate to authenticate rest api
But didn't get what i need to put in data variable

Log into Robinhood using Python Requests Module

I am trying to log into the Robinhood API using:
import requests
def login():
u = "myusername"
p = "mypassword"
url = "https://api.robinhood.com/api-token-auth/"
r = requests.get(url, username=u, password=p)
#r = requests.get(url)
return r.text
print login()
I have a way to do it in Curl which is:
'curl -v https://api.robinhood.com/api-token-auth/ -H "Accept: application/json" -d "username='+username+'&password='+password+'"'
When using Python-requests I get the following error:
Traceback (most recent call last):
File "rhood.py", line 12, in <module>
print login()
File "rhood.py", line 8, in login
r = requests.get(url, username=u, password=p)
File "C:\Python27\Lib\site-packages\requests\api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "C:\Python27\Lib\site-packages\requests\api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
TypeError: request() got an unexpected keyword argument 'username'
You need to create a dictionary containing the parameters you wish to send with the request (see data in the code below). Then include the dictionary in your request by using the json parameter.
Also note, Robinhood API documentation seems to suggest a POST request is required, as opposed to a GET request. Therefore, the code below uses requests.post(...).
import requests
def login():
u = "myusername"
p = "mypassword"
url = "https://api.robinhood.com/api-token-auth/"
data = {"username": u, "password": p}
r = requests.post(url, json=data)
return r.text
print login()
Check out the authentication modules in the requests library
http://docs.python-requests.org/en/master/user/authentication/

Authenticate to linkedin

I am trying to write a code that get some user's linkedin profile and just print it
this is my code
from linkedin import linkedin
CONSUMER_KEY = "XXXXX"
CONSUMER_SECRET = "XXXXX"
RETURN_URL = r"http://localhost:8000"
authentication = linkedin.LinkedInAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
application = linkedin.LinkedInApplication(authentication)
a = application.get_profile(member_url=my_url)
print(a)
I get the following error
Traceback (most recent call last):
File "C:/Users/Linkedin/main.py", line 28, in <module>
a = application.get_profile(member_url=my_url)
File "C:\Python34\lib\site-packages\python_linkedin-4.2-py3.4.egg\linkedin\linkedin.py", line 189, in get_profile
response = self.make_request('GET', url, params=params, headers=headers)
File "C:\Python34\lib\site-packages\python_linkedin-4.2-py3.4.egg\linkedin\linkedin.py", line 169, in make_request
params.update({'oauth2_access_token': self.authentication.token.access_token})
AttributeError: 'NoneType' object has no attribute 'access_token'
What do I do wrong?
Not tested. Try this
As per the documentation. Access token must be generated to grand access to the application.
authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())
application = linkedin.LinkedInApplication(token=authentication.get_access_token())
print authentication.authorization_url
When you grant access to the application, you will be redirected to the return url with the following query strings appended to your RETURN_URL:
"http://localhost:8000/?code=AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8&state=ea34a04b91c72863c82878d2b8f1836c"
Copy the code manually and set like
authentication.authorization_code = 'AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8'
authentication.get_access_token() #AQTFtPILQkJzXHrHtyQ0rjLe3W0I
application = linkedin.LinkedInApplication(token='AQTFtPILQkJzXHrHtyQ0rjLe3W0I')

Python Dropbox API error: 'The provided token does not allow this operation' [duplicate]

I'm following the tutorial here
So far so good but the upload example give me errors. The code:
from dropbox import client, rest, session
f = open('txt2.txt') # upload a file
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
The error:
Traceback (most recent call last):
File "dropbox_ul.py", line 4, in <module>
response = client.put_file('/magnum-opus.txt', f)
AttributeError: 'module' object has no attribute 'put_file'
Where did I go wrong?
EDIT: The new code I'm trying. This is actually from the dropbox developer website. As I stated earlier, I did go through the authentication and setup:
# Include the Dropbox SDK libraries
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
APP_KEY = 'iqxjea6s7ctxv9j'
APP_SECRET = 'npac0nca3p3ct9f'
# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('txt2.txt')
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
folder_metadata = client.metadata('/')
print "metadata:", folder_metadata
f, metadata = client.get_file_and_metadata('/magnum-opus.txt',rev='362e2029684fe')
out = open('magnum-opus.txt', 'w')
out.write(f)
print(metadata)
and the error:
url: https://www.dropbox.com/1/oauth/authorize?oauth_token=jqbasca63c0a84m
Please authorize in the browser. After you're done, press enter.
linked account: {'referral_link': 'https://www.dropbox.com/referrals/NTMxMzM4NjY5', 'display_name': 'Greg Lorincz', 'uid': 3133866, 'country': 'GB', 'quota_info': {'shared': 78211, 'quota': 28185722880, 'normal': 468671581}, 'email': 'alkopop79#gmail.com'}
Traceback (most recent call last):
File "dropb.py", line 28, in <module>
response = client.put_file('/magnum-opus.txt', f)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/client.py", line 149, in put_file
return RESTClient.PUT(url, file_obj, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 146, in PUT
return cls.request("PUT", url, body=body, headers=headers, raw_response=raw_response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 113, in request
raise ErrorResponse(r)
dropbox.rest.ErrorResponse: [403] 'The provided token does not allow this operation'
You haven't initialized the client object. Refer to the tutorial again and you'll see this:
client = client.DropboxClient(sess)
The sess object must also be initialized before calling the client module's DropboxClient method:
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
You should have all the required parameters (i.e., APP_KEY, APP_SECRET, ACCESS_TYPE) assigned to you when you register your application.
I followed the edited code of yours and things worked out perfectly.
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
app_key = 'enter-your-app_key'
app_secret = 'enter-your-app_secret'
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(app_key, app_secret, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('/home/anurag/Documents/sayan.odt')
response = client.put_file('/sayan.odt', f)
print "uploaded:", response
Notice the response and file location on your system, in your code that doesn't matches.
Thanks.

Categories

Resources