cppackage 0.1.0__tar.gz → 0.2.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.
@@ -5,7 +5,7 @@ _db_config = {
5
5
  'user': os.getenv('CPPACKAGE_DB_USER'),
6
6
  'password': os.getenv('CPPACKAGE_DB_PASSWORD'),
7
7
  'database': os.getenv('CPPACKAGE_DB_NAME'),
8
- 'port': int(os.getenv('CPPACKAGE_DB_PORT', '3306')),
8
+ 'port': int(os.getenv('CPPACKAGE_DB_PORT')),
9
9
  }
10
10
 
11
11
  def set_db_config(host=None, user=None, password=None, database=None, port=None):
@@ -0,0 +1,188 @@
1
+ import pymysql
2
+ import time
3
+ from pymysql import Error
4
+
5
+ # 条件导入:支持直接运行和包模式
6
+ try:
7
+ from .config import get_db_config
8
+ except (ImportError, ValueError):
9
+ # 直接运行时失败,尝试绝对路径
10
+ import sys
11
+ import os
12
+ sys.path.insert(0, os.path.dirname(__file__))
13
+ from config import get_db_config
14
+
15
+
16
+ # ===================== 数据库连接 =====================
17
+
18
+ def _get_connection(database=None, port=None):
19
+ cfg = get_db_config()
20
+
21
+ db = database if database else cfg.get('database')
22
+ prt = port if port else cfg.get('port', 3306)
23
+
24
+ return pymysql.connect(
25
+ host=cfg.get('host'),
26
+ user=cfg.get('user'),
27
+ password=cfg.get('password'),
28
+ database=db,
29
+ port=prt,
30
+ charset="utf8mb4",
31
+ autocommit=False
32
+ )
33
+
34
+
35
+ # ===================== 基础操作 =====================
36
+
37
+ def sel_data(sql, params=None, port=None, database=None):
38
+
39
+ try:
40
+ with _get_connection(database, port) as conn:
41
+ with conn.cursor() as cursor:
42
+ cursor.execute(sql, params)
43
+ return cursor.fetchall()
44
+
45
+ except pymysql.MySQLError as e:
46
+ print("查询失败:", e)
47
+ return None
48
+
49
+
50
+ def update_data(sql, values, port=None, database=None):
51
+
52
+ try:
53
+ with _get_connection(database, port) as conn:
54
+ with conn.cursor() as cursor:
55
+ cursor.execute(sql, values)
56
+ conn.commit()
57
+
58
+ except pymysql.MySQLError as e:
59
+ print("更新失败:", e)
60
+
61
+
62
+ def update_datas(sql, values, port=None, database=None):
63
+
64
+ try:
65
+ with _get_connection(database, port) as conn:
66
+ with conn.cursor() as cursor:
67
+ cursor.executemany(sql, values)
68
+ conn.commit()
69
+
70
+ except pymysql.MySQLError as e:
71
+ print("批量更新失败:", e)
72
+
73
+
74
+ def del_data(sql, params=None, port=None, database=None):
75
+
76
+ try:
77
+ with _get_connection(database, port) as conn:
78
+ with conn.cursor() as cursor:
79
+ cursor.execute(sql, params)
80
+ conn.commit()
81
+
82
+ except pymysql.MySQLError as e:
83
+ print("删除失败:", e)
84
+
85
+
86
+ # ===================== 表结构管理 =====================
87
+
88
+ def get_table_columns(table_name, database):
89
+
90
+ sql = """
91
+ SELECT COLUMN_NAME
92
+ FROM INFORMATION_SCHEMA.COLUMNS
93
+ WHERE TABLE_SCHEMA=%s
94
+ AND TABLE_NAME=%s
95
+ ORDER BY ORDINAL_POSITION
96
+ """
97
+
98
+ with _get_connection(database) as conn:
99
+ with conn.cursor() as cursor:
100
+ cursor.execute(sql, (database, table_name))
101
+ return [row[0] for row in cursor.fetchall()]
102
+
103
+
104
+ def add_columns(table_name, database, columns):
105
+
106
+ with _get_connection(database) as conn:
107
+ with conn.cursor() as cursor:
108
+
109
+ for col in columns:
110
+ sql = f"""
111
+ ALTER TABLE `{table_name}`
112
+ ADD COLUMN `{col}` TEXT
113
+ """
114
+ cursor.execute(sql)
115
+ print(f"新增字段: {col}")
116
+
117
+ conn.commit()
118
+
119
+ # 表结构校验
120
+ def check_and_sync_columns(df, table_name, database, max_new=5):
121
+
122
+ df_cols = set(df.columns)
123
+
124
+ db_cols = set(get_table_columns(table_name, database))
125
+
126
+ new_cols = df_cols - db_cols
127
+ missing_cols = db_cols - df_cols
128
+ print("新增字段:", new_cols if new_cols else "无")
129
+ print("缺失字段(忽略):", missing_cols if missing_cols else "无")
130
+
131
+ # 超限
132
+ if len(new_cols) > max_new:
133
+ raise Exception(f"新增字段超过{max_new}个: {new_cols}")
134
+
135
+ # 自动补
136
+ if 0 < len(new_cols) <= max_new:
137
+
138
+ print("开始同步字段...")
139
+ add_columns(table_name, database, new_cols)
140
+
141
+ # 二次校验
142
+ new_db_cols = set(get_table_columns(table_name, database))
143
+
144
+ if not df_cols.issubset(new_db_cols):
145
+ raise Exception("字段同步失败")
146
+
147
+ print("字段同步成功")
148
+
149
+ return True
150
+
151
+
152
+ # ===================== DataFrame 入库 =====================
153
+
154
+ def update_test(df, table_name, database):
155
+
156
+ conn = None
157
+
158
+ try:
159
+ # 表结构校验
160
+ check_and_sync_columns(df, table_name, database)
161
+ conn = _get_connection(database)
162
+ cursor = conn.cursor()
163
+ cols = list(df.columns)
164
+ col_str = ",".join([f"`{c}`" for c in cols])
165
+ value_tpl = "(" + ",".join(["%s"] * len(cols)) + ")"
166
+ values_str = ",".join([value_tpl] * len(df))
167
+ update_clause = ",".join(
168
+ [f"`{c}`=VALUES(`{c}`)" for c in cols if c != "id"]
169
+ )
170
+ sql = f"""
171
+ INSERT INTO `{table_name}` ({col_str})
172
+ VALUES {values_str}
173
+ ON DUPLICATE KEY UPDATE {update_clause}
174
+ """
175
+ data = [tuple(row) for row in df.values]
176
+ flat_data = [v for row in data for v in row]
177
+ cursor.execute(sql, flat_data)
178
+ conn.commit()
179
+ print(f"成功插入/更新 {cursor.rowcount} 条记录")
180
+ except Exception as e:
181
+ if conn:
182
+ conn.rollback()
183
+ print("入库失败:", e)
184
+ finally:
185
+ if conn:
186
+ conn.close()
187
+
188
+
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: cppackage
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: 超品集团自用的Python包
5
5
  Home-page: https://github.com/example/CPpackage
