I use python and this is my code
myUser = 'username'
myServer = 'http://api.url.net', "{\"orga\":\"monorga\",\"coupon\":\"moncoupon\"}"
myPass = 'pass'
authString = base64.encodestring('%s:%s' % (myUser, myPass))
headers = {'Authorization':"Basic %s" % authString}
req = urllib2.Request(myServer, None, headers)
openedUrl = urllib2.urlopen(req)
url = url.strip()
AttributeError: 'tuple' object has no attribute 'strip'
Please help me
When you write url = 'https://api.url.net', "{\"orga\":\"monorga\",\"coupon\":\"moncoupon\"}", basically you're just creating a tuple of two elements ('https://api.url.net' and "{\"orga\":\"monorga\",\"coupon\":\"moncoupon\"}"), and assigning a reference to this tuple to the url variable. This is due to the fact that, in python, there is not always the need to write the parenthesis of a tuple: a = 1, 2 for example.
Thus, url is now a tuple. Also, a tuple does not have a strip method, so you can't call url.strip.
To call strip on url, you must first convert it to a string.
I found this question whilst encountering this error message.
In my case, the problem was that I had an errant trailing comma on a line declaring a string, like so:
x = "my string",
x is therefore, I think quite strangely, a tuple of length one. First and only element is "my string".
This strikes me as an easy and confusing error to make, so I thought I'd put this answer here.
Related
I have used this function before and it worked perfectly. However, I may have accidentally changed something and it now returns the error:
TypeError: 'module' object is not callable
For the line:
bom = botometer.botometer(wait_on_ratelimit=True,rapidapi_key=rapidapi_key,**twitter_app_auth)
The full code I use is:
def bot_detector(account,lang='universal'):
consumer_secret = deleter(open('consumer_sxcrxt.txt','r').rxad(),'\n')
consumer_key = deleter(open('api.txt','r').read(),'\n')
twitter_app_auth = {'consumer_key': consumer_key,'consumer_secret': consumer_secret}
rapidapi_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
bom = botometer.botometer(wait_on_ratelimit=True,rapidapi_key=rapidapi_key,**twitter_app_auth)
result = bom.check_account(account)
score = result['cap'][lang]
return score
print(bot_detector(1.25948029617448E+018))
Notes:
'deleter' is just a way for me to remove the line separator on the files containing my api keys.
I just checked and my twitter api keys are working.
If I put botometer.Botometer as it says on the documentation, I get the error:
AttributeError: module 'botometer' has no attribute 'Botometer'
(I think they made a typo on the documentation.)
Documentation:
https://libraries.io/pypi/botometer
I named my file 'botometer.py' and thus python was looking in the wrong place.
my project is to extract the contents of all my salesforce tables, including the custom ones. To do this, I need to know the names of the columns (fields), since SOQL does not support "SELECT * from TABLENAME".
With simple-salesforce, I know that the following works:
sf = Salesforce(username='foo#bar.com', password='abcd', security_token='ZCdsdPdE4eI2DZMl5gwCFIGEFU')
field_data = sf.Contact.describe()["fields"]
But my problem is that I need to parameterize the "Contact" string in the actual method call above, so that I can call this method for objects that I do not know the names of (ie not defined in standard salesforce). For example I need to do:
field_data = sf.CustomTableName.describe()["fields"]
When I try and use the SFType class:
contact = SFType('Contact',sf.sessionid,sf.sf_instance)
f = contact.describe()
I get this error:
Traceback (most recent call last):
File "./simple-example.py", line 13, in <module>
f = contact.describe()["fields"]
File "/Library/Python/2.7/site-packages/simple_salesforce/api.py", line 430, in describe
result = self._call_salesforce('GET', self.base_url + 'describe')
File "/Library/Python/2.7/site-packages/simple_salesforce/api.py", line 570, in _call_salesforce
'Authorization': 'Bearer ' + self.session_id,
TypeError: cannot concatenate 'str' and 'SFType' objects
Thanks in advance for any advice.
If you look in the source code for simple-salesforce (as of 2015-11-12) you'll see that in the init() of Salesforce() we set the session to self.session_id and instance to self.sf_instance
In your case, you're using sf.sessionid, and because simple-salesforce is setup to return a SFType() object whenever a method or property does not exist on Salesforce() (and sessionid does not exist on Salesforce()) you're actually inserting a SFType() object into the init of your SFType()
SFType.__init__() doesn't do any form of validation to confirm you're passing in strings as arguments, so the error you're getting is from simple-salesforce trying to use the SFType() object you're passing in as a string.
Try this code:
contact = SFType('Contact', sf.session_id, sf.sf_instance)
f = contact.describe()
I ran into the same issue and seemed to have fixed this by removing the protocol ("https://") from the instance_url. This is weird but seems to work for me now and I can do contact.describe()
Something like this:
contact = SFType(sf_object, session_id, instance_url.replace("https://",''))
contact.describe()
import requests
import json
s = requests.Session()
s.params["key"] = "MY_KEY"
s.params["cx"] = "MY_CX"
s.params["num"] = 1
result = s.get('https://www.googleapis.com/customsearch/v1', params={"q": "Search query"})
Everything is working fine and I do get a result back but it's JSON. What I want is one thing. Since my result only gives 1 search result, I want the link of that search result. From I've understood that link value is under the keys "item" and then "link". I've tried lots of things but I keep getting either one of these errors below.
TypeError: 'Response' object is not subscriptable
NameError: name 'json' is not defined
AttributeError: 'Response' object has no attribute 'read'
TypeError: the JSON object must be str, not 'Response'
What am i doing wrong and what's the solution?
I am trying to find a string in the headers of response after login in Wordpress script, so I tried with this find method:
import urllib, urllib2, os, sys, requests , re
....
....
req = urllib2.Request(url, urllib.urlencode(dict(data)), dict(headers))
response = urllib2.urlopen(req)
res = dict(response.headers)
res1 = 'wp-admin'
if res.find(res1) >= 0:
print 'wp-admin exist in dict(response.headers)'
and i get this error :
Traceback (most recent call last):
File "C:\Python27\wp2\wp12.py", line 29, in <module>
if res.find(res1) >= 0:
AttributeError: 'dict' object has no attribute 'find'
Is there any idea confirm that dict(headers) contain 'wp-admin' or transform the dict(headers) into text to use find function correctly?
In general, to find all items in a dict where the value contains a string:
[(key, value) for (key, value) in the_dict.items() if search_string in value]
(On python 2.x, use iteritems for efficiency.)
If you only need to know if it's there at all:
any(search_string in value for value in the_dict.values())
(On python 2.x you can use itervalues as well)
The error message is letting you know that the datatype dict doesn't have a find method available to it like other datatypes might. But the good news for you is that response.headers is already in a dictionary-like format so you can search for your "wp-admin" directly.
import urllib2
url = "http://www.google.com"
response = urllib2.urlopen(url)
for headername in response.headers:
print headername, response.headers[headername]
if "wp-admin" in response.headers:
print "header found"
It's just like this as well:
a = {"wp-admin":"value1",
"header2":"value2"}
if "wp-admin" in a:
print "Found header"
First of all, don't use str.find() to test for the presence of a substring; use in membership testing instead:
>>> 'foo' in 'there was once a foo that barred a bar'
True
>>> 'foo' in 'spam, ham and eggs'
False
To test for a substring in all values of a dictionary, loop over all values. To just test for the presence, use membership tests against each one. The any() function with a generator expression makes that a little more efficient by looping only enough to find a match:
if any('wp-admin' in v for v in response.headers.itervalues()):
Here dict.itervalues() yields all values in a dictionary lazily when looped over.
However, with request headers I'd normally expect the value to show up in just one header; you'd be better of looking for that specific header:
if 'wp-admin' in response.headers.get('set-cookie', ''):
where the .get() method will return '' if the Set-Cookie header is not present.
This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed 29 days ago.
In Python I'm getting an error:
Exception: (<type 'exceptions.AttributeError'>,
AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)
Given python code:
def getEntries (self, sub):
url = 'http://www.reddit.com/'
if (sub != ''):
url += 'r/' + sub
request = urllib2.Request (url +
'.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
response = urllib2.urlopen (request)
jsonStr = response.read()
return json.load(jsonStr)['data']['children']
What does this error mean and what did I do to cause it?
The problem is that for json.load you should pass a file like object with a read function defined. So either you use json.load(response) or json.loads(response.read()).
Ok, this is an old thread but.
I had a same issue, my problem was I used json.load instead of json.loads
This way, json has no problem with loading any kind of dictionary.
Official documentation
json.load - Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.
json.loads - Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.
You need to open the file first. This doesn't work:
json_file = json.load('test.json')
But this works:
f = open('test.json')
json_file = json.load(f)
If you get a python error like this:
AttributeError: 'str' object has no attribute 'some_method'
You probably poisoned your object accidentally by overwriting your object with a string.
How to reproduce this error in python with a few lines of code:
#!/usr/bin/env python
import json
def foobar(json):
msg = json.loads(json)
foobar('{"batman": "yes"}')
Run it, which prints:
AttributeError: 'str' object has no attribute 'loads'
But change the name of the variablename, and it works fine:
#!/usr/bin/env python
import json
def foobar(jsonstring):
msg = json.loads(jsonstring)
foobar('{"batman": "yes"}')
This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.
AttributeError("'str' object has no attribute 'read'",)
This means exactly what it says: something tried to find a .read attribute on the object that you gave it, and you gave it an object of type str (i.e., you gave it a string).
The error occurred here:
json.load(jsonStr)['data']['children']
Well, you aren't looking for read anywhere, so it must happen in the json.load function that you called (as indicated by the full traceback). That is because json.load is trying to .read the thing that you gave it, but you gave it jsonStr, which currently names a string (which you created by calling .read on the response).
Solution: don't call .read yourself; the function will do this, and is expecting you to give it the response directly so that it can do so.
You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load), or for the entire module (try help(json)), or by checking the documentation for those functions on http://docs.python.org .
Instead of json.load() use json.loads() and it would work:
ex:
import json
from json import dumps
strinjJson = '{"event_type": "affected_element_added"}'
data = json.loads(strinjJson)
print(data)
So, don't use json.load(data.read()) use json.loads(data.read()):
def findMailOfDev(fileName):
file=open(fileName,'r')
data=file.read();
data=json.loads(data)
return data['mail']
use json.loads() function , put the s after that ... just a mistake btw i just realized after i searched error
def getEntries (self, sub):
url = 'http://www.reddit.com/'
if (sub != ''):
url += 'r/' + sub
request = urllib2.Request (url +
'.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
response = urllib2.urlopen (request)
jsonStr = response.read()
return json.loads(jsonStr)['data']['children']
try this
Open the file as a text file first
json_data = open("data.json", "r")
Now load it to dict
dict_data = json.load(json_data)
If you need to convert string to json. Then use loads() method instead of load(). load() function uses to load data from a file so used loads() to convert string to json object.
j_obj = json.loads('["label" : "data"]')