__init__.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #-*- coding:utf-8 -*-
  2. # Copyright 2017 Xiaomi, Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import datetime
  16. import time
  17. from flask import g, session, request, redirect
  18. from rrd import app, config
  19. from rrd.view.utils import get_usertoken_from_session, get_current_user_profile
  20. @app.template_filter('fmt_time')
  21. def fmt_time_filter(value, pattern="%Y-%m-%d %H:%M"):
  22. if not value:
  23. return ''
  24. return datetime.datetime.fromtimestamp(value).strftime(pattern)
  25. @app.template_filter('time_duration')
  26. def time_duration(v):
  27. d = time.time() - time.mktime(v.timetuple())
  28. if d <= 60:
  29. return "just now"
  30. if d <= 120:
  31. return "1 minute ago"
  32. if d <= 3600:
  33. return "%d minutes ago" % (d/60)
  34. if d <= 7200:
  35. return "1 hour ago"
  36. if d <= 3600*24:
  37. return "%d hours ago" % (d/3600)
  38. if d <= 3600*24*2:
  39. return "1 day ago"
  40. return "%d days ago" % (d/3600/24)
  41. @app.teardown_request
  42. def app_teardown(exception):
  43. from rrd.store import db, alarm_db
  44. db.commit()
  45. alarm_db.commit()
  46. @app.before_request
  47. def app_before():
  48. g.user_token = get_usertoken_from_session(session)
  49. g.user = get_current_user_profile(g.user_token)
  50. g.locale = request.accept_languages.best_match(config.LANGUAGES.keys())
  51. path = request.path
  52. if not g.user and not path.startswith("/auth/login") and \
  53. not path.startswith("/static/") and \
  54. not path.startswith("/portal/links/") and \
  55. not path.startswith("/auth/register"):
  56. return redirect("/auth/login")
  57. if path.startswith("/screen"):
  58. g.nav_menu = "nav_screen"
  59. elif path.startswith("/portal/hostgroup") or path.startswith("/portal/group"):
  60. g.nav_menu = "p_hostgroup"
  61. elif path.startswith("/portal/template"):
  62. g.nav_menu = "p_template"
  63. elif path.startswith("/portal/expression"):
  64. g.nav_menu = "p_expression"
  65. elif path.startswith("/portal/nodata"):
  66. g.nav_menu = "p_nodata"
  67. elif path.startswith("/portal/alarm-dash"):
  68. g.nav_menu = "p_alarm-dash"
  69. else:
  70. g.nav_menu = ""