74 lines
2.2 KiB
Python
74 lines
2.2 KiB
Python
"""
|
|
工具函数:密码哈希、ID 生成、智能列名识别
|
|
"""
|
|
import hashlib
|
|
import uuid
|
|
import random
|
|
import string
|
|
from difflib import SequenceMatcher
|
|
from config import FIELD_KEYWORDS
|
|
|
|
|
|
def get_client_ip():
|
|
"""获取真实客户端 IP。
|
|
nginx 反代场景下 request.remote_addr 是代理地址(如 127.0.0.1),
|
|
优先取代理注入的 X-Real-IP,其次 X-Forwarded-For 的首个地址,最后回退 remote_addr。"""
|
|
from flask import request
|
|
real_ip = (request.headers.get('X-Real-IP') or '').strip()
|
|
if real_ip:
|
|
return real_ip
|
|
forwarded = (request.headers.get('X-Forwarded-For') or '').strip()
|
|
if forwarded:
|
|
# 多级代理时为逗号分隔链,首个为客户端原始 IP
|
|
return forwarded.split(',')[0].strip()
|
|
return request.remote_addr or ''
|
|
|
|
|
|
def hash_password(password):
|
|
"""密码哈希"""
|
|
return hashlib.sha256(password.encode('utf-8')).hexdigest()
|
|
|
|
|
|
def generate_session_id():
|
|
"""生成会话ID"""
|
|
return uuid.uuid4().hex
|
|
|
|
|
|
def generate_form_id():
|
|
"""生成随机表单ID"""
|
|
return ''.join(random.choices(string.ascii_letters + string.digits, k=8))
|
|
|
|
|
|
def generate_preset_id():
|
|
"""生成预设ID"""
|
|
return 'preset_' + ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
|
|
|
|
|
|
def smart_field_detection(columns):
|
|
"""智能识别列名对应关系"""
|
|
result = {}
|
|
columns_lower = [str(col).lower().strip() for col in columns]
|
|
|
|
for field_type, keywords in FIELD_KEYWORDS.items():
|
|
best_match = None
|
|
best_ratio = 0
|
|
|
|
for i, col in enumerate(columns_lower):
|
|
for keyword in keywords:
|
|
if keyword.lower() == col:
|
|
best_match = columns[i]
|
|
best_ratio = 1.0
|
|
break
|
|
if keyword.lower() in col or col in keyword.lower():
|
|
ratio = SequenceMatcher(None, keyword.lower(), col).ratio()
|
|
if ratio > best_ratio and ratio > 0.6:
|
|
best_ratio = ratio
|
|
best_match = columns[i]
|
|
if best_ratio == 1.0:
|
|
break
|
|
|
|
if best_match:
|
|
result[field_type] = best_match
|
|
|
|
return result
|