X-Git-Url: https://git.mdrn.pl/redakcja.git/blobdiff_plain/5913c54d19b8f6775633176032161d49f9b2f1aa..aac3fdbb766e03b97da2fa17bc2cd3e8378bdefb:/src/apiclient/__init__.py?ds=inline diff --git a/src/apiclient/__init__.py b/src/apiclient/__init__.py index 56ecb96d..44546d33 100644 --- a/src/apiclient/__init__.py +++ b/src/apiclient/__init__.py @@ -1,8 +1,9 @@ -import urllib - +# This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later. +# Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. +# import json +from urllib.parse import urlencode import oauth2 - from apiclient.settings import WL_CONSUMER_KEY, WL_CONSUMER_SECRET, WL_API_URL, BETA_API_URL @@ -20,7 +21,7 @@ class NotAuthorizedError(BaseException): pass -def api_call(user, path, data=None, beta=False): +def api_call(user, path, data=None, beta=False, method=None, as_json=False): from .models import OAuthConnection api_url = BETA_API_URL if beta else WL_API_URL conn = OAuthConnection.get(user=user, beta=beta) @@ -30,22 +31,30 @@ def api_call(user, path, data=None, beta=False): client = oauth2.Client(wl_consumer, token) if data is not None: data = json.dumps(data) - data = urllib.urlencode({"data": data}) + headers = {} + if as_json: + headers["Content-Type"] = 'application/json' + else: + data = urlencode({"data": data}) + data = data.encode('utf-8') + resp, content = client.request( - "%s%s" % (api_url, path), - method="POST", - body=data) + "%s%s" % (api_url, path), + method=method or 'POST', + headers=headers, + body=data) else: resp, content = client.request( - "%s%s" % (api_url, path)) + "%s%s" % (api_url, path), + method=method or 'GET' + ) status = resp['status'] - if status == '200': + if status in ('200', '201'): return json.loads(content) elif status.startswith('2'): return elif status == '401': raise ApiError('User not authorized for publishing.') else: - raise ApiError("WL API call error %s, path: %s" % (status, path)) - + raise ApiError("WL API call error %s, path: %s, body: %s" % (status, path, content))