6
6
  Author: team-数智组
@@ -20,6 +20,16 @@ License-File: LICENSE
20
20
  Requires-Dist: pymysql
21
21
  Requires-Dist: pandas
22
22
  Requires-Dist: numpy
23
+ Dynamic: author
24
+ Dynamic: author-email
25
+ Dynamic: classifier
26
+ Dynamic: description
27
+ Dynamic: description-content-type
28
+ Dynamic: home-page
29
+ Dynamic: license-file
30
+ Dynamic: requires-dist
31
+ Dynamic: requires-python
32
+ Dynamic: summary
23
33
 
24
34
  # CPpackage
25
35
 
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: cppackage
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: 超品集团自用的Python包
5
5
  Home-page: https://github.com/example/CPpackage
6
6
  Author: team-数智组
@@ -20,6 +20,16 @@ License-File: LICENSE
20
20
  Requires-Dist: pymysql
21
21
  Requires-Dist: pandas
22
22
  Requires-Dist: numpy
23
+ Dynamic: author
24
+ Dynamic: author-email
25
+ Dynamic: classifier
26
+ Dynamic: description
27
+ Dynamic: description-content-type
28
+ Dynamic: home-page
29
+ Dynamic: license-file
30
+ Dynamic: requires-dist
31
+ Dynamic: requires-python
32
+ Dynamic: summary
23
33
 
24
34
  # CPpackage
25
35
 
@@ -10,7 +10,7 @@ with open('readme.md', 'r', encoding='utf-8') as f:
10
10
  # 包的基本信息
