upgrade_count.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # **************************************************************************
  4. # Copyright © 2017 jianglin
  5. # File Name: upgrade_coount.py
  6. # Author: jianglin
  7. # Email: xiyang0807@gmail.com
  8. # Created: 2017-04-02 13:00:02 (CST)
  9. # Last Update:星期日 2017-4-2 15:52:41 (CST)
  10. # By:
  11. # Description:
  12. # **************************************************************************
  13. from forums.api.topic.models import Topic, Reply
  14. from forums.api.forums.models import Board
  15. from forums.api.user.models import User
  16. from forums.extension import redis_data
  17. from runserver import app
  18. def forums():
  19. key = 'count:forums'
  20. redis_data.hset(key, 'user', User.query.count())
  21. redis_data.hset(key, 'topic', Topic.query.count())
  22. redis_data.hset(key, 'post', Reply.query.count() + Topic.query.count())
  23. def topic():
  24. topics = Topic.query.all()
  25. for t in topics:
  26. print('topic', t.title)
  27. key = 'count:topic:{}'.format(t.id)
  28. reply_count = t.replies.count()
  29. read_key = 'topic:{}'.format(t.id)
  30. read_count = redis_data.hget(read_key, 'read')
  31. if reply_count:
  32. redis_data.hset(key, 'replies', reply_count)
  33. if read_count:
  34. redis_data.hset(key, 'read', read_count)
  35. # 删除旧key
  36. redis_data.delete(read_key)
  37. def reply():
  38. replies = Reply.query.all()
  39. for t in replies:
  40. print('reply', t.id)
  41. key = 'count:reply:{}'.format(t.id)
  42. liker_count = t.likers.count()
  43. if liker_count:
  44. redis_data.hset(key, 'liker', liker_count)
  45. def user():
  46. users = User.query.all()
  47. for t in users:
  48. print('user', t.username)
  49. key = 'count:user:{}'.format(t.id)
  50. topic_count = t.topics.count()
  51. reply_count = t.replies.count()
  52. if topic_count:
  53. redis_data.hset(key, 'topic', topic_count)
  54. if reply_count:
  55. redis_data.hset(key, 'replies', topic_count)
  56. # 删除旧key
  57. old_user_key = 'user:{}'.format(t.id)
  58. redis_data.delete(old_user_key)
  59. def board():
  60. boards = Board.query.all()
  61. for b in boards:
  62. print('board', b.name)
  63. key = 'count:board:{}'.format(b.id)
  64. topic_count = Topic.query.filter_by(board_id=b.id).count()
  65. reply_count = Reply.query.filter_by(topic__board_id=b.id).count()
  66. post_count = topic_count + reply_count
  67. if topic_count:
  68. redis_data.hset(key, 'topic', topic_count)
  69. if post_count:
  70. redis_data.hset(key, 'post', topic_count)
  71. def main():
  72. with app.app_context():
  73. forums()
  74. topic()
  75. board()
  76. user()
  77. reply()
  78. if __name__ == '__main__':
  79. main()