limit.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import os
  2. import sys
  3. from datetime import datetime, timedelta
  4. sys.path.append(os.getcwd())
  5. from common.aliyun_log import AliyunLogger
  6. from common.scheduling_db import MysqlHelper
  7. from common.db import RedisClient
  8. def generate_expire_time():
  9. """
  10. 计算出过期时间
  11. """
  12. now = datetime.now()
  13. # 当天晚上12点的时间
  14. midnight = datetime(now.year, now.month, now.day) + timedelta(days=1)
  15. # 计算当前时间到当天晚上12点的秒数
  16. seconds_until_midnight = int((midnight - now).total_seconds())
  17. return seconds_until_midnight
  18. class AuthorLimit(object):
  19. """
  20. 账号爬虫限量
  21. """
  22. def __init__(self, mode, platform):
  23. self.mode = mode
  24. self.platform = platform
  25. self.limit_tag_dict = {"352": "余海涛", "353": "罗情", "53": "范军", "51": "鲁涛"}
  26. def find_tag(self, uid):
  27. """
  28. 通过 uid 去找符合标准的 tag
  29. """
  30. sql = f"""select tag from crawler_user_v3 where uid={uid};"""
  31. result = MysqlHelper.get_values(
  32. log_type=self.mode, crawler=self.platform, env="prod", sql=sql
  33. )
  34. tags = result[0]["tag"]
  35. if tags:
  36. tags = tags.split(",")
  37. for tag in tags:
  38. if self.limit_tag_dict.get(tag):
  39. return tag
  40. return None
  41. def author_limitation(self, user_id):
  42. """
  43. 限制账号, 服务长沙四名同学
  44. """
  45. if self.mode == "author":
  46. tag = self.find_tag(user_id)
  47. if tag:
  48. AliyunLogger.logging(
  49. code="8807",
  50. platform=self.platform,
  51. mode=self.mode,
  52. env="prod",
  53. message="找到个人账号,{}".format(tag)
  54. )
  55. R = RedisClient()
  56. if R.connect():
  57. tag_count = R.select(tag)
  58. if tag_count:
  59. tag_count = int(tag_count.decode("utf-8"))
  60. if tag_count <= 300:
  61. tag_count += 1
  62. expire_seconds = generate_expire_time()
  63. R.insert(
  64. key=tag, value=tag_count, expire_time=expire_seconds
  65. )
  66. return True
  67. else:
  68. # 报警
  69. return False
  70. else:
  71. tag_count = 1
  72. expire_seconds = generate_expire_time()
  73. R.insert(
  74. key=tag, value=tag_count, expire_time=expire_seconds
  75. )
  76. return True
  77. else:
  78. return True
  79. else:
  80. return True
  81. else:
  82. return True