kopia lustrzana https://github.com/bugout-dev/moonstream
[WIP] Started working on Moonstream Python client
rodzic
d23313c9d1
commit
9ccbe7462c
|
@ -0,0 +1,147 @@
|
|||
# Created by https://www.toptal.com/developers/gitignore/api/python
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=python
|
||||
|
||||
### Python ###
|
||||
# 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/
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/python
|
||||
|
||||
.moonstream-py/
|
||||
.venv/
|
|
@ -0,0 +1,13 @@
|
|||
# Moonstream Python client
|
||||
|
||||
This is the Python client library for the Moonstream API.
|
||||
|
||||
## Installation
|
||||
|
||||
This library assumes you are using Python 3.6 or greater.
|
||||
|
||||
Install using `pip`:
|
||||
|
||||
```bash
|
||||
pip install moonstream
|
||||
```
|
|
@ -0,0 +1,85 @@
|
|||
from dataclasses import dataclass, field
|
||||
import logging
|
||||
import os
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import requests
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
log_level = logging.INFO
|
||||
if os.environ.get("DEBUG", "").lower() in ["true", "1"]:
|
||||
log_level = logging.DEBUG
|
||||
logger.setLevel(log_level)
|
||||
|
||||
|
||||
def moonstream_endpoints(url: str) -> Dict[str, str]:
|
||||
"""
|
||||
Creates a dictionary of Moonstream API endpoints at the given Moonstream API URL.
|
||||
"""
|
||||
url_with_protocol = url
|
||||
if not (
|
||||
url_with_protocol.startswith("http://")
|
||||
or url_with_protocol.startswith("https://")
|
||||
):
|
||||
url_with_protocol = f"http://{url_with_protocol}"
|
||||
|
||||
normalized_url = url_with_protocol.rstrip("/")
|
||||
|
||||
endpoints = ["/ping", "/version", "/now"]
|
||||
|
||||
return {endpoint: f"{normalized_url}{endpoint}" for endpoint in endpoints}
|
||||
|
||||
|
||||
class UnexpectedResponse(Exception):
|
||||
"""
|
||||
Raised when a server response cannot be parsed into the appropriate/expected Python structure.
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class APISpec:
|
||||
url: str
|
||||
endpoints: Dict[str, str]
|
||||
|
||||
|
||||
class Moonstream:
|
||||
"""
|
||||
A Moonstream client configured to communicate with a given Moonstream API server.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, url: str = "https://api.moonstream.to", timeout: Optional[float] = None
|
||||
):
|
||||
endpoints = moonstream_endpoints(url)
|
||||
self.api = APISpec(url=url, endpoints=endpoints)
|
||||
self.timeout = timeout
|
||||
self._session = requests.Session()
|
||||
|
||||
def ping(self) -> Dict[str, Any]:
|
||||
r = self._session.get(self.api.endpoints["/ping"])
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
def version(self) -> Dict[str, Any]:
|
||||
r = self._session.get(self.api.endpoints["/version"])
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
def server_time(self) -> float:
|
||||
r = self._session.get(self.api.endpoints["/now"])
|
||||
r.raise_for_status()
|
||||
result = r.json()
|
||||
raw_epoch_time = result.get("epoch_time")
|
||||
if raw_epoch_time is None:
|
||||
raise UnexpectedResponse(
|
||||
f'Server response does not contain "epoch_time": {result}'
|
||||
)
|
||||
|
||||
try:
|
||||
epoch_time = float(raw_epoch_time)
|
||||
except:
|
||||
raise UnexpectedResponse(
|
||||
f"Could not process epoch time as a float: {raw_epoch_time}"
|
||||
)
|
||||
|
||||
return epoch_time
|
|
@ -0,0 +1,90 @@
|
|||
from dataclasses import FrozenInstanceError
|
||||
import unittest
|
||||
|
||||
from . import client
|
||||
|
||||
|
||||
class TestMoonstreamClient(unittest.TestCase):
|
||||
def test_client_init(self):
|
||||
m = client.Moonstream()
|
||||
self.assertEqual(m.api.url, "https://api.moonstream.to")
|
||||
self.assertIsNone(m.timeout)
|
||||
self.assertGreater(len(m.api.endpoints), 0)
|
||||
|
||||
def test_client_init_with_timeout(self):
|
||||
timeout = 7
|
||||
m = client.Moonstream(timeout=timeout)
|
||||
self.assertEqual(m.api.url, "https://api.moonstream.to")
|
||||
self.assertEqual(m.timeout, timeout)
|
||||
self.assertGreater(len(m.api.endpoints), 0)
|
||||
|
||||
def test_client_with_custom_url_and_timeout(self):
|
||||
timeout = 9
|
||||
url = "https://my.custom.api.url"
|
||||
m = client.Moonstream(url=url, timeout=timeout)
|
||||
self.assertEqual(m.api.url, url)
|
||||
self.assertEqual(m.timeout, timeout)
|
||||
self.assertGreater(len(m.api.endpoints), 0)
|
||||
|
||||
def test_client_with_custom_messy_url_and_timeout(self):
|
||||
timeout = 3.5
|
||||
url = "https://my.custom.api.url/"
|
||||
m = client.Moonstream(url=url, timeout=timeout)
|
||||
self.assertEqual(m.api.url, url)
|
||||
self.assertEqual(m.timeout, timeout)
|
||||
self.assertGreater(len(m.api.endpoints), 0)
|
||||
|
||||
def test_client_with_custom_messy_url_no_protocol_and_timeout(self):
|
||||
timeout = 5.5
|
||||
url = "my.custom.api.url/"
|
||||
m = client.Moonstream(url=url, timeout=timeout)
|
||||
self.assertEqual(m.api.url, url)
|
||||
self.assertEqual(m.timeout, timeout)
|
||||
self.assertGreater(len(m.api.endpoints), 0)
|
||||
|
||||
def test_immutable_api_url(self):
|
||||
m = client.Moonstream()
|
||||
with self.assertRaises(FrozenInstanceError):
|
||||
m.api.url = "lol"
|
||||
|
||||
def test_immutable_api_endpoints(self):
|
||||
m = client.Moonstream()
|
||||
with self.assertRaises(FrozenInstanceError):
|
||||
m.api.endpoints = {}
|
||||
|
||||
def test_mutable_timeout(self):
|
||||
original_timeout = 5.0
|
||||
updated_timeout = 10.5
|
||||
m = client.Moonstream(timeout=original_timeout)
|
||||
self.assertEqual(m.timeout, original_timeout)
|
||||
m.timeout = updated_timeout
|
||||
self.assertEqual(m.timeout, updated_timeout)
|
||||
|
||||
|
||||
class TestMoonstreamEndpoints(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.url = "https://api.moonstream.to"
|
||||
self.normalized_url = "https://api.moonstream.to"
|
||||
|
||||
def test_moonstream_endpoints(self):
|
||||
endpoints = client.moonstream_endpoints(self.url)
|
||||
self.assertDictEqual(
|
||||
endpoints,
|
||||
{
|
||||
"/ping": f"{self.normalized_url}/ping",
|
||||
"/version": f"{self.normalized_url}/version",
|
||||
"/now": f"{self.normalized_url}/now",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class TestMoonstreamEndpointsMessyURL(TestMoonstreamEndpoints):
|
||||
def setUp(self):
|
||||
self.url = "https://api.moonstream.to/"
|
||||
self.normalized_url = "https://api.moonstream.to"
|
||||
|
||||
|
||||
class TestMoonstreamEndpointsMessyURLWithNoProtocol(TestMoonstreamEndpoints):
|
||||
def setUp(self):
|
||||
self.url = "api.moonstream.to/"
|
||||
self.normalized_url = "http://api.moonstream.to"
|
|
@ -0,0 +1,38 @@
|
|||
from setuptools import find_packages, setup
|
||||
|
||||
long_description = ""
|
||||
with open("README.md") as ifp:
|
||||
long_description = ifp.read()
|
||||
|
||||
setup(
|
||||
name="moonstream",
|
||||
version="0.2.7",
|
||||
packages=find_packages(),
|
||||
package_data={"moonstream": ["py.typed"]},
|
||||
install_requires=[
|
||||
"requests",
|
||||
"dataclasses; python_version=='3.6'"
|
||||
],
|
||||
extras_require={
|
||||
"dev": [
|
||||
"black",
|
||||
"mypy",
|
||||
"wheel",
|
||||
"types-requests",
|
||||
"types-dataclasses",
|
||||
],
|
||||
"distribute": ["setuptools", "twine", "wheel"],
|
||||
},
|
||||
description="Moonstream: Open source blockchain analytics",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
author="Moonstream",
|
||||
author_email="engineering@moonstream.to",
|
||||
classifiers=[
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Programming Language :: Python",
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Topic :: Software Development :: Libraries",
|
||||
],
|
||||
url="https://github.com/bugout-dev/moonstream",
|
||||
)
|
Ładowanie…
Reference in New Issue