Skip to content

Commit 56b0dbb

Browse files
committed
New version relased #7
1 parent 782d556 commit 56b0dbb

File tree

7 files changed

+53
-40
lines changed

7 files changed

+53
-40
lines changed

examples/client.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
# Add REDIS_URI application enviroment
55

6-
os.environ.setdefault("REDIS_URI", "redis://:PpkJfHHNph9X5hB5@localhost:6379/0")
6+
os.environ.setdefault("REDIS_URI", "redis://localhost:6379/0")
77

88
rpc = RedisRPC("channel_name") # channel name must be same as server
99
square = rpc.send("square", 5) # send data to spesific event

examples/server.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,20 @@
33

44
# Add REDIS_URI application enviroment
55

6-
os.environ.setdefault("REDIS_URI", "redis://:PpkJfHHNph9X5hB5@localhost:6379/0")
6+
os.environ.setdefault("REDIS_URI", "redis://localhost:6379/0")
77

88
rpc = RedisRPC("channel_name") # rename what you want
99

1010

1111
# event lists
1212
def calc_square(response): # `response` is a sender data
13-
power_of_number = response ** 2
13+
power_of_number = response**2
1414

1515
return power_of_number # sent to client
1616

1717

1818
def calc_cube(response): # `response` is a sender data
19-
cube_of_number = response ** 3
19+
cube_of_number = response**3
2020
return cube_of_number # sent to client
2121

2222

redisrpc/__init__.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
from redisrpc.base import BasePubSub
22
from redisrpc.version import VERSION
3+
34
__author__ = "munisisazade@gmail.com"
45

56

67
RedisRPC = BasePubSub
78

8-
__all__ = [
9-
"VERSION", "RedisRPC"
10-
]
9+
__all__ = ["VERSION", "RedisRPC"]

redisrpc/base.py

+32-21
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,25 @@
99
import traceback
1010
from urllib.parse import urlparse
1111
from redisrpc.version import VERSION
12+
from redisrpc.errors import ChannelActiveException
1213

1314
try:
1415
import redis
15-
except:
16-
pass
16+
except ImportError:
17+
raise ImportError("redis package must be installed")
1718

1819

1920
class BasePubSub(object):
2021
"""
21-
Base publish–subscribe is a
22-
messaging pattern class
22+
Base publish–subscribe is a
23+
messaging pattern class
2324
"""
2425

2526
def __init__(self, channel_name):
2627
"""
27-
Initialize and subscribe channel
28+
Initialize and subscribe channel
2829
"""
30+
self.validate_env()
2931
self.rdb = redis.StrictRedis.from_url(os.getenv("REDIS_URI"))
3032
self.check_connection_redis()
3133
self.channel = channel_name
@@ -44,7 +46,19 @@ def check_connection_redis(self):
4446
f"redis_uri: {os.getenv('REDIS_URI')}"
4547
)
4648

49+
def validate_env(self):
50+
if not os.getenv("REDIS_URI"):
51+
raise ValueError("REDIS_URI environment variable must be set")
52+
53+
def check_before_connect(self):
54+
# Get the list of currently active channels
55+
active_channels = self.rdb.pubsub_channels()
56+
if self.channel.encode("utf-8") in active_channels:
57+
print("Please use different channel name or kill existing channel")
58+
raise ChannelActiveException(self.channel)
59+
4760
def listen(self):
61+
self.check_before_connect()
4862
try:
4963
self.print_start()
5064
self.log_print("Pubsub is listen...")
@@ -72,20 +86,20 @@ def event_handler(self, event_name, data):
7286
response = event(data)
7387
if response:
7488
self.log_print(f"Success response from {event_name}", "DEBUG")
75-
self.__send_reponse({
76-
"token": self.token,
77-
"event_name": event_name,
78-
"data": response
79-
})
89+
self.__send_reponse(
90+
{
91+
"token": self.token,
92+
"event_name": event_name,
93+
"data": response,
94+
}
95+
)
8096
else:
8197
self.log_print(f"Empty response from {event_name}", "WARNING")
8298
except:
8399
self.log_print(traceback.format_exc(), "FATAL")
84100
else:
85101
self.log_print(f"Can't find `{event_name}` event name", "ERROR")
86-
return {
87-
"error": f"Can't find `{event_name}` event name"
88-
}
102+
return {"error": f"Can't find `{event_name}` event name"}
89103

90104
def print_start(self):
91105
start_text = f"""
@@ -122,10 +136,11 @@ def log_print(self, text, type="INFO"):
122136
def connection_uri(self):
123137
uri = urlparse(os.getenv("REDIS_URI"))
124138
host = uri.netloc
125-
paswd = ""
126139
if ":" in host and "@" in host:
127-
paswd = host[host.index(":"):host.index("@")]
128-
return os.getenv("REDIS_URI").replace(paswd, "****")
140+
paswd = host[host.index(":") : host.index("@")]
141+
return os.getenv("REDIS_URI").replace(paswd, "***")
142+
else:
143+
return os.getenv("REDIS_URI")
129144

130145
def __encode_base64(self, data):
131146
return base64.b64encode(json.dumps(data).encode("utf-8"))
@@ -153,11 +168,7 @@ def __send_reponse(self, data):
153168
self.rdb.publish(self.channel, decode)
154169

155170
def send(self, event_name, data, wait_response_time=2):
156-
resp = {
157-
"token": self.token,
158-
"event_name": event_name,
159-
"data": data
160-
}
171+
resp = {"token": self.token, "event_name": event_name, "data": data}
161172
decode = self.__encode_base64(resp)
162173
self.rdb.publish(self.channel, decode)
163174
print("Send")

redisrpc/errors.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1-
2-
31
class Handler(Exception):
42
def __init__(self, message, errors):
5-
63
# Call the base class constructor with the parameters it needs
74
super().__init__(message)
85

96
# Now for your custom code...
107
self.errors = errors
8+
9+
10+
class ChannelActiveException(Exception):
11+
def __init__(self, channel):
12+
self.channel = channel
13+
super().__init__(f"Channel '{channel}' is currently active.")

redisrpc/version.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1 @@
1-
2-
3-
VERSION = "0.0.6"
1+
VERSION = "0.0.7"

setup.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,23 @@
1111
description="Redis RPC server for microservices",
1212
long_description=long_description,
1313
long_description_content_type="text/markdown",
14-
license='MIT',
14+
license="MIT",
1515
url="https://github.com/munisisazade/redis-pub-sub",
1616
install_requires=["redis"],
17-
extras_require={
18-
"redis": ["redis"]
19-
},
20-
platforms=['any'],
17+
extras_require={"redis": ["redis"]},
18+
platforms=["any"],
2119
packages=setuptools.find_packages(),
2220
classifiers=[
2321
"Intended Audience :: Developers",
2422
"Programming Language :: Python",
2523
"Programming Language :: Python :: 3",
2624
"Programming Language :: Python :: 3.6",
2725
"Programming Language :: Python :: 3.7",
28-
"Programming Language :: Python :: 3 :: Only",
26+
"Programming Language :: Python :: 3.8",
27+
"Programming Language :: Python :: 3.9",
28+
"Programming Language :: Python :: 3.10",
29+
"Programming Language :: Python :: 3.11",
30+
"Programming Language :: Python :: 3.12",
2931
"License :: OSI Approved :: MIT License",
3032
"Operating System :: OS Independent",
3133
],

0 commit comments

Comments
 (0)