Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a patch method to update the message_last_read field in _user_set… #821

Merged
merged 4 commits into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
78 changes: 75 additions & 3 deletions mp_api/client/core/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@

import boto3
import requests
from botocore import UNSIGNED
from botocore.config import Config
from emmet.core.utils import jsanitize
from monty.json import MontyDecoder
from pydantic import BaseModel, create_model
from requests.adapters import HTTPAdapter
from requests.exceptions import RequestException
from tqdm.auto import tqdm
from urllib3.util.retry import Retry
from botocore import UNSIGNED
from botocore.config import Config

from mp_api.client.core.settings import MAPIClientSettings
from mp_api.client.core.utils import api_sanitize, validate_ids
Expand Down Expand Up @@ -133,7 +133,9 @@ def session(self) -> requests.Session:
@property
def s3_resource(self):
if not self._s3_resource:
self._s3_resource = boto3.resource("s3", config=Config(signature_version=UNSIGNED))
self._s3_resource = boto3.resource(
"s3", config=Config(signature_version=UNSIGNED)
)
return self._s3_resource

@staticmethod
Expand Down Expand Up @@ -246,6 +248,76 @@ def _post_resource(
except RequestException as ex:
raise MPRestError(str(ex))

def _patch_resource(
self,
body: Dict = None,
params: Optional[Dict] = None,
suburl: Optional[str] = None,
use_document_model: Optional[bool] = None,
) -> Dict:
"""Patch data to the endpoint for a Resource.

Arguments:
body: body json to send in patch request
params: extra params to send in patch request
suburl: make a request to a specified sub-url
use_document_model: if None, will defer to the self.use_document_model attribute

Returns:
A Resource, a dict with two keys, "data" containing a list of documents, and
"meta" containing meta information, e.g. total number of documents
available.
"""
if use_document_model is None:
use_document_model = self.use_document_model

payload = jsanitize(body)

try:
url = self.endpoint
if suburl:
url = urljoin(self.endpoint, suburl)
if not url.endswith("/"):
url += "/"
response = self.session.patch(url, json=payload, verify=True, params=params)

if response.status_code == 200:
if self.monty_decode:
data = json.loads(response.text, cls=MontyDecoder)
else:
data = json.loads(response.text)

if self.document_model and use_document_model:
if isinstance(data["data"], dict):
data["data"] = self.document_model.parse_obj(data["data"]) # type: ignore
elif isinstance(data["data"], list):
data["data"] = [self.document_model.parse_obj(d) for d in data["data"]] # type: ignore

return data

else:
try:
data = json.loads(response.text)["detail"]
except (JSONDecodeError, KeyError):
data = f"Response {response.text}"
if isinstance(data, str):
message = data
else:
try:
message = ", ".join(
f"{entry['loc'][1]} - {entry['msg']}" for entry in data
)
except (KeyError, IndexError):
message = str(data)

raise MPRestError(
f"REST post query returned with error status code {response.status_code} "
f"on URL {response.url} with message:\n{message}"
)

except RequestException as ex:
raise MPRestError(str(ex))

def _query_open_data(self, bucket: str, prefix: str, key: str) -> dict:
"""Query Materials Project AWS open data s3 buckets

Expand Down
19 changes: 19 additions & 0 deletions mp_api/client/routes/_user_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,25 @@ def set_user_settings(self, consumer_id, settings): # pragma: no cover
body=settings, params={"consumer_id": consumer_id}
).get("data")

def patch_user_time_settings(self, consumer_id, time): # pragma: no cover
"""Set user settings.

Args:
consumer_id: Consumer ID for the user
time: utc datetime object for when the user last see messages
Returns:
Dictionary with consumer_id and write status.


Raises:
MPRestError.
"""

return self._patch_resource(
body={"settings.message_last_read": time.isoformat()},
params={"consumer_id": consumer_id},
).get("data")

def get_user_settings(self, consumer_id): # pragma: no cover
"""Get user settings.

Expand Down