Skip to content

Commit

Permalink
Merge pull request #10 from Undertone0809/docs-add-link
Browse files Browse the repository at this point in the history
feat: add log mode
  • Loading branch information
Undertone0809 authored Mar 21, 2023
2 parents 3b0e506 + ed24347 commit a42579f
Show file tree
Hide file tree
Showing 11 changed files with 70 additions and 25 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
command
.idea
broadcast_service.egg-info/
dist/
Expand Down
39 changes: 24 additions & 15 deletions broadcast_service/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,15 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from concurrent.futures import ThreadPoolExecutor
import logging
from typing import Optional, List, Callable
from concurrent.futures import ThreadPoolExecutor

__all__ = ['broadcast_service', 'BroadcastService', 'enable_log']


__all__ = ['broadcast_service', 'BroadcastService']
def enable_log():
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')


class BroadcastService:
Expand Down Expand Up @@ -57,6 +62,7 @@ def __init__(self):
}
self.enable_async: bool = True
self.thread_pool = ThreadPoolExecutor(max_workers=5)
self.logger = logging.getLogger(__name__)

# function renaming
self.subscribe = self.listen
Expand All @@ -71,13 +77,13 @@ def __init__(self):

def listen(self, topics: str or List[str], callback: Callable):
"""
listen topic.
listen topics.
"""
if type(topics) == str:
self._listen_topic(topics, callback)
self._invoke_listen_topic(topics, callback)
elif type(topics) == list:
for topic in topics:
self._listen_topic(topic, callback)
self._invoke_listen_topic(topic, callback)
else:
raise ValueError("Unknown broadcast-service error, please submit "
"issue to https://github.com/Undertone0809/broadcast-service/issues")
Expand All @@ -86,17 +92,18 @@ def listen_all(self, callback: Callable):
"""
'__all__' is a special topic. It can receive any topic message.
"""
self._listen_topic('__all__', callback)
self._invoke_listen_topic('__all__', callback)

