user53558
user53558

Reputation: 367

Python: raising error for print output of function

I am using the InstagramAPI module from this github to create a script that posts pictures at certain time. A snippet below shows part of the code:

Insta = InstagramAPI(account_name, password)
Insta.login()
InstagramAPI.uploadPhoto(post_path, caption)
InstagramAPI.logout()

This works fine, unless the picture is in the wrong format. If it is in the wrong format, nothing is posted and this is printed:

Request return 400 error!
{u'status': u'fail', u'message': u"Uploaded image isn't in the right format"}

I have a function that will re-size if it isn't in the correct format. However, it is just print and not an error. Therefor, I can not put this in a try/except. So if the file isn't in the right format, it just skips and posts nothing.

Does anyone know of a way I could have my code save the print output to a variable so I can check if it contains "Uploaded image isn't in the right format" and raise an error if so?

Upvotes: 0

Views: 166

Answers (1)

wpercy
wpercy

Reputation: 10090

InstagramAPI.uploadPhoto() returns False if it unsuccessfully tries to post your photo. You can do something like:

Insta = InstagramAPI(account_name, password)
Insta.login()
success = Insta.uploadPhoto(post_path, caption)
if not success:
    resizeImage()  # your resize image logic
else:
    Insta.logout()

This will check to see if it was uploaded successfully, and if not, you can resize the image and try to upload again.

In your comment, you say that it returns False regardless of success, but I find that hard to believe. In uploadPhoto() we see this:

    response = self.s.post(self.API_URL + "upload/photo/", data=m.to_string())
    if response.status_code == 200:
        if self.configure(upload_id, photo, caption):
            self.expose()
    return False

This will only return False if the response code does not equal 200 or if self.configure() returns a falsey value.

self.configure() only generates a request body and calls:

return self.SendRequest('media/configure/?', self.generateSignature(data))

which will return true if your request to the Instagram API was successful:

if response.status_code == 200:
    self.LastResponse = response
    self.LastJson = json.loads(response.text)
    return True

Upvotes: 1

Related Questions