Skip to content

Commit

Permalink
Add an option to set apikey via commandline argument
Browse files Browse the repository at this point in the history
Add samples, and update runbook
  • Loading branch information
dormant-user committed Aug 11, 2024
1 parent 7b1ea5e commit 9046ff0
Show file tree
Hide file tree
Showing 16 changed files with 108 additions and 10 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ doc_gen/_*

temp.py

# work in progress
samples/
logging.ini
*.log

!samples/*
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ pyninja start
- **WORKERS** - Number of workers for the uvicorn server.
- **APIKEY** - API Key for authentication.

> `PyNinja` supports [logging.ini] configuration for custom logging. Just place it in the current working directory.<br>
> Refer [samples] directory for examples.
## Coding Standards
Docstring format: [`Google`][google-docs] <br>
Styling conventions: [`PEP 8`][pep8] and [`isort`][isort]
Expand Down Expand Up @@ -132,3 +135,5 @@ Licensed under the [MIT License][license]
[pypi-repo]: https://packaging.python.org/tutorials/packaging-projects/
[license]: https://github.com/thevickypedia/PyNinja/blob/master/LICENSE
[runbook]: https://thevickypedia.github.io/PyNinja/
[samples]: https://github.com/thevickypedia/PyNinja/tree/main/samples
[logging.ini]: https://docs.python-guide.org/writing/logging/#example-configuration-via-an-ini-file
4 changes: 4 additions & 0 deletions docs/README.html
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ <h2>Environment Variables<a class="headerlink" href="#environment-variables" tit
<li><p><strong>WORKERS</strong> - Number of workers for the uvicorn server.</p></li>
<li><p><strong>APIKEY</strong> - API Key for authentication.</p></li>
</ul>
<blockquote>
<div><p><code class="docutils literal notranslate"><span class="pre">PyNinja</span></code> supports <a class="reference external" href="https://docs.python-guide.org/writing/logging/#example-configuration-via-an-ini-file">logging.ini</a> configuration for custom logging. Just place it in the current working directory.<br>
Refer <a class="reference external" href="https://github.com/thevickypedia/PyNinja/tree/main/samples">samples</a> directory for examples.</p>
</div></blockquote>
</section>
<section id="coding-standards">
<h2>Coding Standards<a class="headerlink" href="#coding-standards" title="Permalink to this heading"></a></h2>
Expand Down
5 changes: 5 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ pyninja start
- **WORKERS** - Number of workers for the uvicorn server.
- **APIKEY** - API Key for authentication.

> `PyNinja` supports [logging.ini] configuration for custom logging. Just place it in the current working directory.<br>
> Refer [samples] directory for examples.
## Coding Standards
Docstring format: [`Google`][google-docs] <br>
Styling conventions: [`PEP 8`][pep8] and [`isort`][isort]
Expand Down Expand Up @@ -132,3 +135,5 @@ Licensed under the [MIT License][license]
[pypi-repo]: https://packaging.python.org/tutorials/packaging-projects/
[license]: https://github.com/thevickypedia/PyNinja/blob/master/LICENSE
[runbook]: https://thevickypedia.github.io/PyNinja/
[samples]: https://github.com/thevickypedia/PyNinja/tree/main/samples
[logging.ini]: https://docs.python-guide.org/writing/logging/#example-configuration-via-an-ini-file
5 changes: 5 additions & 0 deletions docs/_sources/README.md.txt
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ pyninja start
- **WORKERS** - Number of workers for the uvicorn server.
- **APIKEY** - API Key for authentication.

> `PyNinja` supports [logging.ini] configuration for custom logging. Just place it in the current working directory.<br>
> Refer [samples] directory for examples.

## Coding Standards
Docstring format: [`Google`][google-docs] <br>
Styling conventions: [`PEP 8`][pep8] and [`isort`][isort]
Expand Down Expand Up @@ -132,3 +135,5 @@ Licensed under the [MIT License][license]
[pypi-repo]: https://packaging.python.org/tutorials/packaging-projects/
[license]: https://github.com/thevickypedia/PyNinja/blob/master/LICENSE
[runbook]: https://thevickypedia.github.io/PyNinja/
[samples]: https://github.com/thevickypedia/PyNinja/tree/main/samples
[logging.ini]: https://docs.python-guide.org/writing/logging/#example-configuration-via-an-ini-file
2 changes: 1 addition & 1 deletion docs/searchindex.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion pyninja/__init__.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
"""Placeholder for packaging."""

import os
import sys

import click

from pyninja.main import start, version # noqa: F401
from pyninja.main import start # noqa: F401

version = "0.0.0"


@click.command()
@click.argument("start", required=False)
@click.argument("run", required=False)
@click.option("--version", "-V", is_flag=True, help="Prints the version.")
@click.option("--help", "-H", is_flag=True, help="Prints the help section.")
@click.option("--apikey", "-A", help="APIkey for the server.")
@click.option(
"--env",
"-E",
Expand All @@ -24,6 +28,7 @@ def commandline(*args, **kwargs) -> None:
**Flags**
- ``--version | -V``: Prints the version.
- ``--help | -H``: Prints the help section.
- ``--apikey | -A``: Takes the apikey as a commandline argument.
- ``--env | -E``: Environment configuration filepath.
**Commands**
Expand All @@ -33,6 +38,7 @@ def commandline(*args, **kwargs) -> None:
options = {
"--version | -V": "Prints the version.",
"--help | -H": "Prints the help section.",
"--apikey | -A": "APIkey for the server.",
"--env | -E": "Environment configuration filepath.",
"start | run": "Initiates the backup process.",
}
Expand All @@ -51,6 +57,8 @@ def commandline(*args, **kwargs) -> None:
f"\nUsage: pyninja [arbitrary-command]\nOptions (and corresponding behavior):{choices}"
)
sys.exit(0)
if kwargs.get("apikey"):
os.environ["apikey"] = kwargs.get("apikey")
trigger = kwargs.get("start") or kwargs.get("run")
if trigger and trigger.lower() in ("start", "run"):
# Click doesn't support assigning defaults like traditional dictionaries, so kwargs.get("max", 100) won't work
Expand Down
5 changes: 2 additions & 3 deletions pyninja/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
import uvicorn
from fastapi import FastAPI

import pyninja
from pyninja import routers, squire

version = "0.0.0"


def start(env_file: str = None) -> None:
"""Starter function for the API, which uses uvicorn server as trigger.
Expand All @@ -21,7 +20,7 @@ def start(env_file: str = None) -> None:
routes=routers.routes,
title="PyNinja",
description="Light weight OS agnostic service monitoring API",
version=version,
version=pyninja.version,
)
kwargs = dict(
host=squire.env.ninja_host,
Expand Down
4 changes: 2 additions & 2 deletions pyninja/routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from pyninja import auth, exceptions, service, squire

LOGGER = logging.getLogger("uvicorn")
LOGGER = logging.getLogger(__name__)


async def service_status(payload: squire.StatusPayload):
Expand Down Expand Up @@ -39,7 +39,7 @@ async def docs():

routes = [
APIRoute(
path="/status",
path="/service-status",
endpoint=service_status,
methods=["POST"],
dependencies=[Depends(auth.authenticator)],
Expand Down
1 change: 0 additions & 1 deletion pyninja/version.py

This file was deleted.

1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
click==8.1.7
fastapi==0.112.0
psutil==6.0.0
pydantic==2.8.2
Expand Down
4 changes: 4 additions & 0 deletions samples/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
NINJA_HOST="0.0.0.0"
NINJA_PORT=8005
APIKEY="MySecreatAccessToken"
WORKERS=3
31 changes: 31 additions & 0 deletions samples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
## Sample Environment Variables

Environment variables can be sourced using any `plaintext` / `JSON` / `YAML` file.
The filepath should be provided as an argument during object instantiation.

⚠️ Sample values are randomly generated strings from https://pinetools.com/random-string-generator

> By default, `PyNinja` will look for a `.env` file in the current working directory.
### Examples

- PlainText: [.env]
- JSON: [secrets.json]
- YAML: [secrets.yaml]

[.env]: .env
[secrets.json]: secrets.json
[secrets.yaml]: secrets.yaml

### Usage

- **CLI**
```shell
pyninja --env "/path/to/env/file" start
```

- **IDE**
```python
import pyninja
pyninja.start(env_file='/path/to/env/file')
```
27 changes: 27 additions & 0 deletions samples/logging.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[loggers]
keys=root

[handlers]
keys=logfile,logconsole

[formatters]
keys=logformatter

[logger_root]
level=INFO
handlers=logfile, logconsole

[formatter_logformatter]
format=[%(asctime)s.%(msecs)03d] %(levelname)s [%(thread)d] - %(message)s

[handler_logfile]
class=handlers.RotatingFileHandler
level=INFO
args=('logfile.log','a')
formatter=logformatter

[handler_logconsole]
class=handlers.logging.StreamHandler
level=INFO
args=()
formatter=logformatter
6 changes: 6 additions & 0 deletions samples/secrets.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"NINJA_HOST": "0.0.0.0",
"NINJA_PORT": 8005,
"APIKEY": "MySecreatAccessToken",
"WORKERS": 3
}
4 changes: 4 additions & 0 deletions samples/secrets.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
APIKEY: MySecreatAccessToken
NINJA_HOST: 0.0.0.0
NINJA_PORT: 8005
WORKERS: 3

0 comments on commit 9046ff0

Please sign in to comment.