Skip to content

Commit

Permalink
Merge branch 'rl-1.0.3'
Browse files Browse the repository at this point in the history
  • Loading branch information
amenezes committed Nov 12, 2023
2 parents 868f539 + d00facc commit 1f733a4
Show file tree
Hide file tree
Showing 17 changed files with 126 additions and 84 deletions.
30 changes: 0 additions & 30 deletions .codeclimate.yml

This file was deleted.

6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
exclude: >
(?x)(
^mkdocs.yml$|
^examples/|
)
fail_fast: false
repos:
- repo: local
Expand Down
1 change: 1 addition & 0 deletions .tool-versions
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python 3.11.2
7 changes: 1 addition & 6 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,12 @@ ci: lint tests
ifeq ($(GITHUB_HEAD_REF), false)
@echo "--- codecov report ---"
codecov --file coverage.xml -t $$CODECOV_TOKEN
@echo "--- codeclimate report ---"
curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
chmod +x ./cc-test-reporter
./cc-test-reporter format-coverage -t coverage.py -o codeclimate.json
./cc-test-reporter upload-coverage -i codeclimate.json -r $$CC_TEST_REPORTER_ID
endif

docs:
@echo "> generate project documentation..."
@cp README.md docs/index.md
mkdocs serve
mkdocs serve -a 0.0.0.0:8000

tox:
@echo "> running tox..."
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ HTTP engine options available:
- aiohttp `default`;
- httpx.

## Installing
## Using

Install and update using pip:

Expand Down
2 changes: 1 addition & 1 deletion discovery/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
)
from .client import Consul