def broadcast(self, topics: str or List[str], *args, **kwargs):
"""
Launch broadcast on the specify topic
"""
self.logger.debug(f"[broadcast-service] broadcast topic <{topics}>")
if type(topics) == str:
self._broadcast_topic(topics, *args, **kwargs)
self._invoke_broadcast_topic(topics, *args, **kwargs)
elif type(topics) == list:
for topic in topics:
self._broadcast_topic(topic, *args, **kwargs)
self._invoke_broadcast_topic(topic, *args, **kwargs)
else:
raise ValueError("Unknown broadcast-service error, please submit "
"issue to https://github.com/Undertone0809/broadcast-service/issues")
Expand All @@ -109,16 +116,16 @@ def broadcast_all(self, *args, **kwargs):
will not be executed.
"""
for topic in self.pubsub_channels.keys():
self._broadcast_topic(topic, *args, **kwargs)
self._invoke_broadcast_topic(topic, *args, **kwargs)

def _listen_topic(self, topic_name: str, callback: Callable):
def _invoke_listen_topic(self, topic_name: str, callback: Callable):
if topic_name not in self.pubsub_channels.keys():
self.pubsub_channels[topic_name] = []

if callback not in self.pubsub_channels[topic_name]:
self.pubsub_channels[topic_name].append(callback)

def _broadcast_topic(self, topic_name: str, *args, **kwargs):
def _invoke_broadcast_topic(self, topic_name: str, *args, **kwargs):
"""
broadcast single topic.
TODO fix problem: There is no guarantee that every callback function will be executed unnecessarily in some cases.
Expand Down Expand Up @@ -173,18 +180,20 @@ def handle_all_msg(*args, **kwargs):
Attention: Your params should keep '*args, **kwargs'. If you publish a topic take arguments,
the callback function you handle should take arguments, otherwise it will not be called back.
"""

def decorator(fn: Callable) -> Callable:
self.logger.debug(f"[broadcast-service] <{fn.__name__}> listen <{topics}> topic")
if not topics:
self._listen_topic('__all__', fn)
elif type(topics) == str:
self._listen_topic(topics, fn)
elif type(topics) == list:
self.listen_all(fn)
elif type(topics) == str or list:
self.listen(topics, fn)

def inner(*args, **kwargs) -> Callable:
ret = fn(*args, **kwargs)
return ret

return inner

return decorator


Expand Down
2 changes: 1 addition & 1 deletion docs/_coverpage.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<!-- _coverpage.md -->

# broadcast-service <small>1.1.7</small>
# broadcast-service <small>1.2.0</small>

> A lightweight python broadcast library. You can easily construct a Broadcast pattern/Publish subscriber pattern through this library.
Expand Down
1 change: 1 addition & 0 deletions docs/_sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

- [Quick Start](quickstart.md)
- [Async](async.md)
- [Log](log.md)

- Other

Expand Down
4 changes: 2 additions & 2 deletions docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
repo: 'https://github.com/Undertone0809/broadcast-service',
loadNavbar: true,
loadSidebar: true,
subMaxLevel: 3, // 生成目录的最大层级
subMaxLevel: 3,
coverpage: true,
search: {
paths: 'auto',
Expand All @@ -31,6 +31,6 @@
<!-- 搜索插件 -->
<script src="//cdn.jsdelivr.net/npm/docsify/lib/plugins/search.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-bash.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-python.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-python.min.js"></script>
</body>
</html>
23 changes: 23 additions & 0 deletions docs/log.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Log

If you want to open the log mode, you should do as follows:

```python
from broadcast_service import broadcast_service, enable_log

enable_log()


@broadcast_service.on_listen("test")
def handle_msg():
print('handle msg')


broadcast_service.publish('test')

```


- result

<img src="https://zeeland-bucket.oss-cn-beijing.aliyuncs.com/images/20230321132348.png"/>
8 changes: 8 additions & 0 deletions docs/update.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ Please update the latest version. The old version is shit.
pip install --upgrade broadcast-service
```

## v1.3.0 2023-03-21

#### feat
1. Add log mode. [Detail Information](./log.md)

#### fix
1. optimize some code structure

## v1.2.0 2023-01-12

#### feat
Expand Down
6 changes: 4 additions & 2 deletions example/demo1_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from broadcast_service import broadcast_service, BroadcastService
from broadcast_service import broadcast_service, BroadcastService, enable_log

enable_log()


def handle_no_msg():
Expand Down Expand Up @@ -53,7 +55,7 @@ def callback_of_lambda():
callback of lambda
"""
# listen topic
broadcast_service.listen('lambda', lambda x,y: print(f"the params is {x} and {y}"))
broadcast_service.listen('lambda', lambda x, y: print(f"the params is {x} and {y}"))

# publish broadcast
broadcast_service.broadcast('lambda', 11, 22)
Expand Down
1 change: 0 additions & 1 deletion example/demo2_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
similar to the common method.
"""


from broadcast_service import broadcast_service


Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

setuptools.setup(
name="broadcast_service",
version="1.2.0",
version="1.3.0",
author="Zeeland",
author_email="zeeland@foxmail.com",
description="A lightweight third-party broadcast/pubsub library",
Expand Down
8 changes: 5 additions & 3 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@

import time
from unittest import TestCase
from broadcast_service import broadcast_service
from broadcast_service import broadcast_service, enable_log

enable_log()


def wait(seconds=0.1):
Expand Down Expand Up @@ -90,12 +92,12 @@ def test_listen_of_decorator(self):
@broadcast_service.on_listen("test_listen_of_decorator_no_params1")
def handle_topic_no_params():
self.test_listen_of_decorator_no_params1 = True

@broadcast_service.on_listen(["test_listen_of_decorator_no_params2"])
def handle_topic_no_params():
self.test_listen_of_decorator_no_params2 = True

@broadcast_service.on_listen(["test_listen_of_decorator_no_params1","test_listen_of_decorator_no_params2"])
@broadcast_service.on_listen(["test_listen_of_decorator_no_params1", "test_listen_of_decorator_no_params2"])
def handle_topic_no_params():
if self.test_listen_of_decorator_no_params1 and self.test_listen_of_decorator_no_params2:
self.test_listen_of_decorator_multi_params = True
Expand Down

0 comments on commit a42579f

Please sign in to comment.