TelecomService.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : TelecomService.py
  4. @Time : 2024/1/24 15:12
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import time
  10. from decimal import Decimal
  11. from Ansjer.config import LOGGER
  12. from Model.models import UnicomDeviceInfo
  13. from Object.RedisObject import RedisObject
  14. from Object.TelecomObject import TelecomObject
  15. class TelecomService:
  16. @classmethod
  17. def query_total_usage_by_access_number(cls, iccid, access_number, key, expire=600):
  18. """
  19. 根据接入号码查询设备总流量使用量(实现缓存)
  20. @param iccid: 20位ICCID
  21. @param key: 缓存key
  22. @param expire: 失效时间
  23. @param access_number: 接入号码
  24. @return: 查询流量结果
  25. """
  26. redis = RedisObject()
  27. sim_flow_used_total = redis.get_data(key)
  28. if sim_flow_used_total:
  29. return Decimal(sim_flow_used_total).quantize(Decimal('0.00'))
  30. else:
  31. # 查询SIM卡信息
  32. sim_qs = UnicomDeviceInfo.objects.filter(iccid=iccid)
  33. if not sim_qs:
  34. return None
  35. sim_vo = sim_qs.first()
  36. telecom = TelecomObject()
  37. data = telecom.query_total_usage_by_date(access_number)
  38. if data and data['SvcCont']['resultCode'] == '0' and 'dataCumulationTotal' in data['SvcCont']['result']:
  39. cycle_total = data['SvcCont']['result'].get('dataCumulationTotal')
  40. else:
  41. LOGGER.info(f'query_total_usage_by_access_number查询流量异常,iccid:{iccid}')
  42. return sim_vo.sim_used_flow + sim_vo.sim_cycle_used_flow
  43. cycle_total = Decimal(cycle_total).quantize(Decimal('0.00'))
  44. n_time = int(time.time())
  45. # 判断数据库周期流量用量 是否大于API查询出来的周期用量 如果是则判定进入了下一个周期
  46. if sim_vo.sim_cycle_used_flow != 0 and sim_vo.sim_cycle_used_flow > cycle_total:
  47. sim_used_flow = sim_vo.sim_used_flow + sim_vo.sim_cycle_used_flow
  48. sim_qs.update(
  49. sim_used_flow=sim_used_flow,
  50. sim_cycle_used_flow=cycle_total,
  51. updated_time=n_time
  52. )
  53. # 队列用量历史总量 + 上一个周期流量 + 当前周期流量 = 总消耗流量
  54. sim_flow_used_total = sim_used_flow + cycle_total
  55. elif cycle_total > sim_vo.sim_cycle_used_flow: # API周期用量大于当前数据库用量则更新记录
  56. sim_qs.update(sim_cycle_used_flow=cycle_total, updated_time=n_time)
  57. # 队列用量历史总量 + 当前周期流量 = 总消耗流量
  58. sim_flow_used_total = sim_vo.sim_used_flow + cycle_total
  59. else:
  60. sim_flow_used_total = sim_vo.sim_used_flow + sim_vo.sim_cycle_used_flow
  61. redis.CONN.setnx(key, str(sim_flow_used_total))
  62. redis.CONN.expire(key, expire)
  63. return sim_flow_used_total