limit.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 = {
  26. "余海涛": "352",
  27. "罗情": "353",
  28. "范军": "53",
  29. "鲁涛": "51"
  30. }
  31. def find_tag(self, uid):
  32. """
  33. 判断 uid 是否存在changsha_user_accounts中
  34. """
  35. sql = f"""select user_name from changsha_user_accounts where piaoquan_account_id = {uid};"""
  36. result = MysqlHelper.get_values(
  37. log_type=self.mode, crawler=self.platform, env="prod", sql=sql
  38. )
  39. return result
  40. def author_limitation(self, user_id):
  41. """
  42. 限制账号, 服务长沙四名同学
  43. """
  44. if self.mode == "author":
  45. result = self.find_tag(user_id)
  46. if result:
  47. user_name = result[0]['user_name']
  48. AliyunLogger.logging(
  49. code="8807",
  50. platform=self.platform,
  51. mode=self.mode,
  52. env="prod",
  53. message="找到个人账号,{}".format(user_name)
  54. )
  55. R = RedisClient()
  56. if R.connect():
  57. tag = self.limit_tag_dict[user_name]
  58. tag_count = R.select(tag)
  59. if tag_count:
  60. tag_count = int(tag_count.decode("utf-8"))
  61. if tag_count <= 300:
  62. tag_count += 1
  63. expire_seconds = generate_expire_time()
  64. R.insert(
  65. key=tag, value=tag_count, expire_time=expire_seconds
  66. )
  67. return True
  68. else:
  69. # 报警
  70. return False
  71. else:
  72. tag_count = 1
  73. expire_seconds = generate_expire_time()
  74. R.insert(
  75. key=tag, value=tag_count, expire_time=expire_seconds
  76. )
  77. return True
  78. else:
  79. return True
  80. else:
  81. return True
  82. else:
  83. return True