fix(auth): prevent AttributeError when querying permissions for users with no role

This commit is contained in:
DXC
2026-04-14 08:56:47 +08:00
parent 0e8ddd0851
commit c91f8ec693
9 changed files with 209 additions and 23 deletions

View File

@ -0,0 +1,102 @@
import pandas as pd
import psycopg2
# 1. 数据库配置
DB_CONFIG = {
'dbname': 'inventory_system',
'user': 'test',
'password': '1234',
'host': 'localhost',
'port': '5435'
}
# 2. Excel 文件路径
EXCEL_FILE = '筛选后的库存统计.xlsx'
def fix_category_data_no_nan():
try:
print("正在读取 Excel 文件...")
# 【修改点 1】明确限制只读取到第四级
possible_category_cols = ['类别一级', '类别二级', '类别三级', '类别四级']
df_header = pd.read_excel(EXCEL_FILE, nrows=0)
actual_category_cols = [col for col in possible_category_cols if col in df_header.columns]
needed_columns = ['资产名称', '规格型号'] + actual_category_cols
df = pd.read_excel(EXCEL_FILE, dtype=str, usecols=lambda x: x in needed_columns)
df = df.where(pd.notnull(df), None)
df = df.drop_duplicates(subset=['资产名称', '规格型号'])
print(f"发现了 {len(df)} 种独立物料,准备修复类别并清除 'nan'...")
conn = psycopg2.connect(**DB_CONFIG)
cur = conn.cursor()
update_count = 0
for index, row in df.iterrows():
name = row.get('资产名称')
spec_model = row.get('规格型号')
# 清理规格型号,防止它也被 pandas 变成了 'nan'
clean_spec = None if pd.isna(spec_model) or str(spec_model).lower() == 'nan' else str(spec_model).strip()
if not name or str(name).lower() == 'nan':
continue
# --- 核心逻辑只拼接前4级并且严格过滤 nan ---
category_parts = []
for col in actual_category_cols:
val = row.get(col)
if val is not None:
str_val = str(val).strip()
# 【修改点 2】增加对 'nan' 和 'None' 字符串的拦截
if str_val != '' and str_val.lower() != 'nan' and str_val.lower() != 'none':
category_parts.append(str_val)
full_category = "/".join(category_parts)
if not full_category:
continue
prefixed_name = f"库研*{name}"
prefixed_spec = f"KY*{clean_spec}" if clean_spec else None
# 执行更新操作
update_query = """
UPDATE material_base
SET category = %s
WHERE (name = %s OR name = %s)
AND (
(spec_model = %s OR spec_model = %s)
OR (spec_model IS NULL AND %s IS NULL)
) \
"""
cur.execute(update_query, (
full_category,
name, prefixed_name,
clean_spec, prefixed_spec, clean_spec
))
update_count += cur.rowcount
conn.commit()
print(f"✅ 完美修复!清除了讨厌的 'nan',共修正了 {update_count} 条记录。")
except Exception as e:
print(f"❌ 发生错误: {e}")
if 'conn' in locals() and conn:
conn.rollback()
finally:
if 'cur' in locals() and cur:
cur.close()
if 'conn' in locals() and conn:
conn.close()
if __name__ == "__main__":
fix_category_data_no_nan()

Binary file not shown.

29
库研操作/筛选.py Normal file
View File

@ -0,0 +1,29 @@
import pandas as pd
# 1. 读取您的Excel文件
file_path = '库存统计_20260413_094414.xlsx'
df = pd.read_excel(file_path)
# 指定要进行筛选的列名(根据您的截图,列名应为“仓库位置”)
col_name = '仓库位置'
# 2. 数据清洗:确保该列都是字符串格式,并处理可能存在的空值(NaN)
# 这一步是为了防止后续字符串操作报错
df[col_name] = df[col_name].astype(str)
# 3. 进行筛选
# 条件 A: str.count('/') == 2 (说明通过斜杠分割后只有3个部分即3层)
# 条件 B: str.endswith('/1') (说明最后是以 /1 结尾的即最后一层是1)
condition = (df[col_name].str.count('/') == 2) & (df[col_name].str.endswith('/1'))
# 将满足条件的数据提取出来
filtered_df = df[condition]
# 4. 打印查看筛选后的前几行结果
print("筛选出的符合要求的数据如下:")
print(filtered_df[[col_name]])
# 5. (可选)将筛选后的结果保存为新的 Excel 文件
output_path = '筛选后的库存统计.xlsx'
filtered_df.to_excel(output_path, index=False)
print(f"\n筛选完成,结果已保存至:{output_path}")

Binary file not shown.