Skip to content

Commit

Permalink
Merge pull request #5 from gabrielmscampos/fix/ruff-linting
Browse files Browse the repository at this point in the history
fix: ruff target-version should be py39 instead of py310
  • Loading branch information
gabrielmscampos authored May 15, 2024
2 parents c31b0b0 + 62517a5 commit 0d29e1b
Show file tree
Hide file tree
Showing 16 changed files with 39 additions and 22 deletions.
1 change: 1 addition & 0 deletions .tool-versions
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python 3.9.19
1 change: 1 addition & 0 deletions cmsdials/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .cmsdials import Dials


__all__ = ["Dials"]
6 changes: 3 additions & 3 deletions cmsdials/auth/_base.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import threading
from abc import ABC, abstractmethod
from collections.abc import Mapping
from datetime import datetime, timedelta
from enum import Enum
from typing import Mapping

from .exceptions import ImpossibleToRefreshToken
from .exceptions import ImpossibleToRefreshTokenError


class TokenState(Enum):
Expand Down Expand Up @@ -116,7 +116,7 @@ def before_request(self, headers: Mapping[str, str]):
# If token is invalid (both token and refresh token expired): Throw error
# User need to interactively authenticate again
if self.token_state == TokenState.INVALID:
raise ImpossibleToRefreshToken
raise ImpossibleToRefreshTokenError

# If token is stale (token is close to expire)
# Re-use the token but launch a new thread to refresh the token
Expand Down
6 changes: 4 additions & 2 deletions cmsdials/auth/bearer.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import json
import os
import os.path
from collections.abc import Mapping
from datetime import datetime
from typing import Mapping, Optional
from typing import Optional

from ..utils._json import TokenDecoder, TokenEncoder
from ..utils.logger import logger
from ._base import BaseCredentials, TokenState
from .client import AuthClient
from .models import Token


DEFAULT_CACHE_DIR = ".cache"
DEFAULT_CACHE_FILENAME = "creds"

