upgrade_count.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 13:47:2 (CST)
  10. # By:
  11. # Description:
  12. # **************************************************************************
  13. from runserver import app
  14. from forums.api.topic.models import Topic, Reply
  15. from forums.api.forums.models import Board
  16. from forums.api.user.models import User
  17. from forums.extension import redis_data
  18. def topic():
  19. topics = Topic.query.all()
  20. for t in topics:
  21. print('topic', t.title)
  22. key = 'count:topic:{}'.format(t.id)
  23. reply_count = t.replies.count()
  24. read_key = 'topic:{}'.format(t.id)
  25. read_count = redis_data.hget(read_key, 'read')
  26. if reply_count:
  27. redis_data.hset(key, 'replies', reply_count)
  28. if read_count:
  29. redis_data.hset(key, 'read', read_count)
  30. # 删除旧key
  31. redis_data.delete(read_key)
  32. def reply():
  33. replies = Reply.query.all()
  34. for t in replies:
  35. print('reply', t.id)
  36. key = 'count:reply:{}'.format(t.id)
  37. liker_count = t.likers.count()
  38. if liker_count:
  39. redis_data.hset(key, 'liker', liker_count)
  40. def user():
  41. users = User.query.all()
  42. for t in users:
  43. print('user', t.username)
  44. key = 'count:user:{}'.format(t.id)
  45. topic_count = t.topics.count()
  46. reply_count = t.replies.count()
  47. if topic_count:
  48. redis_data.hset(key, 'topic', topic_count)
  49. if reply_count:
  50. redis_data.hset(key, 'replies', topic_count)
  51. # 删除旧key
  52. old_user_key = 'user:{}'.format(t.id)
  53. redis_data.delete(old_user_key)
  54. def board():
  55. boards = Board.query.all()
  56. for b in boards:
  57. print('board', b.name)
  58. key = 'count:board:{}'.format(b.id)
  59. topic_count = Topic.query.filter_by(board_id=b.id).count()
  60. reply_count = Reply.query.filter_by(topic__board_id=b.id).count()
  61. post_count = topic_count + reply_count
  62. if topic_count:
  63. redis_data.hset(key, 'topic', topic_count)
  64. if post_count:
  65. redis_data.hset(key, 'post', topic_count)
  66. def main():
  67. with app.app_context():
  68. topic()
  69. board()
  70. user()
  71. reply()
  72. if __name__ == '__main__':
  73. main()