Skip to content

Commit

Permalink
chore: add mkdocs and reuseable workflows (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
hairmare authored Feb 18, 2023
1 parent 8607f39 commit f455ab6
Show file tree
Hide file tree
Showing 11 changed files with 705 additions and 128 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/lint-and-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ on:
- gh-pages

jobs:
call-workflow:
uses: radiorabe/actions/.github/workflows/test-pre-commit.yaml@main
pre-commit:
uses: radiorabe/actions/.github/workflows/test-pre-commit.yaml@v0.7.0
pytest:
uses: radiorabe/actions/.github/workflows/test-python-poetry.yaml@main
uses: radiorabe/actions/.github/workflows/test-python-poetry.yaml@v0.7.0
41 changes: 6 additions & 35 deletions .github/workflows/release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,13 @@ name: Release

on:
pull_request:
push:
branches: [main]
release:
types: [created]

jobs:
pypi:

runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0

- run: pipx install poetry

- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.x'
cache: 'poetry'

- run: poetry install

- name: Configure poetry
run: poetry config pypi-token.pypi ${{ secrets.RABE_PYPI_TOKEN }}
if: ${{ github.event_name != 'pull_request' }}

- name: Set dry-run flag
id: dry-run
run: |
flag="--dry-run"
if ${{ github.event_name != 'pull_request' }}
then
flag=""
fi
echo "flag=$flag" >> $GITHUB_OUTPUT
- run: poetry version $(git describe --tags --abbrev=0 --exact-match || (git describe --tags --abbrev=0 --dirty=+dev|tr -d '\n'; echo "+dev"))

- run: poetry publish --build --no-interaction ${{ steps.dry-run.outputs.flag }}
python-poetry:
uses: radiorabe/actions/.github/workflows/release-python-poetry.yaml@v0.7.0
secrets:
RABE_PYPI_TOKEN: ${{ secrets.RABE_PYPI_TOKEN }}
2 changes: 1 addition & 1 deletion .github/workflows/semantic-release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ on:

jobs:
call-workflow:
uses: radiorabe/actions/.github/workflows/semantic-release.yaml@main
uses: radiorabe/actions/.github/workflows/semantic-release.yaml@v0.7.0
secrets:
RABE_ITREAKTION_GITHUB_TOKEN: ${{ secrets.RABE_ITREAKTION_GITHUB_TOKEN }}
18 changes: 18 additions & 0 deletions acrclient/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,19 @@
"""
Get started by importing the Client
```python
>>> from acrclient import Client
```
Create an instance and pass it a bearer token:
```python
>>> client = Client("bearer-token")
```
See [`Client`](./client/#acrclient.client.Client) for available methods and options.
"""
from .client import Client
100 changes: 71 additions & 29 deletions acrclient/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,55 +22,60 @@ def __call__(self, request: PreparedRequest) -> PreparedRequest:


class Client:
"""ACRCloud client to fetch metadata.
"""Client class with various methods to call ACRCloud API v2 endpoints.
>>> bearer_token = "bearer-token"
>>> config = Client.Config(retries= 5, backoff_factor= 0.1)
>>> client = Client(bearer_token, config=config)
Examples:
Create an instance with configuration.
```python
>>> bearer_token = "bearer-token"
>>> config = Client.Config(retries= 5, backoff_factor= 0.1)
>>> client = Client(bearer_token, config=config)
:param str bearer_token
The bearer token for ACRCloud.
```
"""

class Config:
"""Configuration for acrclient.
:param int retries
Total number of retries to allow.
:param float backoff_factor
A backoff factor to apply between attempts after the second try
(most errors are resolved immediately by a second try without a
delay). urllib3 will sleep for::
{backoff factor} * (2 ** ({number of total retries} - 1))
seconds. If the backoff_factor is 0.1, then :func:`Retry.sleep` will sleep
for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer
than `backoff_max`.
By default, backoff is set to 0.1.
"""
"""Configuration for acrclient."""

def __init__(
self,
retries: Union[bool | int | None] = 5,
backoff_factor: float = 0.1,
):
) -> None:
"""
Parameters:
retries: Total number of retries to allow.
backoff_factor: A backoff factor to apply between attempts after the
second try (most errors are resolved immediately by a second try
without a delay). urllib3 will sleep for::
{backoff factor} * (2 ** ({number of total retries} - 1))
seconds. If the backoff_factor is 0.1, then :func:`Retry.sleep`
will sleep for [0.0s, 0.2s, 0.4s, ...] between retries. It will
never be longer than `backoff_max`.
By default, backoff is set to 0.1.
"""
self._retries: Union[bool | int | None] = retries
self._backoff_factor: float = backoff_factor

@property
def retries(self):
def retries(self) -> Union[bool | int | None]:
return self._retries

@property
def backoff_factor(self):
def backoff_factor(self) -> float:
return self._backoff_factor

def __init__(
self,
bearer_token: str,
base_url: str = "https://eu-api-v2.acrcloud.com",
config: Optional[Config] = None,
):
) -> None:
"""
Parameters:
bearer_token: The bearer token for ACRCloud.
"""
self.base_url: str = base_url

self._config: Optional[Client.Config] = config or Client.Config()
Expand All @@ -86,8 +91,21 @@ def __init__(
),
)

def get(self, path: str, params: Any = None, **kwargs) -> Response:
"""Fetch JSON data from ACRCloud API with set Access Key param."""
def get(
self,
path: str,
params: Any = None,
**kwargs: Any,
) -> Response:
"""Fetch JSON data from ACRCloud API with set Access Key param.
Parameters:
path: URL path
params: Parameters for request (usually used as GET params)
**kwargs: Get passed to `requests.get`
Returns:
Response object
"""
url = f"{self.base_url}{path}"
if not kwargs.get("timeout"):
kwargs["timeout"] = 60
Expand All @@ -97,7 +115,21 @@ def get(self, path: str, params: Any = None, **kwargs) -> Response:
response.raise_for_status()
return response

def json(self, path: str, params: Any = None, **kwargs) -> Any:
def json(
self,
path: str,
params: Any = None,
**kwargs: Any,
) -> Any:
"""Get the json results of a get call.
Parameters:
path: URL path
params: Parameters for request (usually used as GET params)
**kwargs: Get passed to `requests.get`
Returns:
Data from API
"""
response = self.get(path, params=params, **kwargs)
return response.json()

Expand All @@ -106,8 +138,18 @@ def get_bm_cs_projects_results(
project_id: int,
stream_id: str,
params: Optional[GetBmCsProjectsResultsParams] = None,
**kwargs,
**kwargs: Any,
) -> Any:
"""Get Custom Broadcast Monitoring Streams Results from ACRCloud.
Parameters:
project_id: Custom Broadcast Monitoring Project ID
stream_id: Custom Broadcast Monitoring Stream ID
params: GET parameters for request
**kwargs: Get passed to `requests.get`
Returns:
Data from API
"""
return self.json(
path=f"/api/bm-cs-projects/{project_id}/streams/{stream_id}/results",
params=params,
Expand Down
13 changes: 13 additions & 0 deletions catalog-info.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
apiVersion: backstage.io/v1alpha1
kind: Component
metadata:
name: acrclient
description: API wrapper for the v2 ACRCloud API
annotations:
backstage.io/techdocs-ref: dir:.
github.com/project-slug: radiorabe/python-acrclient
spec:
type: library
lifecycle: experimental
owner: it-reaktion
10 changes: 10 additions & 0 deletions docs/css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/* set primary color */
:root {
--md-primary-fg-color: #00C9BF;
--md-accent-fg-color: #00C9BF;
}

/* make code selectable on main */
.highlight .o {
user-select: none;
}
40 changes: 40 additions & 0 deletions docs/gen_ref_pages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Generate the code reference pages and navigation.
From https://mkdocstrings.github.io/recipes/
"""

from pathlib import Path

import mkdocs_gen_files

nav = mkdocs_gen_files.Nav()

for path in sorted(Path("acrclient").rglob("*.py")):
module_path = path.relative_to(".").with_suffix("")
doc_path = path.relative_to(".").with_suffix(".md")
full_doc_path = Path("reference", doc_path)

parts = tuple(module_path.parts)

if parts[-1] == "__init__":
parts = parts[:-1]
doc_path = doc_path.with_name("index.md")
full_doc_path = full_doc_path.with_name("index.md")
elif parts[-1] == "__main__":
continue

nav[parts] = doc_path.as_posix()

full_doc_path.parent.mkdir(parents=True, exist_ok=True)
with mkdocs_gen_files.open(full_doc_path, "w") as fd:
ident = ".".join(parts)
fd.write(f"::: {ident}")

mkdocs_gen_files.set_edit_path(full_doc_path, path)

with mkdocs_gen_files.open("reference/SUMMARY.md", "w") as nav_file:
nav_file.writelines(nav.build_literate_nav())

readme = Path("README.md").open("r")
with mkdocs_gen_files.open("index.md", "w") as index_file:
index_file.writelines(readme.read())
54 changes: 54 additions & 0 deletions mkdocs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
site_name: acrclient
repo_url: https://github.com/radiorabe/python-acrclient
repo_name: radiorabe/python-acrclient

theme:
name: "material"
palette:
# Palette toggle for dark mode
- scheme: slate
toggle:
icon: material/brightness-4
name: Switch to light mode
# Palette toggle for light mode
- scheme: default
toggle:
icon: material/brightness-7
name: Switch to dark mode
icon:
repo: fontawesome/brands/git-alt
features:
- content.code.copy
- toc.integrate

markdown_extensions:
- pymdownx.highlight:
anchor_linenums: true
- pymdownx.inlinehilite
- pymdownx.snippets
- pymdownx.superfences

extra_css:
- css/style.css

plugins:
- search
- autorefs
- gen-files:
scripts:
- docs/gen_ref_pages.py
- literate-nav:
nav_file: SUMMARY.md
- section-index
- mkdocstrings:
handlers:
python:
paths: [acrclient]

nav:
- README: index.md
- API Reference: reference/

watch:
- README.md
- acrclient/
Loading

0 comments on commit f455ab6

Please sign in to comment.