socket-cyg 1.0.0__tar.gz → 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: socket-cyg
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: CYG socket 封装
5
5
  Author: LiuWei
6
6
  Author-email: 183074632@qq.com
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "socket-cyg"
3
- version = "1.0.0"
3
+ version = "1.1.0"
4
4
  description = "CYG socket 封装"
5
5
  authors = ["LiuWei <183074632@qq.com>"]
6
6
  readme = "README.md"
@@ -4,6 +4,7 @@ import asyncio
4
4
  import datetime
5
5
  import logging
6
6
  import os
7
+ import pathlib
7
8
  import socket
8
9
  import sys
9
10
  from asyncio import AbstractEventLoop
@@ -21,45 +22,56 @@ class CygSocketServerAsyncio:
21
22
  def __init__(self, address="127.0.0.1", port=8000):
22
23
  self._address = address
23
24
  self._port = port
24
- self._logger = logging.getLogger(f"{self.__module__}.{self.__class__.__name__}")
25
+ self.logger = logging.getLogger(__name__)
25
26
  self._file_handler = None
26
- self.set_log()
27
-
28
- def set_log(self):
29
- """设置日志."""
30
- self.file_handler.setFormatter(logging.Formatter(self.LOG_FORMAT))
31
- self.file_handler.setLevel(logging.INFO)
32
- self.logger.addHandler(self.file_handler)
33
- if sys.version_info.minor == 11:
34
- logging.basicConfig(level=logging.INFO, encoding="UTF-8", format=self.LOG_FORMAT)
35
- else:
36
- console_handler = logging.StreamHandler()
37
- console_handler.setFormatter(logging.Formatter(self.LOG_FORMAT))
38
- console_handler.setLevel(logging.INFO)
39
- self.logger.addHandler(console_handler)
40
- self.logger.setLevel(logging.INFO)
27
+ self._initial_log_config()
28
+
29
+ def _initial_log_config(self) -> None:
30
+ """日志配置."""
31
+ self._create_log_dir()
32
+ self.logger.addHandler(self.file_handler) # 保存日志
33
+
34
+ @staticmethod
35
+ def _create_log_dir():
36
+ """判断log目录是否存在, 不存在就创建."""
37
+ log_dir = pathlib.Path(f"{os.getcwd()}/log")
38
+ if not log_dir.exists():
39
+ os.mkdir(log_dir)
41
40
 
42
41
  @property
43
- def file_handler(self):
44
- """保存日志的日志器."""
42
+ def file_handler(self) -> TimedRotatingFileHandler:
43
+ """设置保存日志的处理器, 每隔 24h 自动生成一个日志文件.
44
+
45
+ Returns:
46
+ TimedRotatingFileHandler: 返回 TimedRotatingFileHandler 日志处理器.
47
+ """
45
48
  if self._file_handler is None:
46
- log_dir = f"{os.getcwd()}/log"
47
- os.makedirs(log_dir, exist_ok=True)
48
- file_name = f"{log_dir}/{datetime.datetime.now().strftime('%Y-%m-%d')}_{os.path.basename(os.getcwd())}.log"
49
49
  self._file_handler = TimedRotatingFileHandler(
50
- file_name, when="D", interval=1, backupCount=10, encoding="UTF-8"
50
+ f"{os.getcwd()}/log/socket.log",
51
+ when="D", interval=1, backupCount=10, encoding="UTF-8"
51
52
  )
53
+ self._file_handler.namer = self._custom_log_name
54
+ self._file_handler.setFormatter(logging.Formatter(self.LOG_FORMAT))
52
55
  return self._file_handler
53
56
 
54
- @property
55
- def logger(self):
56
- """日志实例."""
57
- return self._logger
57
+ @staticmethod
58
+ def _custom_log_name(log_path: str):
59
+ """自定义新生成的日志名称.
60
+
61
+ Args:
62
+ log_path: 原始的日志文件路径.
63
+
64
+ Returns:
65
+ str: 新生成的自定义日志文件路径.
66
+ """
67
+ _, suffix, date_str = log_path.split(".")
68
+ new_log_path = f"{os.getcwd()}/log/socket_{date_str}.{suffix}"
69
+ return new_log_path
58
70
 
