cm/app.py

71 lines
2.9 KiB
Python

from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
# 全局变量,存储传递进来的嵌套字典数据
customer_data = []
@app.route('/')
def index():
# 默认展示第一个客户
return redirect(url_for('view_customer', index=0))
@app.route('/customer/<int:index>')
def view_customer(index):
# 判断是否有数据
if not customer_data:
return "No customer data provided.", 400
# 确保 index 在合法范围内
if index < 0 or index >= len(customer_data):
return "Index out of range.", 400
customer = customer_data[index]
# 为每个 email addresses 列表中的项添加唯一的索引
for domain, info in customer.items():
print(f"..........domain={domain}")
print(f"..........info={info}")
if 'email addresses' in info and isinstance(info['email addresses'], list):
for email_idx, email in enumerate(info['email addresses']):
email['idx'] = email_idx # 给每个 email 项添加唯一的索引
is_first = index == 0
is_last = index == len(customer_data) - 1
return render_template('edit_customers.html',
customer=customer,
index=index,
is_first=is_first,
is_last=is_last)
@app.route('/update/<int:index>', methods=['POST'])
def update_customers(index):
updated_data = request.form.to_dict(flat=False)
# 更新嵌套字典数据
if 0 <= index < len(customer_data):
customer = customer_data[index]
for domain, info in customer.items():
print(f"..........domain={domain}")
print(f"..........info={info}")
if 'customer industry' in info:
info['customer industry'] = updated_data.get(f'{domain}_industry', [info['customer industry']])[0]
if 'email addresses' in info and isinstance(info['email addresses'], list):
for j, email in enumerate(info['email addresses']):
email["owner's name"] = updated_data.get(f'{domain}_owner_name_{j}', [email["owner's name"]])[0]
email['email address'] = updated_data.get(f'{domain}_email_address_{j}', [email['email address']])[0]
email['category'] = updated_data.get(f'{domain}_category_{j}', [email['category']])[0]
email['promotion history'] = updated_data.get(f'{domain}_promotion_history_{j}', [', '.join(email['promotion history'])])[0].split(', ')
return redirect(url_for('view_customer', index=index))
def set_customer_data(data):
global customer_data
# 确保数据为嵌套字典格式
if isinstance(data, list) and all(isinstance(customer, dict) for customer in data):
customer_data = data
else:
raise ValueError("Data must be a list of dictionaries.")