Skip to content

Commit

Permalink
add midleware
Browse files Browse the repository at this point in the history
  • Loading branch information
guangrei committed Jan 10, 2024
1 parent 0b36175 commit 6973838
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 15 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ name: Test

on:
push:
branches: [ "main" ]
branches: [ "main", "dev" ]
pull_request:
branches: [ "main" ]

Expand All @@ -26,10 +26,10 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi
pip install poetry && poetry update
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
poetry run flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
poetry run flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
59 changes: 52 additions & 7 deletions chatrouter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"""

__author__ = "guangrei"
__version__ = "v1.0.1"
__version__ = "v1.0.2"

_data: dict = {} # chatrouter storage
data_user: Any = None # data user storage
Expand Down Expand Up @@ -64,7 +64,8 @@ def dec(func: Callable) -> Callable:
if self._async and not inspect.iscoroutinefunction(func):
raise ValueError("function must be awaitable!")
elif not self._async and inspect.iscoroutinefunction(func):
raise ValueError("coroutine function is not supported in synchronous mode!")
raise ValueError(
"coroutine function is not supported in synchronous mode!")
_data[self.id][method] = {}
_data[self.id][method]["callback"] = func
_data[self.id][method]["description"] = description
Expand All @@ -80,12 +81,28 @@ def dec(func: Callable) -> Callable:
if self._async and not inspect.iscoroutinefunction(func):
raise ValueError("function must be awaitable!")
elif not self._async and inspect.iscoroutinefunction(func):
raise ValueError("coroutine function is not supported in synchronous mode!")
raise ValueError(
"coroutine function is not supported in synchronous mode!")
_data[self.id]["__default__"] = {}
_data[self.id]["__default__"]["callback"] = func
return func
return dec

def midleware(self) -> Callable:
"""
fungsi untuk menambahkan midleware
"""
def dec(func: Callable) -> Callable:
if self._async and not inspect.iscoroutinefunction(func):
raise ValueError("function must be awaitable!")
elif not self._async and inspect.iscoroutinefunction(func):
raise ValueError(
"coroutine function is not supported in synchronous mode!")
_data[self.id]["__midleware__"] = {}
_data[self.id]["__midleware__"]["callback"] = func
return func
return dec

def _start(self) -> str:
"""
fungsi ini sebagai default callback /start commands
Expand Down Expand Up @@ -228,9 +245,13 @@ def run(route: group, msg: str) -> Union[str, None]:
"""
ini adalah fungsi utama untuk interpretasi chatrouter
"""
if "__midleware__" in _data[route.id]:
coba = _data[route.id]["__default__"]["callback"]()
if coba is not True:
return coba
if len(msg):
for k, v in _data[route.id].items():
if k != "__default__":
if k not in ("__default__", "__midleware__"):
args = util._route(k, msg, v["strict"])
if args is not False:
return v["callback"](*args)
Expand All @@ -244,9 +265,13 @@ async def async_run(route: group, msg: str) -> Union[str, None]:
"""
ini adalah versi async dari function run
"""
if "__midleware__" in _data[route.id]:
coba = await _data[route.id]["__default__"]["callback"]()
if coba is not True:
return coba
if len(msg):
for k, v in _data[route.id].items():
if k != "__default__":
if k not in ("__default__", "__midleware__"):
args = await util._async_route(k, msg, v["strict"])
if args is not False:
ret = await v["callback"](*args)
Expand All @@ -269,7 +294,8 @@ def dec(func: Callable) -> Callable:
if asynchronous and not inspect.iscoroutinefunction(func):
raise ValueError("function must be awaitable!")
elif not asynchronous and inspect.iscoroutinefunction(func):
raise ValueError("coroutine function is not supported in synchronous mode!")
raise ValueError(
"coroutine function is not supported in synchronous mode!")
_data[group_route][method] = {}
_data[group_route][method]["callback"] = func
_data[group_route][method]["description"] = description
Expand All @@ -288,12 +314,31 @@ def dec(func: Callable) -> Callable:
if asynchronous and not inspect.iscoroutinefunction(func):
raise ValueError("function must be awaitable!")
elif not asynchronous and inspect.iscoroutinefunction(func):
raise ValueError("coroutine function is not supported in synchronous mode!")
raise ValueError(
"coroutine function is not supported in synchronous mode!")
_data[group_route]["__default__"] = {}
_data[group_route]["__default__"]["callback"] = func
return func
return dec


def midleware(group_route: str = "main", asynchronous: bool = False) -> Callable:
"""
fungsi untuk menambahkan midleware secara cepat
"""
group(group_route, asynchronous=asynchronous)

def dec(func: Callable) -> Callable:
if asynchronous and not inspect.iscoroutinefunction(func):
raise ValueError("function must be awaitable!")
elif not asynchronous and inspect.iscoroutinefunction(func):
raise ValueError(
"coroutine function is not supported in synchronous mode!")
_data[group_route]["__midleware__"] = {}
_data[group_route]["__midleware__"]["callback"] = func
return func
return dec


if __name__ == '__main__':
pass
20 changes: 20 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[tool.poetry]
name = "chatrouter"
version = "1.0.2"
description = "router for chatbot"
authors = ["guangrei"]
license = "mit"
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.10"

[tool.poetry.group.dev.dependencies]
flake8 = "^7.0.0"
autopep8 = "^2.0.4"
mypy = "^1.8.0"
twine = "^4.0.2"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
4 changes: 0 additions & 4 deletions requirements-dev.txt

This file was deleted.

0 comments on commit 6973838

Please sign in to comment.