AttributeError: 'str' object has no attribute 'sign' - python

When I run my python script, it gives me the following error. Not sure how to resolve it. I think so either the problem is in the version of python, I am using python 3.6 or It could be some packages not included. Please see the included image for error.
Thanks.
Error
Code:
f = open('c:\ExamCreator\My Project-9352ed298182.json')
key = f.read()
f.close()
credentials = ServiceAccountCredentials(
'CLIENT_EMAIL', key,
scope=
'https://www.googleapis.com/auth/admin.directory.user',
sub='amankahlon#test.grasslands.ab.ca'
)
http = httplib2.Http()
http = credentials.authorize(http)
userinfo = {
'primaryEmail': 'test1#test.grasslands.ab.ca',
'name': {
'givenName':'John','familyName':'Smith'
},
'password': 'Hello1'
}
service = build("admin", "directory_v1", http=http)
service.users().insert(body=userinfo).execute()

It appears that signer is being interpreted as a string, which inherently is just...a string. Not a dict or a list, both of which have attrs. Please post the function that is throwing this error. Also, this SO question and answer may be relevant to your interests.

Related

Amazon Seller Central - SP-API - Create a feed document - InvalidInput

Trying to create feed document (here ) and I'm getting InvalidInput error code.
Authentication works well (I tried other endpoints and it works) so I think headers are not the issue.
Here is my sample code:
endpoint = 'https://sellingpartnerapi-eu.amazon.com/feeds/2020-09-04/documents'
body = {
"contentType": "text/tab-separated-values; charset=UTF-8"
}
resp = requests.post(
endpoint,
auth=self.amazon_auth.auth,
headers=self.amazon_auth.headers,
json=body
)
return resp
Response code:
{'errors': [{'code': 'InvalidInput',
'message': 'Invalid Input',
'details': ''}]}
I was also trying to use different contentType and charset (like text/plain) but I receive same error code!
This is first step of Submit feed tutorial.
I'm trying to create feed so I can get cartonIds to download labels for a shipment I created over Amazon Seller Central.
Any hint, help is more than welcome!
Thanks!
I solved this issue by:
requests.post(data=json.dumps(body))
Also make sure you pass the body for signing as well
I use RestSharp
restRequest1.AddParameter(....); gave me the same error as yours Invalid Input
but the below line gave me a response value
restRequest1.AddJsonBody(new { contentType = "text/xml; charset=UTF-8" });
It serializes obj to json format and adds it to the request body.
This code snippet in C# worked for me, i successfully uploaded a feed
My upload method:
private static bool UploadFile(byte[] encrypted, string url)
{
bool isUploaded = false;
var contentType = "text/tab-separated-values; charset=UTF-8";
var parameter = new Parameter
{
Name = contentType,
Value = encrypted,
Type = ParameterType.RequestBody
};
var restRequest = new RestRequest(Method.PUT);
restRequest.Parameters.Add(parameter);
var restClient = new RestClient(url);
var response = restClient.Execute(restRequest);
isUploaded = response.StatusCode == System.Net.HttpStatusCode.OK;
return isUploaded;
}

Python Twitch API Attribute Error problem

I received the error: AttributeError: 'set' object has no attribute 'items' while trying to get info via twitch API.
import requests
ENDPOINT = 'https://api.twitch.tv/kraken/clips/top?channel=Twitch&period=month&trending=true&limit=1'
HEAD = {
'Accept: application/vnd.twitchtv.v5+json',
'Client-ID: HIDDEN',
}
response = requests.get(url=ENDPOINT, headers=HEAD)
print (response.text)
The problem is the way you have defined your header in HEAD, you have actually created a set, not a dictionary. Revise your HEAD as follows:
HEAD = {
'Accept': 'application/vnd.twitchtv.v5+json',
'Client-ID': 'HIDDEN',
}
Not that the key and value are wrapped inside a quotation.
Dictionary:
{'key', 'value'}
What you had done was to create a Set:
{'key value'}

Insert member - code: 400, message: Missing required field: member

I have valid json that is erroring out in the google groups member API. I left the oauth stuff out but here the executed code:
groupsSettings = build('groupssettings', 'v1', credentials=creds)
file=open('file.json')
data=json.load(file)
group = (data[i]["group"])
memberEmail = (data[i]["memberEmail"])
member = json.dumps({"email": memberEmail,"role": "MEMBER"})
adminRequest=admin.members().insert(groupKey=group,body=member)
groupsResponse=groupsRequest.execute()
The error is:
{'error': {'errors': [{'domain': 'global', 'reason': 'required', 'message': 'Missing required field: member'}], 'code': 400, 'message': 'Missing required field: member'}}
400 missing required field member. My member variable IS the member. I've tried the same groupKey and body in the google API explorer and it works without issue. I'm not sure what is wrong here but on the surface it appears that this should be valid. Any insight is greatly appreciated.
For anyone interested, this was a simple mistake of trying to push serialized json. It was corrected by using deserialized json in the following manner:
encode = json.dumps({"email": memberEmail,"role": "MEMBER"})
member = json.loads(encode)

