middleware.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # **************************************************************************
  4. # Copyright © 2016 jianglin
  5. # File Name: middleware.py
  6. # Author: jianglin
  7. # Email: xiyang0807@gmail.com
  8. # Created: 2016-11-12 13:29:17 (CST)
  9. # Last Update:星期三 2017-3-29 22:26:9 (CST)
  10. # By:
  11. # Description:
  12. # **************************************************************************
  13. from flask import g, request
  14. from flask_login import current_user
  15. from forums.api.forms import SortForm, SearchForm
  16. from .records import mark_online, load_online_users
  17. def set_form(form):
  18. within = request.args.get('within', 0, type=int)
  19. orderby = request.args.get('orderby', 0, type=int)
  20. desc = request.args.get('desc', 0, type=int)
  21. form.within.data = within
  22. form.orderby.data = orderby
  23. form.desc.data = desc
  24. return form
  25. class GlobalMiddleware(object):
  26. def preprocess_request(self):
  27. g.user = current_user
  28. g.sort_form = SortForm()
  29. g.sort_form = set_form(g.sort_form)
  30. g.search_form = SearchForm()
  31. request.user = current_user._get_current_object()
  32. if request.method == 'GET':
  33. request.data = request.args.to_dict()
  34. else:
  35. request.data = request.json
  36. if request.data is None:
  37. request.data = request.form.to_dict()
  38. class OnlineMiddleware(object):
  39. def preprocess_request(self):
  40. if g.user.is_authenticated:
  41. mark_online(g.user.username)
  42. else:
  43. mark_online(request.remote_addr)
  44. g.get_online = get_online()
  45. def get_online():
  46. return (load_online_users(1), load_online_users(2), load_online_users(3),
  47. load_online_users(4), load_online_users(5))