Continue On Error Smartsheet SDK on python - python

I'm Trying to list the users of my domain smartsheet to backup their data one by one.
For that i need to list them then for every id i retrieve user Home with ss.Home.list_all_content()
the first one is ok, but the second give me this error when i try to retrieve his home or just make a ss.Users.get_User(his id) see below error:
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
ss.Users.list_users(include_all=True)
File "D:\Users\maxime.champain\AppData\Local\Programs\Python\Python35-32\lib\site-packages\smartsheet\users.py", line 277, in list_users
response = self._base.request(prepped_request, expected, _op)
File "D:\Users\maxime.champain\AppData\Local\Programs\Python\Python35-32\lib\site-packages\smartsheet\smartsheet.py", line 218, in request
raise the_ex(native, str(native.result.code) + ': ' + native.result.message)
smartsheet.exceptions.ApiError: {"result": {"shouldRetry": false, "refId": null, "code": 5349, "recommendation": "Do not retry without fixing the problem. ", "statusCode": 400, "message": "You must agree to the Smartsheet User Agreement before using Smartsheet. These terms can be viewed the next time you log in to https://app.smartsheet.com from a desktop browser.", "name": "ApiError"}, "requestResponse": null}
Question
How can I simply bypass this error to continue the program.
The exception of this error is handled by the smartsheet api sdk but i don't know how to call it.
regards,

If you want to catch this exception and continue, you'll need to use the try and except keywords.
There are many tutorials on the web, here's one: https://docs.python.org/3/tutorial/errors.html#handling-exceptions

Related

Unable to improve transcription accuracy with speech adaptation boost

I'm using SpeechRecognition Python library to perform Speech to Text operations. I'm using the recognize_google_cloud function to use Google Cloud Speech-to-Text API.
Here is my code:
import speech_recognition as sr;
import json;
j = '';
with open('key.json', 'r') as f:
j = f.read().replace('\n', '');
js = json.loads(j);
r = sr.Recognizer();
mic = sr.Microphone();
with candide as source:
audio = r.record(source);
print(r.recognize_google_cloud(audio, language='fr-FR', preferred_phrases=['pistoles', 'disait'], credentials_json=j));
The function recognize_google_cloud send the data captured by the microphone to Google API and selects the most probable transcription of the given speech among a set of alternatives.
The parameter preferered_phrases, as explained in this page of the documentation, is used to select an other alternative that contains the listed words.
It is possible to improve these results using speech adaptation boost. As the version of the SpeechRecognition library doesn't let us to specify a boost value, I updated the speech_recognition/__init__.py file with an hard-coded boost value:
if preferred_phrases is not None:
speech_config["speechContexts"] = {"phrases": preferred_phrases, "boost": 19}
Unfortunately, when I execute my code, I get the following error:
Traceback (most recent call last):
File "/home/pierre/.local/lib/python3.8/site-packages/speech_recognition/__init__.py", line 931, in recognize_google_cloud
response = request.execute()
File "/home/pierre/.local/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
return wrapped(*args, **kwargs)
File "/home/pierre/.local/lib/python3.8/site-packages/googleapiclient/http.py", line 915, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://speech.googleapis.com/v1/speech:recognize?alt=json returned "Invalid JSON payload received. Unknown name "boost" at 'config.speech_contexts': Cannot find field.". Details: "[{'#type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'config.speech_contexts', 'description': 'Invalid JSON payload received. Unknown name "boost" at \'config.speech_contexts\': Cannot find field.'}]}]">
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "spech_reco.py", line 23, in <module>
print(r.recognize_google_cloud(audio, language='fr-FR', preferred_phrases=['pistoles', 'disait'], credentials_json=j));
File "/home/pierre/.local/lib/python3.8/site-packages/speech_recognition/__init__.py", line 933, in recognize_google_cloud
raise RequestError(e)
speech_recognition.RequestError: <HttpError 400 when requesting https://speech.googleapis.com/v1/speech:recognize?alt=json returned "Invalid JSON payload received. Unknown name "boost" at 'config.speech_contexts': Cannot find field.". Details: "[{'#type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'config.speech_contexts', 'description': 'Invalid JSON payload received. Unknown name "boost" at \'config.speech_contexts\': Cannot find field.'}]}]">
Is there an error in my request?
I understand that you are modifying the speech_recognition/__init__.py file of the SpeechRecognition library in order to include the "boost" parameter in your request.
When reviewing this file I noticed that it is using the 'v1' version of the API; however, the "boost" parameter is only supported in the ‘v1p1beta1’ version
Therefore, another of the adaptations that you could make in the code is the following:
`speech_service = build ("speech","v1p1beta1", credentials = api_credentials, cache_discovery = False)`
With this modification you should no longer see the BadRequest error.
At the same time, please consider that this library is a third-party library that uses the Google Speech-to-text API internally. Therefore, if this library does not cover all your current needs, another alternative could create your own implementation directly using the Speech-to-text API Python Client library.

How To Retrieve Folder Tree With Smartsheets API Python

