first prototype

This commit is contained in:
2021-05-27 15:09:08 +02:00
parent b8d7e7fa6b
commit d1f44d04c1
11 changed files with 578 additions and 0 deletions

69
scilog/scicat.py Normal file
View File

@ -0,0 +1,69 @@
import getpass
from .config import Config
from .utils import post_request, get_request
from .autherror import AuthError
AUTH_HEADERS = {
"Content-type": "application/json",
"Accept": "application/json"
}
class SciCat:
def __init__(self, address):
self.address = address.rstrip("/")
self._token = None
self.config = Config(".scicat-tokens")
def __repr__(self):
return f"SciCat @ {self.address}"
@property
def proposals(self):
url = self.address + "/proposals"
headers = self.auth_headers
return get_request(url, headers=headers)
@property
def auth_headers(self):
headers = AUTH_HEADERS.copy()
headers["Authorization"] = self.token
return headers
@property
def token(self):
username = getpass.getuser()
password = getpass.getpass(prompt=f"SciCat password for {username}: ")
token = self._token
if token is None:
try:
token = self.config[username]
except KeyError:
token = self.authenticate(username, password)
self.config[username] = self._token = token
return token
def authenticate(self, username, password):
url = self.address + "/users/login"
auth_payload = {
"username": username,
"password": password
}
res = post_request(url, auth_payload, AUTH_HEADERS)
try:
token = res["id"]
except KeyError as e:
raise SciCatAuthError(res) from e
else:
return token
class SciCatAuthError(AuthError):
pass