first
This commit is contained in:
139
.gitignore
vendored
Normal file
139
.gitignore
vendored
Normal file
@ -0,0 +1,139 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
26
example_scicat.py
Executable file
26
example_scicat.py
Executable file
@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import urllib3
|
||||
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
|
||||
from scicat import SciCat
|
||||
|
||||
url = "https://dacat.psi.ch/api/v3/"
|
||||
cat = SciCat(url)
|
||||
|
||||
props = cat.proposals
|
||||
nprops = len(props)
|
||||
print(f"got {nprops} proposals")
|
||||
|
||||
|
||||
for prop in props:
|
||||
# print(prop)
|
||||
pgroup = prop["ownerGroup"]
|
||||
pi_first = prop["pi_firstname"]
|
||||
pi_last = prop["pi_lastname"]
|
||||
first = prop["firstname"]
|
||||
last = prop["lastname"]
|
||||
print(pgroup, pi_first, pi_last, first, last)
|
||||
|
4
scicat/__init__.py
Normal file
4
scicat/__init__.py
Normal file
@ -0,0 +1,4 @@
|
||||
|
||||
from .scicat import SciCat
|
||||
|
||||
|
52
scicat/authmixin.py
Normal file
52
scicat/authmixin.py
Normal file
@ -0,0 +1,52 @@
|
||||
import getpass
|
||||
from abc import ABC, abstractmethod
|
||||
from .config import Config
|
||||
from .utils import typename
|
||||
|
||||
|
||||
HEADER_JSON = {
|
||||
"Content-type": "application/json",
|
||||
"Accept": "application/json"
|
||||
}
|
||||
|
||||
|
||||
class AuthMixin(ABC):
|
||||
|
||||
def __init__(self, address):
|
||||
self.address = address.rstrip("/")
|
||||
self._token = None
|
||||
tn = typename(self).lower()
|
||||
self.config = Config(f".{tn}-tokens")
|
||||
|
||||
def __repr__(self):
|
||||
tn = typename(self)
|
||||
return f"{tn} @ {self.address}"
|
||||
|
||||
@abstractmethod
|
||||
def authenticate(self, username, password):
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
def token(self):
|
||||
return self._retrieve_token()
|
||||
|
||||
def _retrieve_token(self):
|
||||
username = input("Username: ")
|
||||
token = self._token
|
||||
if token is None:
|
||||
try:
|
||||
token = self.config[username]
|
||||
except KeyError:
|
||||
tn = typename(self)
|
||||
password = getpass.getpass(prompt=f"{tn} password for {username}: ")
|
||||
token = self.authenticate(username, password)
|
||||
self.config[username] = self._token = token
|
||||
return token
|
||||
|
||||
|
||||
|
||||
class AuthError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
|
47
scicat/config.py
Normal file
47
scicat/config.py
Normal file
@ -0,0 +1,47 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
|
||||
class Config(dict):
|
||||
|
||||
def __init__(self, fname, folder=None):
|
||||
if folder is not None:
|
||||
folder = Path(folder)
|
||||
else:
|
||||
folder = Path.home()
|
||||
self.fname = folder / fname
|
||||
content = self._load()
|
||||
super().__init__(content)
|
||||
|
||||
def __setitem__(self, name, value):
|
||||
self.update(**{name: value})
|
||||
|
||||
def update(self, **kwargs):
|
||||
super().update(**kwargs)
|
||||
self._save()
|
||||
|
||||
def _load(self):
|
||||
fn = self.fname
|
||||
if fn.exists():
|
||||
return json_load(fn)
|
||||
else:
|
||||
return {}
|
||||
|
||||
def _save(self):
|
||||
json_save(self, self.fname)
|
||||
|
||||
def delete(self):
|
||||
self.fname.unlink()
|
||||
|
||||
|
||||
|
||||
def json_save(what, filename, *args, indent=4, sort_keys=True, **kwargs):
|
||||
with open(filename, "w") as f:
|
||||
json.dump(what, f, *args, indent=indent, sort_keys=sort_keys, **kwargs)
|
||||
|
||||
def json_load(filename, *args, **kwargs):
|
||||
with open(filename, "r") as f:
|
||||
return json.load(f, *args, **kwargs)
|
||||
|
||||
|
||||
|
78
scicat/httpclient.py
Normal file
78
scicat/httpclient.py
Normal file
@ -0,0 +1,78 @@
|
||||
import functools
|
||||
import json
|
||||
import requests
|
||||
|
||||
from .authmixin import AuthMixin, AuthError, HEADER_JSON
|
||||
|
||||
|
||||
def authenticated(func):
|
||||
@functools.wraps(func)
|
||||
def authenticated_call(client, *args, **kwargs):
|
||||
if not isinstance(client, HttpClient):
|
||||
raise AttributeError("First argument must be an instance of HttpClient")
|
||||
if "headers" in kwargs:
|
||||
kwargs["headers"] = kwargs["headers"].copy()
|
||||
else:
|
||||
kwargs["headers"] = {}
|
||||
kwargs["headers"]["Authorization"] = client.token
|
||||
return func(client, *args, **kwargs)
|
||||
return authenticated_call
|
||||
|
||||
|
||||
class HttpClient(AuthMixin):
|
||||
|
||||
def __init__(self, address):
|
||||
self.address = address
|
||||
self._verify_certificate = True
|
||||
self.login_path = self.address + "/users/login"
|
||||
super().__init__(address)
|
||||
|
||||
def authenticate(self, username, password):
|
||||
auth_payload = {
|
||||
"principal": username,
|
||||
"password": password
|
||||
}
|
||||
res = self._login(auth_payload, HEADER_JSON)
|
||||
try:
|
||||
token = "Bearer " + res["token"]
|
||||
except KeyError as e:
|
||||
raise AuthError(res) from e
|
||||
else:
|
||||
return token
|
||||
|
||||
@authenticated
|
||||
def get_request(self, url, params=None, headers=None, timeout=10):
|
||||
response = requests.get(url, params=params, headers=headers, timeout=timeout, verify=self._verify_certificate)
|
||||
if response.ok:
|
||||
return response.json()
|
||||
else:
|
||||
if response.reason == "Unauthorized":
|
||||
self.config.delete()
|
||||
raise response.raise_for_status()
|
||||
|
||||
@authenticated
|
||||
def post_request(self, url, payload=None, headers=None, timeout=10):
|
||||
return requests.post(url, json=payload, headers=headers, timeout=timeout, verify=self._verify_certificate).json()
|
||||
|
||||
def _login(self, payload=None, headers=None, timeout=10):
|
||||
return requests.post(self.login_path, json=payload, headers=headers, timeout=timeout, verify=self._verify_certificate).json()
|
||||
|
||||
@staticmethod
|
||||
def make_filter(where:dict=None, limit:int=0, skip:int=0, fields:dict=None, include:dict=None, order:list=None):
|
||||
filt = dict()
|
||||
if where is not None:
|
||||
items = [where.copy()]
|
||||
filt["where"] = {"and": items}
|
||||
if limit > 0:
|
||||
filt["limit"] = limit
|
||||
if skip > 0:
|
||||
filt["skip"] = skip
|
||||
if fields is not None:
|
||||
filt["fields"] = include
|
||||
if order is not None:
|
||||
filt["order"] = order
|
||||
filt = json.dumps(filt)
|
||||
return {"filter": filt}
|
||||
|
||||
|
||||
|
46
scicat/scicat.py
Normal file
46
scicat/scicat.py
Normal file
@ -0,0 +1,46 @@
|
||||
from .authmixin import AuthMixin, AuthError, HEADER_JSON
|
||||
from .httpclient import HttpClient
|
||||
|
||||
|
||||
class SciCatRestAPI(HttpClient):
|
||||
|
||||
def __init__(self, url):
|
||||
super().__init__(url)
|
||||
# self.login_path = "https://dacat.psi.ch/auth/msad"
|
||||
self.login_path = "https://dacat.psi.ch/api/v3/users/login"
|
||||
|
||||
def authenticate(self, username, password):
|
||||
auth_payload = {
|
||||
"username": username,
|
||||
"password": password
|
||||
}
|
||||
res = self._login(auth_payload, HEADER_JSON)
|
||||
if res == "authentication error":
|
||||
raise SciCatAuthError(res)
|
||||
try:
|
||||
# token = res["access_token"]
|
||||
token = res["id"]
|
||||
except KeyError as e:
|
||||
raise SciCatAuthError(res) from e
|
||||
else:
|
||||
return token
|
||||
|
||||
|
||||
|
||||
class SciCat():
|
||||
|
||||
def __init__(self, url="https://dacat.psi.ch/api/v3/"):
|
||||
self.http_client = SciCatRestAPI(url)
|
||||
|
||||
@property
|
||||
def proposals(self):
|
||||
url = self.http_client.address + "/proposals"
|
||||
return self.http_client.get_request(url, headers=HEADER_JSON)
|
||||
|
||||
|
||||
|
||||
class SciCatAuthError(AuthError):
|
||||
pass
|
||||
|
||||
|
||||
|
20
scicat/utils.py
Normal file
20
scicat/utils.py
Normal file
@ -0,0 +1,20 @@
|
||||
import requests
|
||||
|
||||
|
||||
#TODO: add params/payload and response validation
|
||||
|
||||
|
||||
def get_request(url, params=None, headers=None, timeout=10):
|
||||
response = requests.get(url, params=params, headers=headers, timeout=timeout, verify=False).json()
|
||||
return response
|
||||
|
||||
def post_request(url, payload=None, headers=None, timeout=10):
|
||||
response = requests.post(url, json=payload, headers=headers, timeout=timeout, verify=False).json()
|
||||
return response
|
||||
|
||||
|
||||
def typename(obj):
|
||||
return type(obj).__name__
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user