I'm trying to retrieve sheets with Users.list_org_sheets(include_all=True) from the Python SDK API.
With That I can see all the things I need :
lstorg = ss.Users.list_org_sheets(include_all=True)
for entry in lstorg.data:
print(entry.id)
print(entry.name)
ss is the smartsheet.Smartsheet(token).
So with that i can see all the sheets in my domain, but when i try to download them with get_sheet_as_excel(id, path) I got that error:
print(ss.Sheets.get_sheet('6157394402142084'))
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print(ss.Sheets.get_sheet('6157394402142084')
File "E:\Python\lib\site-packages\smartsheet\sheets.py", line 525, in get_sheet
response = self._base.request(prepped_request, expected, _op)
File "E:\Python\lib\site-packages\smartsheet\smartsheet.py", line 218, in request
raise the_ex(native, str(native.result.code) + ': ' + native.result.message)
smartsheet.exceptions.ApiError: {"requestResponse": null, "result": {"code": 1006, "message": "Not Found", "name": "ApiError", "recommendation": "Do not retry without fixing the problem. ", "refId": null, "shouldRetry": false, "statusCode": 404}}
I guess that this error mean that he didn't find the file (Error 404) but I don't know why, just before i make the command to get a list of all sheets and then when i pick one of that (that i'm not owner with this token but the token is SysAdmin)
Thanks For the help
The situation you're describing is due to how permissions work in Smartsheet. Using the SysAdmin token, you can successfully get the list of all Sheets owned by members of the account, but the SysAdmin token will not allow you to access the contents of those sheets, unless that SysAdmin user has been explicitly granted access to the sheets. You're getting the "not found" error when you try to retrieve the sheet because the SysAdmin user hasn't explicitly been granted access to that sheet in Smartsheet.
To actually retrieve a sheet that's listed in the "List Org Sheets" response, you'll need to add the Assume-User header to the "Get Sheet" API request to impersonate the sheet owner. You can find documentation about the Assume-User header here: https://smartsheet-platform.github.io/api-docs/#http-headers.

Python Boto3 Module fetching API Keys with position parameter raising an exception

I tried to fetch list of API Keys created in my aws account. There are 50 Api keys. I want to list 10 Api Keys per request. Here is the code snippet.
import boto3
client = boto3.client('apigateway')
response = client.get_api_keys(
limit=10,
position="1",
)
print response
When I run the script, It is showing an error,
Traceback (most recent call last):
File "test.py", line 7, in <module>
position="1",
File "C:\Users\Murthy\workspace\my_project\venv\lib\site-packages\botocore\client.py", line 310, in _api_call
return self._make_api_call(operation_name, kwargs)
File "C:\Users\Murthy\workspace\my_project\venv\lib\site-packages\botocore\client.py", line 599, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.errorfactory.BadRequestException: An error occurred (BadRequestException) when calling the GetApiKeys operation: Invalid position parameter
Am I doing wrong ?
Also maximum results per query is 500. How do we know total number of results to perform the pagination ?
The position variable acts as a token. It is to be used to get the next page of your request.
In the first call to retrieve the usage plans, the position should be set to null, then to get the next page, you have to assign the position the value of the position in the previous response. The position variable is more like a token.
import boto3
client = boto3.client('apigateway')
response = client.get_api_keys(
limit=10,
position=null,
)
print response
Your response would be something like this
{
"position": "vWQ3Uzc4bAY2YQ%3D%3D",
"items": [
{
"id": "fqewi1",
"name": "3rd Party",
"description": null,
"apiStages": [],
"throttle": {
"burstLimit": 2,
"rateLimit": 1.0
},
.
.
.
}
Your next request would be in this format
import boto3
client = boto3.client('apigateway')
response = client.get_api_keys(
limit=10,
position="vWQ3Uzc4bAY2YQ%3D%3D",
)
print response
This would return the next page. For the last page, the position would be null.

Key Error when extracting the body from email

For some messages, I believe that there is no 'parts' component. I thought the code below covers most messages, but it is still throwing a keyerror: 'data' when trying to get some messages. I have looked through the json result for those messages and they all contain 'data', not sure what's going on. Traceback shows that the keyerror is coming from messages that do contain 'parts'
Traceback
Traceback (most recent call last):
File "gmail.py", line 168, in <module>
final_message_list.append(GetMessage(gmail_service, 'me', message_id))
File "gmail.py", line 150, in GetMessage
message_raw = message['payload']['parts'][0]['body']['data']
(within GetMessage)
# Pull Raw Message Body from Response, some emails may not contain 'parts'
if 'parts' in message['payload']:
message_raw = message['payload']['parts'][0]['body']['data']
else:
message_raw = message['payload']['body']['data']
After some investigation, this is the best I've been able to do for now, if anyone has a better solution please post.
It looks like the message in question that caused the failure has an attachment, and perhaps the attachment is what messes up the structure of the message a bit. I've been able to see that the mimeType within 'Parts' is different (multipart/alternative) for attachment messages than it is for non-attachment messages (text/plain). Thus, I've been able to cover this case by just putting an 'if' statement before I try to parse out the message body, as shown below.
if 'parts' in message['payload']:
if message['payload']['parts'][0]['mimeType'] == 'multipart/alternative':
message_raw = message['payload']['parts'][0]['parts'][0]['body']['data']
else:
message_raw = message['payload']['parts'][0]['body']['data']
else:
message_raw = message['payload']['body']['data']

ValidationError while running Google adwords client library examples

I get the following error when I try to run sample example of Google adwords
[root#some v200909]# python get_related_keywords.py Traceback (most recent call last): File "get_related_keywords.py", line 53, in
page = targeting_idea_service.Get(selector)[0] File "../../aw_api/TargetingIdeaService.py", line 105, in Get
'TargetingIdea', self.__loc, request) File "../../aw_api/WebService.py", line 350, in CallMethod
raise ValidationError(error['data']) aw_api.Errors.ValidationError: Invalid headers for 'https://adwords-sandbox.google.com', see http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders. [root#some v200909]#
This sounds like an issue with the headers you're providing. The headers must be especially formatted for the sandbox, so make sure that:
a) You're formatting the headers as specified in http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders , as Goose Bumper mentioned. This applies to both v2009 and v13, as you still need to format the developer token and client email according to the instructions (the application token is now obsolete).
b) You're choosing the right endpoint, namely adwords-sandbox.google.com for v2009 and sandbox.google.com for v13
If this still doesn't work for you, the SOAP logs for your request might be useful.

Categories