Skip to content

Instantly share code, notes, and snippets.

@gorhack
Last active December 28, 2015 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gorhack/2b09b603a8b2d6e8cbb9 to your computer and use it in GitHub Desktop.
Save gorhack/2b09b603a8b2d6e8cbb9 to your computer and use it in GitHub Desktop.
import requests
from io import BytesIO
def genCatImage():
"""
generates an image from TheCatAPI and returns the image as a Byte stream
"""
# get image from website
r = requests.get('http://thecatapi.com/api/images/get?format=src&type=png')
if r.status_code == requests.codes.ok: # image returned OK
img = BytesIO(r.content) # create BytesIO object from the request
r.close() # close the get request
return img # return the BytesIO object
else: # request failed to retrieve the image
r.close() # close the get request
return genCatImage() # try to return another image
def uploadImage(url, params, file):
"""
uploads an image given the upload url [string], extra parameters [string], and file [bytes]
"""
# parameters for image upload
post_params = {'parameters': params}
# convert the BytesIO file object to a viable file parameter
files = {'file': file.getvalue()}
# POST request with the parameters for upload
r = requests.post(url, data=post_params, files=files)
file.close() # close the BytesIO object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment