Skip to content

Commit

Permalink
global: use black as opinionated code formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
tmorrell committed Mar 21, 2024
1 parent 1a7fe9c commit 6daf1c0
Show file tree
Hide file tree
Showing 30 changed files with 2,852 additions and 2,654 deletions.
9 changes: 0 additions & 9 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,6 @@ insert_final_newline = true
trim_trailing_whitespace = true
charset = utf-8

# Python files
[*.py]
indent_size = 4
# isort plugin configuration
known_first_party = datacite
known_standard_library = ssl
multi_line_output = 2
default_section = THIRDPARTY

# RST files (used by sphinx)
[*.rst]
indent_size = 4
Expand Down
2 changes: 1 addition & 1 deletion datacite/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@

__version__ = "1.1.4"

__all__ = ('DataCiteMDSClient', 'DataCiteRESTClient', '__version__')
__all__ = ("DataCiteMDSClient", "DataCiteRESTClient", "__version__")
26 changes: 14 additions & 12 deletions datacite/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
from .errors import DataCiteError
from .request import DataCiteRequest

HTTP_OK = requests.codes['ok']
HTTP_CREATED = requests.codes['created']
HTTP_OK = requests.codes["ok"]
HTTP_CREATED = requests.codes["created"]


class DataCiteMDSClient(object):
Expand All @@ -30,8 +30,9 @@ class DataCiteMDSClient(object):
developed.
"""

def __init__(self, username, password, prefix, test_mode=False, url=None,
timeout=None):
def __init__(
self, username, password, prefix, test_mode=False, url=None, timeout=None
):
"""Initialize the API client wrapper.
:param username: DataCite username.
Expand All @@ -51,14 +52,14 @@ def __init__(self, username, password, prefix, test_mode=False, url=None,
else:
self.api_url = url or "https://mds.datacite.org/"

if not self.api_url.endswith('/'):
self.api_url += '/'
if not self.api_url.endswith("/"):
self.api_url += "/"

self.timeout = timeout

def __repr__(self):
"""Create string representation of object."""
return '<DataCiteMDSClient: {0}>'.format(self.username)
return "<DataCiteMDSClient: {0}>".format(self.username)

def _create_request(self):
"""Create a new Request object."""
Expand Down Expand Up @@ -88,7 +89,7 @@ def doi_post(self, new_doi, location):
:param location: URL where the resource is located.
:return: "CREATED" or "HANDLE_ALREADY_EXISTS".
"""
headers = {'Content-Type': 'text/plain;charset=UTF-8'}
headers = {"Content-Type": "text/plain;charset=UTF-8"}
# Use \r\n for HTTP client data.
body = "\r\n".join(["doi=%s" % new_doi, "url=%s" % location])

Expand All @@ -105,8 +106,7 @@ def metadata_get(self, doi):
:param doi: DOI name of the resource.
"""
headers = {'Accept': 'application/xml',
'Accept-Encoding': 'UTF-8'}
headers = {"Accept": "application/xml", "Accept-Encoding": "UTF-8"}

request = self._create_request()
resp = request.get("metadata/" + doi, headers=headers)
Expand All @@ -125,7 +125,9 @@ def metadata_post(self, metadata):
:param metadata: XML format of the metadata.
:return: "CREATED" or "HANDLE_ALREADY_EXISTS"
"""
headers = {'Content-Type': 'application/xml;charset=UTF-8', }
headers = {
"Content-Type": "application/xml;charset=UTF-8",
}

request = self._create_request()
resp = request.post("metadata", body=metadata, headers=headers)
Expand Down Expand Up @@ -174,7 +176,7 @@ def media_post(self, doi, media):
:param media: Dictionary of (mime-type, URL) key/value pairs.
:return: "OK"
"""
headers = {'Content-Type': 'text/plain;charset=UTF-8'}
headers = {"Content-Type": "text/plain;charset=UTF-8"}

# Use \r\n for HTTP client data.
body = "\r\n".join(["%s=%s" % (k, v) for k, v in media.items()])
Expand Down
6 changes: 3 additions & 3 deletions datacite/jsonutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@
"""JSON utilities."""

import json

from jsonschema import RefResolver, validate
from jsonschema.validators import validator_for


def validator_factory(schema_filename):
"""Provide a JSON schema validator for a given schema file."""
with open(schema_filename, 'r') as fp:
with open(schema_filename, "r") as fp:
schema = json.load(fp)

validator_cls = validator_for(schema)
validator_cls.check_schema(schema)

return validator_cls(
schema,
resolver=RefResolver('file:{}'.format(schema_filename), schema)
schema, resolver=RefResolver("file:{}".format(schema_filename), schema)
)
39 changes: 23 additions & 16 deletions datacite/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,22 @@ class DataCiteRequest(object):
(connect, read) to specify each timeout individually.
"""

def __init__(self, base_url=None, username=None, password=None,
default_params=None, timeout=None):
def __init__(
self,
base_url=None,
username=None,
password=None,
default_params=None,
timeout=None,
):
"""Initialize request object."""
self.base_url = base_url
self.username = username
self.password = password.encode('utf8')
self.password = password.encode("utf8")
self.default_params = default_params or {}
self.timeout = timeout

def request(self, url, method='GET', body=None, params=None, headers=None):
def request(self, url, method="GET", body=None, params=None, headers=None):
"""Make a request.
If the request was successful (i.e no exceptions), you can find the
Expand All @@ -66,7 +72,7 @@ def request(self, url, method='GET', body=None, params=None, headers=None):
url = self.base_url + url

if body and isinstance(body, str):
body = body.encode('utf-8')
body = body.encode("utf-8")

request_func = getattr(requests, method.lower())
kwargs = dict(
Expand All @@ -75,12 +81,12 @@ def request(self, url, method='GET', body=None, params=None, headers=None):
headers=headers,
)

if method == 'POST':
kwargs['data'] = body
if method == 'PUT':
kwargs['data'] = body
if method == "POST":
kwargs["data"] = body
if method == "PUT":
kwargs["data"] = body
if self.timeout is not None:
kwargs['timeout'] = self.timeout
kwargs["timeout"] = self.timeout

try:
return request_func(url, **kwargs)
Expand All @@ -95,15 +101,16 @@ def get(self, url, params=None, headers=None):

def post(self, url, body=None, params=None, headers=None):
"""Make a POST request."""
return self.request(url, method="POST", body=body, params=params,
headers=headers)
return self.request(
url, method="POST", body=body, params=params, headers=headers
)

def put(self, url, body=None, params=None, headers=None):
"""Make a PUT request."""
return self.request(url, method="PUT", body=body, params=params,
headers=headers)
return self.request(
url, method="PUT", body=body, params=params, headers=headers
)

def delete(self, url, params=None, headers=None):
"""Make a DELETE request."""
return self.request(url, method="DELETE", params=params,
headers=headers)
return self.request(url, method="DELETE", params=params, headers=headers)
55 changes: 29 additions & 26 deletions datacite/rest_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,24 @@
"""

import json
import requests
import warnings

import requests
from idutils import normalize_doi

from .errors import DataCiteError
from .request import DataCiteRequest

HTTP_OK = requests.codes['ok']
HTTP_CREATED = requests.codes['created']
HTTP_OK = requests.codes["ok"]
HTTP_CREATED = requests.codes["created"]


class DataCiteRESTClient(object):
"""DataCite REST API client wrapper."""

def __init__(self, username, password, prefix, test_mode=False, url=None,
timeout=None):
def __init__(
self, username, password, prefix, test_mode=False, url=None, timeout=None
):
"""Initialize the REST client wrapper.
:param username: DataCite username.
Expand All @@ -52,14 +54,14 @@ def __init__(self, username, password, prefix, test_mode=False, url=None,
else:
self.api_url = url or "https://api.datacite.org/"

if not self.api_url.endswith('/'):
self.api_url += '/'
if not self.api_url.endswith("/"):
self.api_url += "/"

self.timeout = timeout

def __repr__(self):
"""Create string representation of object."""
return '<DataCiteRESTClient: {0}>'.format(self.username)
return "<DataCiteRESTClient: {0}>".format(self.username)

def _create_request(self):
"""Create a new Request object."""
Expand Down Expand Up @@ -87,7 +89,7 @@ def get_doi(self, doi):
request = self._create_request()
resp = request.get("dois/" + doi)
if resp.status_code == HTTP_OK:
return resp.json()['data']['attributes']['url']
return resp.json()["data"]["attributes"]["url"]
else:
raise DataCiteError.factory(resp.status_code, resp.text)

Expand All @@ -98,38 +100,39 @@ def check_doi(self, doi):
12.12345/123 with the prefix defined
"""
# If prefix is in doi
if '/' in doi:
split = doi.split('/')
if "/" in doi:
split = doi.split("/")
prefix = split[0]
if prefix != self.prefix:
# Provided a DOI with the wrong prefix
raise ValueError('Wrong DOI {0} prefix provided, it should be '
'{1} as defined in the rest client'
.format(prefix, self.prefix))
raise ValueError(
"Wrong DOI {0} prefix provided, it should be "
"{1} as defined in the rest client".format(prefix, self.prefix)
)
else:
doi = '{prefix}/{doi}'.format(prefix=self.prefix, doi=doi)
doi = "{prefix}/{doi}".format(prefix=self.prefix, doi=doi)
return normalize_doi(doi)

def post_doi(self, data):
"""Post a new JSON payload to DataCite."""
headers = {'content-type': 'application/vnd.api+json'}
headers = {"content-type": "application/vnd.api+json"}
body = {"data": data}
request = self._create_request()
resp = request.post("dois", body=json.dumps(body), headers=headers)
if resp.status_code == HTTP_CREATED:
return resp.json()['data']['id']
return resp.json()["data"]["id"]
else:
raise DataCiteError.factory(resp.status_code, resp.text)

def put_doi(self, doi, data):
"""Put a JSON payload to DataCite for an existing DOI."""
headers = {'content-type': 'application/vnd.api+json'}
headers = {"content-type": "application/vnd.api+json"}
body = {"data": data}
request = self._create_request()
url = "dois/" + doi
resp = request.put(url, body=json.dumps(body), headers=headers)
if resp.status_code == HTTP_OK:
return resp.json()['data']['attributes']
return resp.json()["data"]["attributes"]
else:
raise DataCiteError.factory(resp.status_code, resp.text)

Expand All @@ -148,7 +151,7 @@ def draft_doi(self, metadata=None, doi=None):
"""
data = {"attributes": {}}
if metadata:
data['attributes'] = metadata
data["attributes"] = metadata
data["attributes"]["prefix"] = self.prefix
if doi:
doi = self.check_doi(doi)
Expand All @@ -166,7 +169,7 @@ def update_url(self, doi, url):
data = {"attributes": {"url": url}}

result = self.put_doi(doi, data)
return result['url']
return result["url"]

def delete_doi(self, doi):
"""Delete a doi.
Expand Down Expand Up @@ -220,7 +223,7 @@ def update_doi(self, doi, metadata=None, url=None):
doi = self.check_doi(doi)
data["attributes"]["doi"] = doi
if metadata:
data['attributes'] = metadata
data["attributes"] = metadata
if url:
data["attributes"]["url"] = url

Expand Down Expand Up @@ -300,12 +303,12 @@ def get_metadata(self, doi):
:param doi: DOI name of the resource.
"""
"""Put a JSON payload to DataCite for an existing DOI."""
headers = {'content-type': 'application/vnd.api+json'}
headers = {"content-type": "application/vnd.api+json"}
request = self._create_request()
resp = request.get("dois/" + doi, headers=headers)

if resp.status_code == HTTP_OK:
return resp.json()['data']['attributes']
return resp.json()["data"]["attributes"]
else:
raise DataCiteError.factory(resp.status_code, resp.text)

Expand All @@ -323,11 +326,11 @@ def get_media(self, doi):
:param doi: DOI name of the resource.
"""
headers = {'content-type': 'application/vnd.api+json'}
headers = {"content-type": "application/vnd.api+json"}
request = self._create_request()
resp = request.get("dois/" + doi, headers=headers)

if resp.status_code == HTTP_OK:
return resp.json()['relationships']['media']
return resp.json()["relationships"]["media"]
else:
raise DataCiteError.factory(resp.status_code, resp.text)
Loading

0 comments on commit 6daf1c0

Please sign in to comment.