Expand Down Expand Up @@ -103,7 +105,7 @@ def from_creds_file(cache_dir: str = DEFAULT_CACHE_DIR, client: Optional[AuthCli
client = client or AuthClient()
fpath = Credentials._handle_creds_filepath(cache_dir)
try:
with open(fpath, "r") as filebuffer:
with open(fpath) as filebuffer:
fcontents = json.load(filebuffer, cls=TokenDecoder)
token = Token(**fcontents)
except FileNotFoundError:
Expand Down
5 changes: 5 additions & 0 deletions cmsdials/auth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ class AuthClient(BaseAPIClient):
Client for DIALS auth endpoint
"""

default_timeout = 30 # seconds

def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)

Expand All @@ -24,6 +26,7 @@ def new_device(self) -> Device:
headers={
"accept": "application/json",
},
timeout=self.default_timeout,
)
response.raise_for_status()
response = response.json()
Expand All @@ -38,6 +41,7 @@ def device_token(self, device_code: str) -> Token:
"Content-Type": "application/json",
},
json={"device_code": device_code},
timeout=self.default_timeout,
)

if response.status_code == 400 and "authorization_pending" in response.text:
Expand All @@ -63,6 +67,7 @@ def refresh_token(self, token_type: str, access_token: str, refresh_token: str)
"Authorization": f"{token_type} {access_token}",
},
json={"refresh_token": refresh_token},
timeout=self.default_timeout,
)
response.raise_for_status()
response = response.json()
Expand Down
2 changes: 1 addition & 1 deletion cmsdials/auth/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ class PendingAuthorizationError(Exception):
pass


class ImpossibleToRefreshToken(Exception):
class ImpossibleToRefreshTokenError(Exception):
pass
2 changes: 1 addition & 1 deletion cmsdials/auth/secret_key.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Mapping
from collections.abc import Mapping

from ._base import BaseCredentials

Expand Down
4 changes: 2 additions & 2 deletions cmsdials/clients/file_index/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import datetime
from typing import List, Optional
from typing import Optional

from pydantic import AnyUrl, BaseModel, Field

Expand All @@ -21,7 +21,7 @@ class FileIndex(BaseModel):
class PaginatedFileIndexList(BaseModel):
next: Optional[AnyUrl]
previous: Optional[AnyUrl]
results: List[FileIndex]
results: list[FileIndex]


class FileIndexFilters(OBaseModel):
Expand Down
4 changes: 2 additions & 2 deletions cmsdials/clients/h1d/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import List, Optional
from typing import Optional

from pydantic import AnyUrl, BaseModel, Field

Expand All @@ -24,7 +24,7 @@ class LumisectionHistogram1D(BaseModel):
class PaginatedLumisectionHistogram1DList(BaseModel):
next: Optional[AnyUrl]
previous: Optional[AnyUrl]
results: List[LumisectionHistogram1D]
results: list[LumisectionHistogram1D]


class LumisectionHistogram1DFilters(OBaseModel):
Expand Down
2 changes: 1 addition & 1 deletion cmsdials/clients/lumisection/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class LumisectionClient(BaseAuthorizedAPIClient):
def get(self, dataset_id: int, run_number: int, ls_number: int):
endpoint_url = f"{self.api_url}{self.lookup_url}{dataset_id}/{run_number}/{ls_number}/"
headers = self._build_headers()
response = requests.get(endpoint_url, headers=headers)
response = requests.get(endpoint_url, headers=headers, timeout=self.default_timeout)

try:
response.raise_for_status()
Expand Down
8 changes: 5 additions & 3 deletions cmsdials/clients/mes/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Optional

from pydantic import BaseModel, Field

from ...utils.base_model import OBaseModel
Expand All @@ -11,6 +13,6 @@ class MonitoringElement(BaseModel):


class MEFilters(OBaseModel):
me: str | None = None
me__regex: str | None = None
dim: int | None = None
me: Optional[str] = None
me__regex: Optional[str] = None
dim: Optional[int] = None
2 changes: 1 addition & 1 deletion cmsdials/clients/run/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class RunClient(BaseAuthorizedAPIClient):
def get(self, dataset_id: int, run_number: int):
endpoint_url = f"{self.api_url}{self.lookup_url}{dataset_id}/{run_number}/"
headers = self._build_headers()
response = requests.get(endpoint_url, headers=headers)
response = requests.get(endpoint_url, headers=headers, timeout=self.default_timeout)

try:
response.raise_for_status()
Expand Down
4 changes: 3 additions & 1 deletion cmsdials/cmsdials.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Optional

from .auth._base import BaseCredentials
from .clients.file_index.client import FileIndexClient
from .clients.h1d.client import LumisectionHistogram1DClient
Expand All @@ -8,7 +10,7 @@


class Dials:
def __init__(self, creds: BaseCredentials, workspace: str | None = None, *args, **kwargs) -> None:
def __init__(self, creds: BaseCredentials, workspace: Optional[str] = None, *args, **kwargs) -> None:
self.file_index = FileIndexClient(creds, workspace, *args, **kwargs)
self.h1d = LumisectionHistogram1DClient(creds, workspace, *args, **kwargs)
self.h2d = LumisectionHistogram2DClient(creds, workspace, *args, **kwargs)
Expand Down
11 changes: 7 additions & 4 deletions cmsdials/utils/api_client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import Optional
from urllib.parse import parse_qs, urlparse

import requests
Expand All @@ -12,7 +13,9 @@ class BaseAPIClient:
PRODUCTION_API_ROUTE = "api/"
PRODUCTION_API_VERSION = "v1/"

def __init__(self, base_url: str | None = None, route: str | None = None, version: str | None = None) -> None:
def __init__(
self, base_url: Optional[str] = None, route: Optional[str] = None, version: Optional[str] = None
) -> None:
self.base_url = self.__endswithslash(base_url or self.PRODUCTION_BASE_URL)
self.route = self.__endswithslash(route or self.PRODUCTION_API_ROUTE)
self.version = self.__endswithslash(version or self.PRODUCTION_API_VERSION)
Expand All @@ -38,7 +41,7 @@ class BaseAuthorizedAPIClient(BaseAPIClient):
def __init__(
self,
creds: BaseCredentials,
workspace: str | None = None,
workspace: Optional[str] = None,
*args: str,
**kwargs: str,
) -> None:
Expand Down Expand Up @@ -87,7 +90,7 @@ def list(self, filters=None):

raise ValueError("pagination model is None and response is not a list.")

def __list_sync(self, filters, max_pages: int | None = None):
def __list_sync(self, filters, max_pages: Optional[int] = None):
next_token = None
results = []
is_last_page = False
Expand All @@ -110,7 +113,7 @@ def __list_sync(self, filters, max_pages: int | None = None):
results=results, # No problem re-using last response count
)

def list_all(self, filters, max_pages: int | None = None):
def list_all(self, filters, max_pages: Optional[int] = None):
if self.pagination_model is None:
return self.list(filters)
return self.__list_sync(filters, max_pages)
1 change: 1 addition & 0 deletions cmsdials/utils/logger.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging


logging.basicConfig(format="[%(asctime)s] %(levelname)s: %(message)s", level=logging.INFO)

logger = logging.getLogger(__name__)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ exclude = [
]
line-length = 120
indent-width = 4
target-version = "py310"
target-version = "py39"

[tool.ruff.lint]
select = [
Expand Down

0 comments on commit 0d29e1b

Please sign in to comment.