Skip to content

Commit 1d673d8

Browse files
gsvdutraGBgustavodutrasaitoHugo
authored
Add obk core views (#30)
* Fix tests and dataclass inerithance * Fix tests and dataclass inerithance * Fix tests and dataclass inerithance * Update changelog * Remove comments * apply black * Revert "apply black" This reverts commit 03a5f8f. * Apply linter * Apply linter to tests * remove black * Add test async event handler * Add new logger module * add picpay logger * Add docstrings * Fix typos * improve configurations * Add new views and config envrionments Co-authored-by: GBgustavodutra <[email protected]> Co-authored-by: Hugo Saito <[email protected]>
1 parent 71b8248 commit 1d673d8

File tree

14 files changed

+328
-3
lines changed

14 files changed

+328
-3
lines changed

events_protocol/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1-
__version__ = "0.3.1" # pragma: no cover
1+
__version__ = "0.3.2" # pragma: no cover
2+
23

events_protocol/core/builder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class EventBuilder(LoggableMixin):
1616
@classmethod
1717
def error_for(
1818
cls,
19-
exception: typing.Union[EventException],
19+
exception: EventException,
2020
event: typing.Optional[Event] = Event(name="", version=1, id=str(uuid4())),
2121
id_flow=str(uuid4()),
2222
loggable=True,
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
from logging import Logger
1+
from .loggable import LoggableMixin

events_protocol/core/urls.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
from events_protocol.core.views.aiohttp import AIOHTTPHealthCheckView
2+
3+
from events_protocol.core.views.event import EventView
4+
5+
URL_PATTERNS = [(EventView, r"/events"), (AIOHTTPHealthCheckView, r"/health")]
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from .config import config
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import os
2+
import typing
3+
import glob
4+
5+
from decouple import Config, RepositoryEnv, Undefined
6+
7+
def config(
8+
config_name: str,
9+
default: typing.Any = None,
10+
cast: typing.Type = None,
11+
env_file=os.environ.get("APPLICATION_ENVIRONMENT") or "dev"
12+
):
13+
try:
14+
available_env_files = glob.glob("./**/*.env", recursive=True)
15+
env_file_path = [file for file in available_env_files if file.endswith(f'/{env_file}.env')][0]
16+
_config = Config(RepositoryEnv(env_file_path))
17+
except IndexError as ex:
18+
raise FileNotFoundError(f'Can\'t find environment file {env_file}.env')
19+
except Exception as ex:
20+
raise OSError(f'Can\'t parse env file {env_file}.env: {ex}')
21+
22+
cfg = None
23+
try:
24+
cfg = _config(config_name, default=default or Undefined(), cast=cast or Undefined())
25+
except Exception:
26+
cfg = cast(default) if cast else default
27+
return cfg
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import datetime
2+
import json
3+
from uuid import UUID
4+
5+
6+
class JSONEncoder(json.JSONEncoder):
7+
def default(self, obj):
8+
if isinstance(obj, UUID):
9+
return obj.hex
10+
elif isinstance(obj, datetime.datetime):
11+
return str(obj)
12+
return json.JSONEncoder.default(self, obj)

events_protocol/core/utils/sync.py

Whitespace-only changes.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from .aiohttp import *
2+
from .event import *
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import json
2+
import tracemalloc
3+
import typing
4+
from http import HTTPStatus
5+
6+
from aiohttp.web import Application, Request, Response, View
7+
from aiohttp.web_middlewares import _Middleware as AIOHTTPMiddleware
8+
9+
from events_protocol.core.views.base import BaseHealth, BaseView
10+
from events_protocol.core.utils.encoder import JSONEncoder
11+
12+
13+
async def init_app(
14+
routes: typing.List[typing.Tuple[View, str]],
15+
middlewares: typing.Iterable[AIOHTTPMiddleware] = [],
16+
) -> Application:
17+
18+
tracemalloc.start()
19+
app = Application(middlewares=middlewares)
20+
for view, path in routes:
21+
app.router.add_view(path, view)
22+
23+
return app
24+
25+
26+
_NOT_ALLOWED_AIOHTTP = Response(status=HTTPStatus.METHOD_NOT_ALLOWED)
27+
28+
29+
class AIOHTTPView(BaseView, View):
30+
request: Request
31+
body: str = None
32+
33+
def __init__(self, *args, **kwargs):
34+
self.request = args[0]
35+
super().__init__(*args, **kwargs)
36+
37+
def __iter__(self):
38+
return self._iter().__await__()
39+
40+
async def get_body(self):
41+
if not self.body and self.request.body_exists:
42+
_body: bytes = await self.request.content.read(-1)
43+
self.body = _body.decode("utf-8")
44+
return self.body
45+
46+
async def get(self, *args, **kwargs):
47+
return await self._get(*args, **kwargs)
48+
49+
async def _get(self, *args, **kwargs):
50+
return _NOT_ALLOWED_AIOHTTP
51+
52+
async def put(self, *args, **kwargs):
53+
await self.get_body()
54+
return await self._put(*args, **kwargs)
55+
56+
async def _put(self, *args, **kwargs):
57+
return _NOT_ALLOWED_AIOHTTP
58+
59+
async def post(self, *args, **kwargs):
60+
await self.get_body()
61+
return await self._post(*args, **kwargs)
62+
63+
async def _post(self, *args, **kwargs):
64+
return _NOT_ALLOWED_AIOHTTP
65+
66+
async def delete(self, *args, **kwargs):
67+
return await self._delete(*args, **kwargs)
68+
69+
async def _delete(self, *args, **kwargs):
70+
return _NOT_ALLOWED_AIOHTTP
71+
72+
def get_query_args(self):
73+
return self.request.rel_url.query or dict()
74+
75+
async def write_response(
76+
self, http_status: HTTPStatus, response_body: dict, headers: dict = {},
77+
):
78+
headers.update(self._base_header)
79+
return Response(
80+
body=json.dumps(response_body, cls=JSONEncoder), status=http_status, headers=headers,
81+
)
82+
83+
84+
class AIOHTTPHealthCheckView(BaseHealth, AIOHTTPView):
85+
pass

0 commit comments

Comments
 (0)