locals.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.forum.locals
  4. ~~~~~~~~~~~~~~~~~~~~
  5. Thread local helpers for FlaskBB
  6. :copyright: 2017, the FlaskBB Team
  7. :license: BSD, see license for more details
  8. """
  9. from flask import _request_ctx_stack, has_request_context, request
  10. from werkzeug.local import LocalProxy
  11. from .models import Category, Forum, Post, Topic
  12. @LocalProxy
  13. def current_post():
  14. return _get_item(Post, 'post_id', 'post')
  15. @LocalProxy
  16. def current_topic():
  17. if current_post:
  18. return current_post.topic
  19. return _get_item(Topic, 'topic_id', 'topic')
  20. @LocalProxy
  21. def current_forum():
  22. if current_topic:
  23. return current_topic.forum
  24. return _get_item(Forum, 'forum_id', 'forum')
  25. @LocalProxy
  26. def current_category():
  27. if current_forum:
  28. return current_forum.category
  29. return _get_item(Category, 'category_id', 'category')
  30. def _get_item(model, view_arg, name):
  31. if (
  32. has_request_context() and
  33. not getattr(_request_ctx_stack.top, name, None) and
  34. view_arg in request.view_args
  35. ):
  36. setattr(
  37. _request_ctx_stack.top,
  38. name,
  39. model.query.filter_by(id=request.view_args[view_arg]).first()
  40. )
  41. return getattr(_request_ctx_stack.top, name, None)