cppackage 0.1.0__tar.gz → 0.2.1__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,165 @@
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
+
51
+ def del_data(sql, params=None, port=None, database=None):
52
+
53
+ try:
54
+ with _get_connection(database, port) as conn:
55
+ with conn.cursor() as cursor:
56
+ cursor.execute(sql, params)
57
+ conn.commit()
58
+
59
+ except pymysql.MySQLError as e:
60
+ print("删除失败:", e)
61
+
62
+
63
+ # ===================== 表结构管理 =====================
64
+
65
+ def get_table_columns(table_name, database):
66
+
67
+ sql = """
68
+ SELECT COLUMN_NAME
69
+ FROM INFORMATION_SCHEMA.COLUMNS
70
+ WHERE TABLE_SCHEMA=%s
71
+ AND TABLE_NAME=%s
72
+ ORDER BY ORDINAL_POSITION
73
+ """
74
+
75
+ with _get_connection(database) as conn:
76
+ with conn.cursor() as cursor:
77
+ cursor.execute(sql, (database, table_name))
78
+ return [row[0] for row in cursor.fetchall()]
79
+
80
+
81
+ def add_columns(table_name, database, columns):
82
+
83
+ with _get_connection(database) as conn:
84
+ with conn.cursor() as cursor:
85
+
86
+ for col in columns:
87
+ sql = f"""
88
+ ALTER TABLE `{table_name}`
89
+ ADD COLUMN `{col}` TEXT
90
+ """
91
+ cursor.execute(sql)
92
+ print(f"新增字段: {col}")
93
+
94
+ conn.commit()
95
+
96
+ # 表结构校验
97
+ def check_and_sync_columns(df, table_name, database, max_new=5):
98
+
99
+ df_cols = set(df.columns)
100
+
101
+ db_cols = set(get_table_columns(table_name, database))
102
+
103
+ new_cols = df_cols - db_cols
104
+ missing_cols = db_cols - df_cols
105
+ print("新增字段:", new_cols if new_cols else "无")
106
+ print("缺失字段(忽略):", missing_cols if missing_cols else "无")
107
+
108
+ # 超限
109
+ if len(new_cols) > max_new:
110
+ raise Exception(f"新增字段超过{max_new}个: {new_cols}")
111
+
112
+ # 自动补
113
+ if 0 < len(new_cols) <= max_new:
114
+
115
+ print("开始同步字段...")
116
+ add_columns(table_name, database, new_cols)
117
+
118
+ # 二次校验
119
+ new_db_cols = set(get_table_columns(table_name, database))
120
+
121
+ if not df_cols.issubset(new_db_cols):
122
+ raise Exception("字段同步失败")
123
+
124
+ print("字段同步成功")
125
+
126
+ return True
127
+
128
+
129
+ # ===================== DataFrame 入库 =====================
130
+
131
+ def update_datas(df, table_name, database):
132
+
133
+ conn = None
134
+
135
+ try:
136
+ # 表结构校验
137
+ check_and_sync_columns(df, table_name, database)
138
+ conn = _get_connection(database)
139
+ cursor = conn.cursor()
140
+ cols = list(df.columns)
141
+ col_str = ",".join([f"`{c}`" for c in cols])
142
+ value_tpl = "(" + ",".join(["%s"] * len(cols)) + ")"
143
+ values_str = ",".join([value_tpl] * len(df))
144
+ update_clause = ",".join(
145
+ [f"`{c}`=VALUES(`{c}`)" for c in cols if c != "id"]
146
+ )
147
+ sql = f"""
148
+ INSERT INTO `{table_name}` ({col_str})
149
+ VALUES {values_str}
150
+ ON DUPLICATE KEY UPDATE {update_clause}
151
+ """
152
+ data = [tuple(row) for row in df.values]
153
+ flat_data = [v for row in data for v in row]
154
+ cursor.execute(sql, flat_data)
155
+ conn.commit()
156
+ print(f"成功插入/更新 {cursor.rowcount} 条记录")
157
+ except Exception as e:
158
+ if conn:
159
+ conn.rollback()
160
+ print("入库失败:", e)
161
+ finally:
162
+ if conn:
163
+ conn.close()
164
+
165
+
@@ -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.1
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
 
@@ -37,15 +47,16 @@ pip install CPpackage
37
47
 
38
48
  ```python
39
49
  # 导入包
40
- from CPpackage.db import set_db_config
41
- from CPpackage.db.sql_model import sel_data, update_data, updata, update_datas, del_data, deldata, deldata_time, update_test
50
+ from CPpackage.db.config import set_db_config
51
+ from CPpackage.db.sql_model import sel_data, del_data , get_table_columns,add_columns,check_and_sync_columns,update_datas
42
52
 
43
53
  # 配置数据库连接(也可通过环境变量CPPACKAGE_DB_*配置)
44
54
  set_db_config(host='your_host', user='your_user', password='your_password', database='your_database', port=3306)
45
55
 
46
- # 查询示例
47
- rows = sel_data('SELECT 1')
48
- print(rows)
56
+ # 更新数据函数,在完成数据库信息配置后,df为pd.dataframe格式的数据
57
+ # 更新过程会先经过check_and_sync_columns函数完成表格校验
58
+ update_datas(df, table_name, database)
59
+
49
60
  ```
50
61
 
51
62
  ## 项目结构
@@ -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.1
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
 
@@ -37,15 +47,16 @@ pip install CPpackage
37
47
 
38
48
  ```python
39
49
  # 导入包
40
- from CPpackage.db import set_db_config
41
- from CPpackage.db.sql_model import sel_data, update_data, updata, update_datas, del_data, deldata, deldata_time, update_test
50
+ from CPpackage.db.config import set_db_config
51
+ from CPpackage.db.sql_model import sel_data, del_data , get_table_columns,add_columns,check_and_sync_columns,update_datas
42
52
 
43
53
  # 配置数据库连接(也可通过环境变量CPPACKAGE_DB_*配置)
44
54
  set_db_config(host='your_host', user='your_user', password='your_password', database='your_database', port=3306)
45
55
 
46
- # 查询示例
47
- rows = sel_data('SELECT 1')
48
- print(rows)
56
+ # 更新数据函数,在完成数据库信息配置后,df为pd.dataframe格式的数据
57
+ # 更新过程会先经过check_and_sync_columns函数完成表格校验
58
+ update_datas(df, table_name, database)
59
+
49
60
  ```
50
61
 
51
62
  ## 项目结构
@@ -14,15 +14,16 @@ pip install CPpackage
14
14
 
15
15
  ```python
16
16
  # 导入包
17
- from CPpackage.db import set_db_config
18
- from CPpackage.db.sql_model import sel_data, update_data, updata, update_datas, del_data, deldata, deldata_time, update_test
17
+ from CPpackage.db.config import set_db_config
18
+ from CPpackage.db.sql_model import sel_data, del_data , get_table_columns,add_columns,check_and_sync_columns,update_datas
19
19
 
20
20
  # 配置数据库连接(也可通过环境变量CPPACKAGE_DB_*配置)
21
21
  set_db_config(host='your_host', user='your_user', password='your_password', database='your_database', port=3306)
22
22
 
23
- # 查询示例
24
- rows = sel_data('SELECT 1')
25
- print(rows)
23
+ # 更新数据函数,在完成数据库信息配置后,df为pd.dataframe格式的数据
24
+ # 更新过程会先经过check_and_sync_columns函数完成表格校验
25
+ update_datas(df, table_name, database)
26
+
26
27
  ```
27
28
 
28
29
  ## 项目结构
@@ -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.1',
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