11
11
  setup(
12
12
  name='cppackage',
13
- version='0.1.0',
13
+ version='0.2.0',
14
14
  description='超品集团自用的Python包',
15
15
  long_description=long_description,
16
16
  long_description_content_type='text/markdown',
@@ -1,105 +0,0 @@
1
- import pymysql
2
- import time
3
- from pymysql import Error
4
- from .config import get_db_config
5
-
6
- def _get_connection(database=None, port=None):
7
- cfg = get_db_config()
8
- db = database if database is not None else cfg.get('database')
9
- prt = port if port is not None else cfg.get('port', 3306)
10
- return pymysql.connect(
11
- host=cfg.get('host'),
12
- user=cfg.get('user'),
13
- password=cfg.get('password'),
14
- database=db,
15
- port=prt,
16
- )
17
-
18
- def sel_data(sql, port=None, database=None):
19
- try:
20
- conn = _get_connection(database=database, port=port)
21
- cursor = conn.cursor()
22
- cursor.execute(sql)
23
- result = cursor.fetchall()
24
- cursor.close()
25
- conn.close()
26
- return result
27
- except pymysql.MySQLError as e:
28
- print(f"An error occurred: {e}")
29
-
30
- def update_data(sql, values, port=None, database=None):
31
- conn = _get_connection(database=database, port=port)
32
- cursor = conn.cursor()
33
- cursor.execute(sql, values)
34
- conn.commit()
35
- cursor.close()
36
- conn.close()
37
-
38
- def updata(data, databases, table):
39
- s = ""
40
- st1 = ""
41
- for i in data.columns.values:
42
- s = s + "`" + i + "`,"
43
- st1 = st1 + "%s,"
44
- s = s[:-1]
45
- st1 = st1[:-1]
46
- all_data = []
47
- for _, k in data.iterrows():
48
- all_data.append(tuple(k.to_list()))
49
- sql = 'INSERT INTO %s (%s) VALUES (%s)' % (table, s, st1)
50
- update_datas(sql, tuple(all_data), database=databases)
51
- time.sleep(2)
52
-
53
- def deldata(all_del_list, id_name, table_name, database):
54
- str11 = ""
55
- for te in all_del_list:
56
- if "str" in str(type(te)):
57
- str11 = str11 + "'" + str(te) + "',"
58
- else:
59
- str11 = str11 + str(te) + ","
60
- str11 = str11[:-1]
61
- delsql = 'DELETE from `%s` where %s in (%s)' % (table_name, id_name, str11)
62
- del_data(delsql, database=database)
63
-
64
- def deldata_time(id_name, table_name, id, database, time_name, start_time, end_time):
65
- delsql = 'DELETE from `%s` where %s = %s and `%s`>= "%s" and `%s`<= "%s"' % (
66
- table_name, id_name, id, time_name, start_time, time_name, end_time
67
- )
68
- del_data(delsql, database=database)
69
-
70
- def update_datas(sql, values, port=None, database=None):
71
- with _get_connection(database=database, port=port) as conn:
72
- with conn.cursor() as cursor:
73
- cursor.executemany(sql, values)
74
- conn.commit()
75
-
76
- def del_data(sql, port=None, database=None):
77
- try:
78
- conn = _get_connection(database=database, port=port)
79
- cursor = conn.cursor()
80
- cursor.execute(sql)
81
- conn.commit()
82
- cursor.close()
83
- conn.close()
84
- except pymysql.MySQLError as e:
85
- print(f"An error occurred: {e}")
86
-
87
- def update_test(df, table_name, databases):
88
- try:
89
- conn = _get_connection(database=databases)
90
- cursor = conn.cursor()
91
- columns = ', '.join(df.columns)
92
- values_template = ', '.join([f'({", ".join(["%s"] * len(df.columns))})'] * len(df))
93
- update_clause = ', '.join([f'{col} = VALUES({col})' for col in df.columns if col != 'id'])
94
- sql = f"INSERT INTO {table_name} ({columns}) VALUES {values_template} " \
95
- f"ON DUPLICATE KEY UPDATE {update_clause}"
96
- values = [tuple(row) for row in df.values]
97
- flat_values = [item for sublist in values for item in sublist]
98
- cursor.execute(sql, flat_values)
99
- conn.commit()
100
- print(f"成功插入/更新 {cursor.rowcount} 条记录")
101
- except Error as e:
102
- print(f"数据库错误: {e}")
103
- finally:
104
- if conn:
105
- conn.close()
File without changes
File without changes
File without changes
File without changes