__version__ = "1.0.2"
__version__ = "1.0.3"
__all__ = [
"Consul",
"HealthState",
Expand Down
2 changes: 0 additions & 2 deletions discovery/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ def http(
interval: str = "10s",
timeout: str = "5s",
deregister_after: str = "1m",
disable_redirects: bool = True,
) -> dict:
name = name or f"http-{uuid4().hex}"
header = header or {}
Expand All @@ -35,7 +34,6 @@ def http(
method=method,
header=header,
body=body,
disable_redirects=disable_redirects,
interval=interval,
timeout=timeout,
deregister_critical_service_after=deregister_after,
Expand Down
40 changes: 19 additions & 21 deletions discovery/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def status(leader, peers, verbose):
try:
if leader:
resp = loop.run_until_complete(consul.status.leader())
elif peers:
else:
resp = loop.run_until_complete(consul.status.leader())
except Exception as err:
console.print(f"[red][*][/red] Failed to process request: [details='{err}']")
Expand All @@ -57,11 +57,7 @@ def catalog(services, datacenters, nodes, verbose):
_show_verbose()

try:
if services:
resp = loop.run_until_complete(consul.catalog.list_services())
for i, svc in enumerate(resp, start=1):
table.add_row(f"{i}[yellow]:[/yellow]", svc)
elif datacenters:
if datacenters:
resp = loop.run_until_complete(consul.catalog.list_datacenters())
for i, dc in enumerate(resp, start=1):
table.add_row(f"{i}[yellow]:[/yellow]", dc)
Expand All @@ -80,6 +76,10 @@ def catalog(services, datacenters, nodes, verbose):
table.add_row(
f"{i}[yellow]:[/yellow]", node["Node"], node["Address"]
)
else:
resp = loop.run_until_complete(consul.catalog.list_services())
for i, svc in enumerate(resp, start=1):
table.add_row(f"{i}[yellow]:[/yellow]", svc)
except Exception as err:
console.print(f"[red][*][/red] Failed to process request: [details='{err}']")
raise SystemExit
Expand All @@ -93,29 +93,27 @@ def catalog(services, datacenters, nodes, verbose):


@cli.command()
@click.option("-n", "--node", help="Node name.")
@click.option("-s", "--service", help="Service name.")
@click.option("--state", help="State name.")
@click.argument("argument")
@click.option("-n", "--node", is_flag=True, help="List checks for node.")
@click.option("-s", "--service", is_flag=True, help="List checks for service.")
@click.option("--state", is_flag=True, help="List checks for state.")
@click.option("-v", "--verbose", is_flag=True, help="Extend output info.")
def health(node, service, state, verbose):
def health(argument, node, service, state, verbose):
"""Health API."""
if verbose:
_show_verbose()

try:
if node:
resp = loop.run_until_complete(consul.health.checks_for_node(node))
resp = loop.run_until_complete(consul.health.checks_for_node(argument))
elif service:
resp = loop.run_until_complete(consul.health.checks_for_service(service))
resp = loop.run_until_complete(consul.health.checks_for_service(argument))
elif state:
resp = loop.run_until_complete(consul.health.checks_in_state(state))
resp = loop.run_until_complete(consul.health.checks_in_state(argument))
except Exception as err:
console.print(f"[red][*][/red] Failed to process request: [details='{err}']")
raise SystemExit
console.print(
resp
# f"{highlight(json.dumps(resp, indent=4, sort_keys=True), JsonLexer(), TerminalFormatter())}"
)
console.print(resp)


@cli.command()
Expand All @@ -128,12 +126,12 @@ def raft(read, delete, verbose):
_show_verbose()

try:
if read:
resp = loop.run_until_complete(consul.operator.raft.read_configuration())
console.print(resp)
elif delete:
if delete:
resp = loop.run_until_complete(consul.operator.raft.delete_peer())
console.print(resp)
else:
resp = loop.run_until_complete(consul.operator.raft.read_configuration())
console.print(resp)
except Exception as err:
console.print(f"[red][*][/red] Failed to process request: [details='{err}']")
raise SystemExit
Expand Down
16 changes: 8 additions & 8 deletions discovery/engine/aiohttp/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ def __init__(self, *args, **kwargs) -> None:

@asynccontextmanager
async def get(self, *args, **kwargs):
log.debug(f"args: {args}")
log.debug(f"kwargs: {kwargs}")
log.debug(f"GET: {args}")
log.debug(f"get_kwargs: {kwargs}")
async with ClientSession(**self._session_kwargs) as session:
log.debug(f"session_kwargs: {self._session_kwargs}")
response = await session.get(*args, **kwargs)
Expand All @@ -30,8 +30,8 @@ async def get(self, *args, **kwargs):

@asynccontextmanager
async def put(self, *args, **kwargs):
log.debug(f"args: {args}")
log.debug(f"kwargs: {kwargs}")
log.debug(f"PUT: {args}")
log.debug(f"put_kwargs: {kwargs}")
async with ClientSession(**self._session_kwargs) as session:
log.debug(f"session_kwargs: {self._session_kwargs}")
response = await session.put(*args, **kwargs)
Expand All @@ -40,8 +40,8 @@ async def put(self, *args, **kwargs):

@asynccontextmanager
async def delete(self, *args, **kwargs):
log.debug(f"args: {args}")
log.debug(f"kwargs: {kwargs}")
log.debug(f"DELETE: {args}")
log.debug(f"delete_kwargs: {kwargs}")
async with ClientSession(**self._session_kwargs) as session:
log.debug(f"session_kwargs: {self._session_kwargs}")
response = await session.delete(*args, **kwargs)
Expand All @@ -50,8 +50,8 @@ async def delete(self, *args, **kwargs):

@asynccontextmanager
async def post(self, *args, **kwargs):
log.debug(f"args: {args}")
log.debug(f"kwargs: {kwargs}")
log.debug(f"POST: {args}")
log.debug(f"post_kwargs: {kwargs}")
async with ClientSession(**self._session_kwargs) as session:
log.debug(f"session_kwargs: {self._session_kwargs}")
response = await session.post(*args, **kwargs)
Expand Down
16 changes: 8 additions & 8 deletions discovery/engine/httpx/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ def __init__(self, *args, **kwargs) -> None:

@asynccontextmanager
async def get(self, *args, **kwargs):
log.debug(f"args: {args}")
log.debug(f"kwargs: {kwargs}")
log.debug(f"GET: {args}")
log.debug(f"get_kwargs: {kwargs}")
async with AsyncClient(**self._session_kwargs) as session:
log.debug(f"session_kwargs: {self._session_kwargs}")
response = await session.get(*args, **kwargs)
Expand All @@ -33,8 +33,8 @@ async def get(self, *args, **kwargs):

@asynccontextmanager
async def put(self, *args, **kwargs):
log.debug(f"args: {args}")
log.debug(f"kwargs: {kwargs}")
log.debug(f"PUT: {args}")
log.debug(f"put_kwargs: {kwargs}")
async with AsyncClient(**self._session_kwargs) as session:
log.debug(f"session_kwargs: {self._session_kwargs}")
response = await session.put(*args, **kwargs)
Expand All @@ -43,8 +43,8 @@ async def put(self, *args, **kwargs):

@asynccontextmanager
async def delete(self, *args, **kwargs):
log.debug(f"args: {args}")
log.debug(f"kwargs: {kwargs}")
log.debug(f"DELETE: {args}")
log.debug(f"delete_kwargs: {kwargs}")
async with AsyncClient(**self._session_kwargs) as session:
log.debug(f"session_kwargs: {self._session_kwargs}")
response = await session.delete(*args, **kwargs)
Expand All @@ -53,8 +53,8 @@ async def delete(self, *args, **kwargs):

@asynccontextmanager
async def post(self, *args, **kwargs):
log.debug(f"args: {args}")
log.debug(f"kwargs: {kwargs}")
log.debug(f"POST: {args}")
log.debug(f"post_kwargs: {kwargs}")
async with AsyncClient(**self._session_kwargs) as session:
log.debug(f"session_kwargs: {self._session_kwargs}")
response = await session.post(*args, **kwargs)
Expand Down
4 changes: 2 additions & 2 deletions docs/engine/aiohttp.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@

Using default client:

```python
``` py linenums="1"
from discovery import Consul

consul = Consul()
```

## custom client

```python
``` py linenums="1"
import logging

from discovery import Consul
Expand Down
2 changes: 1 addition & 1 deletion docs/engine/httpx.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Using httpx [**async client**](https://www.python-httpx.org/async/).

```python
``` py linenums="1"
import logging

from discovery import Consul
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ HTTP engine options available:
- aiohttp `default`;
- httpx.

## Installing
## Using

Install and update using pip:

Expand Down
64 changes: 64 additions & 0 deletions examples/aiohttp_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import logging
import socket

from aiohttp import web

from discovery import Consul, checks
from discovery.utils import Service

app = web.Application()
routes = web.RouteTableDef()
logging.basicConfig(level=logging.INFO)


async def register(app: web.Application) -> None:
logging.info("Registering the eservice")
app_service = Service(
name="app",
port=8080,
address="",
check=checks.http(
f"http://{socket.gethostbyname(socket.gethostname())}:8080/health",
timeout="15s",
interval="10s",
),
)
consul = Consul()
await consul.register(app_service)

app["app_service"] = app_service
app["consul"] = consul
logging.info("Registered service")


async def deregister(app: web.Application) -> None:
logging.info("Removing service registration")
await app["consul"].deregister(app["app_service"].id)
logging.info("Registered removed")


@routes.get("/") # type: ignore
def home(request: web.Request) -> web.Response:
body = """
<html>
<body>
<p>discovery-client | aiohttp integration</p>
<p>sample endpoints</p>
<ul>
<li><a href="http://localhost:8080/health">/health</a></li>
</ul>
</body>
</html>
"""
return web.Response(text=body, content_type="text/html")


@routes.get("/health") # type: ignore
def health(request: web.Request) -> web.Response:
return web.json_response({"status": "UP"})


app.add_routes(routes)
app.on_startup.append(register)
app.on_shutdown.append(deregister)
web.run_app(app)
10 changes: 10 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ theme:
- search.share
- content.code.annotate
- content.tooltips
- content.code.select
- content.code.copy
- toc.follow
palette:
- scheme: default
Expand All @@ -38,6 +40,14 @@ extra:
link: https://github.com/amenezes/discovery-client/issues
- icon: fontawesome/solid/envelope
link: mailto:alexandre.fmenezes@gmail.com
markdown_extensions:
- pymdownx.highlight:
anchor_linenums: true
line_spans: __span
pygments_lang_class: true
- pymdownx.inlinehilite
- pymdownx.snippets
- pymdownx.superfences
nav:
- API:
- ACLs:
Expand Down
Loading

0 comments on commit 1f733a4

Please sign in to comment.