I'm not yet very familiar with error handling in Python. I'd like to know how to retrieve the error code when I get an error using the python-twitter package :
import twitter
#[...]
try:
twitter_connexion.friendships.create(screen_name = "someone_who_blocked_me", follow = True)
except twitter.TwitterHTTPError as twittererror:
print(twittererror)
Twitter sent status 403 for URL: 1.1/friendships/create.json using parameters: (follow=True&oauth_consumer_key=XXX&oauth_nonce=XXX&oauth_signature_method=HMAC-SHA1&oauth_timestamp=XXX&oauth_token=XXX&oauth_version=1.0&screen_name=someone_who_blocked_me&oauth_signature=XXX)
details: {'errors': [{'message': 'You have been blocked from following this account at the request of the user.', 'code': 162}]}
In this case, I'd like to retrieve the 'code': 162 part, or just the 162.
twittererror.args is a tuple with one element in it, which is a string, print(twittererror.args[0][0:10]) outputs Twitter se
How can I get the 162 ?
(Obviously, twittererror.args[0][582:585] is not the answer I'm looking for, as any other error message will be of a different length and the error code won't be at [582:585])
Looking at how the TwitterHTTPError is defined in this GitHub repo, you should obtain the dict with twittererror.response_data.
Therefore you can do something like that:
import twitter
#[...]
try:
twitter_connexion.friendships.create(screen_name = "someone_who_blocked_me", follow = True)
except twitter.TwitterHTTPError as twittererror:
for error in twittererror.response_data.get("errors", []):
print(error.get("code", None))
Related
I was wondering how to validate that a user has correctly entered their spotify developer profile information correctly. I have a file, credentials.py, with 3 constants needed to get a spotify API token. In main.py, I use these constants like so.
def authenticate_user():
if not credentials.SPOTIPY_CLIENT_SECRET or not credentials.SPOTIPY_CLIENT_ID:
raise RuntimeError("Spotify credentials have not been set! Check credentials.py")
os.environ["SPOTIPY_CLIENT_ID"] = credentials.SPOTIPY_CLIENT_ID
os.environ["SPOTIPY_CLIENT_SECRET"] = credentials.SPOTIPY_CLIENT_SECRET
os.environ["SPOTIPY_REDIRECT_URI"] = credentials.SPOTIPY_REDIRECT_URI
sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth())
return sp
The resulting variable, sp, does not seem to have any methods to verify that it has successfully been validated. On attempting to use any methods, you are sent to a webpage with the corresponding spotify endpoint, showing that the request failed. When exiting the page, no error is thrown and the program hangs. How do I throw an error on invalid information being used to authenticate with the spotify servers?
You can check if the spotipy api returns a boolean upon verification, just make an if statement that looks like this:
If (sp == True):
Print('credentials valid')
Base on Spotify docs here
you should get a Spotify.oauth2.SpotifyOauthError
then you can surround the code with a try and except.
you can do it like this:
try:
sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth())
return sp
except SpotifyOauthError as e:
raise RuntimeError(f"Spotify credentials didn't work, error={e}")
just don't forget to import the exception from Spotify.oauth2.SpotifyOauthError
I want to rates the stocks in Benzinga using Benzinga API for python. But, when I follow its documentation I get an error as shown below.
raise TokenAuthenticationError
benzinga.benzinga_errors.TokenAuthenticationError: Error Message: Something went wrong. Please again try again later
I used the default key from Benzinga API Document.
from benzinga import financial_data
api_key = "testkey892834789s9s8abshtuy"
fin = financial_data.Benzinga(api_key)
stock_ratings = fin.ratings()
fin.output(stock_ratings)
What should I do to make it work? Did the API key is expired and I need to renew it?
I want to use Google Street View API to download some images in python.
Sometimes there is no image return in one area, but the API key can be used.
Other time API key is expired or invalid, and also cannot return image.
The Google Maps API server rejected your request. The provided API key is expired.
How to distinguish these two situations with code in Python?
Thank you very much.
One way to do this would be to make an api call with the requests library, and parse the JSON response:
import requests
url = 'https://maps.googleapis.com/maps/api/streetview?size=600x300&location=46.414382,10.013988&heading=151.78&pitch=-0.76&key=YOUR_API_KEY'
r = requests.get(url)
results = r.json()
error_message = results.get('error_message')
Now error_message will be the text of the error message (e.g., 'The provided API key is expired.'), or will be None if there is no error message. So later in your code you can check if there is an error message, and do things based on the content of the message:
if error_message and 'The provided API key is invalid.' in error_message:
do_something()
elif ...:
do_something_else()
You could also check the key 'status' if you just want to see if the request was successful or not:
status = results.get('status')
I have some code that follows everyone in return when they follow me:
import twitter
from sets import Set
try:
api = twitter.Api(consumer_key='',
consumer_secret='',
access_token_key='',
access_token_secret='')
following = api.GetFriends()
friendNames = Set()
for friend in following:
friendNames.add(friend.screen_name)
followers = api.GetFollowers()
for follower in followers:
if (not follower.screen_name in friendNames):
api.CreateFriendship(follower.screen_name)
except Exception as exc:
print('generated an exception: %s' % (exc))
This is throwing up the following error:
generated an exception: [{'message': 'Rate limit exceeded', 'code': 88}]
I am aware that their is a restriction around how many followers you can follow back per hour using this code via the API, however I have manually followed all my followers back and still got the same error. Can anyone see what the issue is here?
Thanks
I am using tweepy to make a twitter application.
When users tweet/update profile, etc, they will get some errors. I want to classify error and give user more information.
try:
tweet/update profile/ follow....
except tweepy.TweepError, e:
if tweepy.TweepError is "Account update failed: Description is too long (maximum is 160 characters)"
Do something
if tweepy.TweepError is "Failed to send request: Invalid request URL: http://api.twitter.com/1/account/update_profile.json?location=%E5%85%B5%E5%BA%A"
Do something
if tweepy.TweepError is "[{u'message': u'Over capacity', u'code': 130}]"
Do something
Is the only way to classify error is to compare e with string, for example, Account update failed: Description is too long (maximum is 160 characters)?
Right, it is the only way now. There is only one TweepError exception defined. It's raised throughout the app with different text.
Here's the relevant open issue on github. So there is a chance that it'll be improved in the future.