59
71
  def operations_return_data(self, data: bytes):
60
72
  """操作返回数据."""
61
73
  data = data.decode("UTF-8")
62
- self._logger.warning("*** 回显 *** -> 没有重写 operations_return_data 函数, 默认是回显.")
74
+ self.logger.warning("没有重写 operations_return_data 函数, 默认是回显.")
63
75
  return data
64
76
 
65
77
  async def socket_send(self, client_connection, data: bytes):
@@ -67,33 +79,33 @@ class CygSocketServerAsyncio:
67
79
  if client_connection:
68
80
  client_ip = client_connection.getpeername()
69
81
  await self.loop.sock_sendall(client_connection, data)
70
- self._logger.info("***发送*** --> %s 发送成功, %s", client_ip, data)
82
+ self.logger.info("%s 发送成功, %s", client_ip, data)
71
83
  else:
72
- self._logger.info("***发送*** --> 发送失败, %s, 未连接", data)
84
+ self.logger.info("发送数据 % 失败", data)
73
85
 
74
86
  async def receive_send(self, client_connection: socket.socket):
75
- """接收发送数据."""
87
+ """接收后发送数据."""
76
88
  client_ip = client_connection.getpeername()[0] # 获取连接客户端的ip
77
89
  try:
78
90
  while data := await self.loop.sock_recv(client_connection, 1024 * 1024):
79
- self._logger.info("%s", '-' * 60)
80
- self._logger.info("***Socket接收*** --> %s, 数据: %s", client_ip, data.decode('UTF-8'))
91
+ self.logger.info("%s", "-" * 60)
92
+ self.logger.info("接收到客户端 %s 的数据: %s", client_ip, data.decode("UTF-8"))
81
93
  send_data = self.operations_return_data(data) # 这个方法实现具体业务, 需要重写, 不重写回显
82
94
  send_data_byte = send_data.encode("UTF-8") + b"\r\n"
83
95
  await self.loop.sock_sendall(client_connection, send_data_byte)
84
- self._logger.info("***Socket回复*** --> %s, 数据: %s", client_ip, send_data)
85
- self._logger.info("%s", '-' * 60)
96
+ self.logger.info("回复客户端 %s 的数据是: %s", client_ip, send_data)
97
+ self.logger.info("%s", "-" * 60)
86
98
  except Exception as e: # pylint: disable=W0718
87
- self._logger.warning("***通讯出现异常*** --> 异常信息是: %s", e)
99
+ self.logger.warning("通讯出现异常, 异常信息是: %s", str(e))
88
100
  finally:
89
101
  self.clients.pop(client_ip)
90
102
  self.tasks.get(client_ip).cancel()
91
- self._logger.warning("***下位机断开*** --> %s, 断开了", client_ip)
103
+ self.logger.warning("客户端 %s 断开了", client_ip)
92
104
  client_connection.close()
93
105
 
94
106
  async def listen_for_connection(self, socket_server: socket):
95
107
  """异步监听连接."""
96
- self._logger.info("***服务端已启动*** --> %s 等待客户端连接", socket_server.getsockname())
108
+ self.logger.info("服务端 %s 已启动,等待客户端连接", socket_server.getsockname())
97
109
 
98
110
  while True:
99
111
  self.loop = asyncio.get_running_loop()
@@ -103,7 +115,7 @@ class CygSocketServerAsyncio:
103
115
  self.tasks.update({
104
116
  address[0]: self.loop.create_task(self.receive_send(client_connection))
105
117
  })
106
- self._logger.warning("***下位机连接*** --> %s, 连接了", address)
118
+ self.logger.warning("客户端 %s 连接了", address)
107
119
 
108
120
  async def run_socket_server(self):
109
121
  """运行socket服务, 并监听客户端连接."""
File without changes