Issues while inserting data in cloudant DB

I am working a project, where in I am suppose to get some user input through web application, and send that data to cloudant DB. I am using python for the use case. Below is the sample code:
import requests
import json
dict_key ={}
key = frozenset(dict_key.items())
doc={
{
"_ID":"1",
"COORD1":"1,1",
"COORD2":"1,2",
"COORD3":"2,1",
"COORD4":"2,2",
"AREA":"1",
"ONAME":"abc",
"STYPE":"black",
"CROPNAME":"paddy",
"CROPPHASE":"initial",
"CROPSTARTDATE":"01-01-2017",
"CROPTYPE":"temp",
"CROPTITLE":"rice",
"HREADYDATE":"06-03-2017",
"CROPPRICE":"1000",
"WATERRQ":"1000",
"WATERSRC":"borewell"
}
}
auth = ('uid', 'pwd')
headers = {'Content-type': 'application/json'}
post_url = "server_IP".format(auth[0])
req = requests.put(post_url, auth=auth,headers=headers, data=json.dumps(doc))
#req = requests.get(post_url, auth=auth)
print json.dumps(req.json(), indent=1)
When I am running the code, I am getting the below error:
"WATERSRC":"borewell"
TypeError: unhashable type: 'dict'
I searched a bit, and found below stackflow link as a prospective resolution
TypeError: unhashable type: 'dict'
It says that "To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:
key = frozenset(dict_key.items())"
I have below queries:
1) I have tried using it in my code above,but I am not sure if I have used it correctly.
2) To put the data in the cloudant DB, I am using Python module "requests". In the code, I am using the below line to put the data in the DB:
req = requests.put(post_url, auth=auth,headers=headers, data=json.dumps(doc))
But I am getting below error:
"reason": "Only GET,HEAD,POST allowed"
I searched on that as well, and I found IBM BLuemix document about it as follows
https://console.ng.bluemix.net/docs/services/Cloudant/basics/index.html#cloudant-basics
As I referred the document, I can say that I am using the right option. But may be I am wrong.
If you are adding a document to the database and you know the the _id, then you need to do an HTTP POST. Here's some slightly modified code:
import requests
import json
doc={
"_id":"2",
"COORD1":"1,1",
"COORD2":"1,2",
"COORD3":"2,1",
"COORD4":"2,2",
"AREA":"1",
"ONAME":"abc",
"STYPE":"black",
"CROPNAME":"paddy",
"CROPPHASE":"initial",
"CROPSTARTDATE":"01-01-2017",
"CROPTYPE":"temp",
"CROPTITLE":"rice",
"HREADYDATE":"06-03-2017",
"CROPPRICE":"1000",
"WATERRQ":"1000",
"WATERSRC":"borewell"
}
auth = ('admin', 'admin')
headers = {'Content-type': 'application/json'}
post_url = 'http://localhost:5984/mydb'
req = requests.post(post_url, auth=auth,headers=headers, data=json.dumps(doc))
print json.dumps(req.json(), indent=1)
Notice that
the _id field is supplied in the doc and is lower case
the request call is a POST not a PUT
the post_url contains the name of the database being written to - in this case mydb
N.B in the above example I am writing to local CouchDB, but replacing the URL with your Cloudant URL and adding correct credentials should get this working for you.

Google maps reverse geocoding always responds with 602 (Unknown Address) on server side

I have server-side code that calls the Google geocoding API, like this:
http://maps.google.com/maps/geo?q=40.714224,-73.961452&output=json&sensor=false&key=API_KEY
where API_KEY is my API key. I get a JSON reply, as expected, but the reponse is always 602 (Unknown Address). Is my URL wrong? (I've also tried the URL in the Google docs, but that returns a status: 'REQUEST_DENIED'.
What else could be wrong?
Update:
Well, it seems to actually be a mistake in my implementation, not the URL. This was how I did it:
api_params = {
'q': '40.714224,-73.961452',
'sensor': 'false',
'key': KEY,
'output': 'json'
}
# make the api call
http_response = urllib.urlopen('http://maps.google.com/maps/geo',
urllib.urlencode(api_params))
r = json.load(http_response)
but changing it to:
api_params = {
#'q': str(lat) + ',' + str(lng),
'q': '40.714224,-73.961452',
'sensor': 'false',
'key': KEY,
'output': 'json'
}
# make the api call
http_response = urllib.urlopen('http://maps.google.com/maps/geo?q='+api_params['q']+'&output=json&sensor=false&key='+api_params['key'])
r = json.load(http_response)
print r
fixes the problem. So my new question is, what's wrong with the first one?
The first one executes POST request, the second - GET request.
You may also want to use the urllib.urlencode function for concatenation.
But the easiest way is to use geopy.
Try using a HTTP watcher to make sure that this is the actual URL that is being sent within your application. There could be a chance that it isn't being encoded correctly or maybe is being incorrectly assembled. Since you aren't getting request denied and we were able to get a good response when we viewed it directly it seems that could be the best place to start. Hope that helps!

Categories

Resources