# coding=utf-8 import csv import sys import os from base import init_env from decimal import InvalidOperation env = sys.argv[1] os.environ.setdefault('DJANGO_SETTINGS_MODULE', env) init_env(interactive=False) from apps.web.helpers import get_wechat_user_manager_mp_proxy from apps.web.user.models import MyUser from apps.web.agent.models import Agent no_agent_user = list() error_user = list() agent_map = dict() wechat_map = dict() decimal_error = 0 def get_agent(agentId): if agentId not in agent_map: try: agent = Agent.objects.get(id=agentId) except Exception as e: agent = None agent_map[agentId] = agent else: agent = agent_map.get(agentId) return agent def check_agent(agent): # 正常的no group 用户 if hasattr(agent, "wechatUserManagerialApp") and agent.wechatUserManagerialApp: return True # 该用户的 agent 不是一级代理商 else: return False def get_user_data(user): return { "userId": str(user.id), "balance": str(user.balance) if hasattr(user, "balance") else "", "gateway": str(user.gateway) if hasattr(user, "gateway") else "", "totalRecharge": str(user.total_recharged) if hasattr(user, "total_recharged") else "", "totalConsume": str(user.total_consumed) if hasattr(user, "total_consumed") else "", "addTime": str(user.dateTimeAdded)[:7] if hasattr(user, "dateTimeAdded") else "", } def check_user(user): agentId = user.agentId agent = get_agent(agentId) if not agent: data = get_user_data(user) data.update( {"agentId": agentId if agentId else ""} ) return if not check_agent(agent): data = get_user_data(user) data.update({ "agentId": str(user.agentId), "agentProductName": agent.productName if agent else "" }) error_user.append(data) return def get_productId(agent): if str(agent.id) in wechat_map: return wechat_map.get(str(agent.id)) productId = get_wechat_user_manager_mp_proxy(agent).occupantId wechat_map[str(agent.id)] = productId return productId def add_productId(user): agentId = user.agentId agent = get_agent(agentId) if not agent: return productId = get_productId(agent) user.productAgentId = productId try: user.save() except Exception as e: pass def write_csv(**kwargs): name = kwargs.keys()[0] user_lis = kwargs.get(name) if user_lis: fieldNames = user_lis[0].keys() with open("{}.csv".format(name), "w", ) as csvFile: writer = csv.DictWriter(csvFile, fieldnames=fieldNames,lineterminator='\n') writer.writeheader() writer.writerows(user_lis) def main(): index = 0 lens = 1000 while True: users = MyUser.objects.filter(groupId="")[index: index+lens] if users: try: for user in users: if hasattr(user, "groupId") and not user.groupId: # check_user(user) add_productId(user) except Exception as e: print "error index: %s" % index print e index += lens else: break # write_csv(error_user=error_user) # write_csv(no_agent_user=no_agent_user) if __name__ == '__main__': main()