Skip to content

Commit

Permalink
Add upload image method
Browse files Browse the repository at this point in the history
  • Loading branch information
kylehg committed Oct 9, 2015
1 parent b2654cc commit 66b6560
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions medium/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Copyright 2015 A Medium Corporation
from os.path import basename
try:
from urllib.parse import urlencode
except ImportError:
Expand Down Expand Up @@ -88,6 +89,8 @@ def exchange_refresh_token(self, refresh_token):
def get_current_user(self):
"""Fetch the data for the currently authenticated user.
Requires the ``basicProfile`` scope.
:returns: A dictionary with the users data ::
{
Expand All @@ -104,6 +107,8 @@ def create_post(self, user_id, title, content, content_format, tags=None,
canonical_url=None, publish_status=None, license=None):
"""Create a post for the current user.
Requires the ``publishPost`` scope.
:param str user_id: The application-specific user ID as returned by
``get_current_user()``
:param str title: The title of the post
Expand Down Expand Up @@ -156,6 +161,26 @@ def create_post(self, user_id, title, content, content_format, tags=None,
path = "/v1/users/%s/posts" % user_id
return self._request("POST", path, json=data)

def upload_image(self, file_path, content_type):
"""Upload a local image to Medium for use in a post.
Requires the ``uploadImage`` scope.
:param str file_path: The file path of the image
:param str content_type: The type of the image. Valid values are
``image/jpeg``, ``image/png``, ``image/gif``, and ``image/tiff``.
:returns: A dictionary with the image data ::
{
'url': 'https://cdn-images-1.medium.com/0*dlkfjalksdjfl.jpg',
'md5': 'd87e1628ca597d386e8b3e25de3a18b8'
}
"""
with open(file_path, "rb") as f:
filename = basename(file_path)
files = {"image": (filename, f, content_type)}
return self._request("POST", "/v1/images", files=files)

def _request_and_set_auth_code(self, data):
"""Request an access token and set it on the current client."""
result = self._request("POST", "/v1/tokens", form_data=data)
Expand All @@ -170,10 +195,7 @@ def _request(self, method, path, json=None, form_data=None, files=None):
"Accept-Charset": "utf-8",
"Authorization": "Bearer %s" % self.access_token,
}
if form_data is not None:
headers["Content-Type"] = "application/x-www-form-urlencoded"
else:
headers["Content-Type"] = "application/json"

resp = requests.request(method, url, json=json, data=form_data,
files=files, headers=headers)
json = resp.json()
Expand Down

0 comments on commit 66b6560

Please sign in to comment.