jinja.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # **************************************************************************
  4. # Copyright © 2016 jianglin
  5. # File Name: jinja.py
  6. # Author: jianglin
  7. # Email: mail@honmaple.com
  8. # Created: 2016-11-07 21:00:32 (CST)
  9. # Last Update: Monday 2022-12-12 16:11:32 (CST)
  10. # By:
  11. # Description:
  12. # **************************************************************************
  13. from datetime import datetime
  14. from forums import default
  15. from bleach import clean
  16. from flask import Markup, g
  17. from flask_babel import format_datetime
  18. from markdown import markdown as m
  19. def safe_clean(text):
  20. tags = ['b', 'i', 'font', 'br', 'blockquote', 'div', 'h2', 'a', 'p']
  21. attrs = {'*': ['style', 'id', 'class'], 'font': ['color'], 'a': ['href']}
  22. styles = ['color']
  23. return Markup(clean(text, tags=tags, attributes=attrs, styles=styles))
  24. def markdown(text, clean=True):
  25. html = m(text, extensions=['markdown.extensions.fenced_code'])
  26. if clean:
  27. return Markup(safe_clean(html))
  28. return Markup(html)
  29. def timesince(dt, default="just now"):
  30. now = datetime.utcnow()
  31. diff = now - dt
  32. if diff.days > 10:
  33. return format_datetime(dt, 'Y-M-d H:m')
  34. elif diff.days <= 10 and diff.days > 0:
  35. periods = ((diff.days, "day", "days"), )
  36. elif diff.days <= 0 and diff.seconds > 3600:
  37. periods = ((diff.seconds / 3600, "hour", "hours"), )
  38. elif diff.seconds <= 3600 and diff.seconds > 90:
  39. periods = ((diff.seconds / 60, "minute", "minutes"), )
  40. else:
  41. return default
  42. for period, singular, plural in periods:
  43. if period:
  44. return "%d %s ago" % (period, singular if period == 1 else plural)
  45. return default
  46. def show_time():
  47. if g.user.is_authenticated:
  48. return 'LOCALE:' + format_datetime(datetime.utcnow())
  49. return 'UTC:' + format_datetime(datetime.utcnow())
  50. def hot_tags():
  51. from forums.api.tag.db import Tags
  52. tags = Tags.query.limit(9).all()
  53. return tags
  54. def recent_tags():
  55. from forums.api.tag.db import Tags
  56. tags = Tags.query.limit(12).all()
  57. return tags
  58. def forums_count():
  59. from forums.extension import redis_data
  60. key = 'count:forums'
  61. return redis_data.hgetall(key)
  62. def init_app(app):
  63. app.jinja_env.globals['DEFAULT'] = default
  64. app.jinja_env.globals['hot_tags'] = hot_tags
  65. app.jinja_env.globals['recent_tags'] = recent_tags
  66. app.jinja_env.globals['show_time'] = show_time
  67. app.jinja_env.globals['forums_count'] = forums_count
  68. app.jinja_env.filters['timesince'] = timesince
  69. app.jinja_env.filters['safe_clean'] = safe_clean