app.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.app
  4. ~~~~~~~~~~~~~~~~~~~~
  5. manages the app creation and configuration process
  6. :copyright: (c) 2013 by the FlaskBB Team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import os
  10. import logging
  11. import datetime
  12. from flask import Flask, render_template, request
  13. from flask.ext.login import current_user
  14. # Import the user blueprint
  15. from flaskbb.user.views import user
  16. from flaskbb.user.models import User, Guest, PrivateMessage
  17. # Import the auth blueprint
  18. from flaskbb.auth.views import auth
  19. # Import the admin blueprint
  20. from flaskbb.admin.views import admin
  21. # Import the forum blueprint
  22. from flaskbb.forum.views import forum
  23. from flaskbb.extensions import (db, login_manager, mail, cache, redis,
  24. debugtoolbar)
  25. from flaskbb.utils.helpers import (format_date, time_since, crop_title,
  26. can_post_reply, can_post_topic,
  27. can_delete_topic, can_delete_post, is_online,
  28. can_edit_post, render_markup, mark_online,
  29. is_unread)
  30. DEFAULT_BLUEPRINTS = (
  31. (forum, ""),
  32. (auth, ""),
  33. (user, "/user"),
  34. (admin, "/admin")
  35. )
  36. def create_app(config=None, blueprints=None):
  37. """
  38. Creates the app.
  39. """
  40. if blueprints is None:
  41. blueprints = DEFAULT_BLUEPRINTS
  42. # Initialize the app
  43. app = Flask("flaskbb")
  44. # Use the default config and override it afterwards
  45. app.config.from_object('flaskbb.configs.default.DefaultConfig')
  46. # Update the config
  47. app.config.from_object(config)
  48. # try to update the config via the environment variable
  49. app.config.from_envvar("FLASKBB_SETTINGS", silent=True)
  50. for blueprint, url_prefix in blueprints:
  51. app.register_blueprint(blueprint, url_prefix=url_prefix)
  52. configure_extensions(app)
  53. configure_template_filters(app)
  54. configure_before_handlers(app)
  55. configure_errorhandlers(app)
  56. configure_logging(app)
  57. return app
  58. def configure_extensions(app):
  59. """
  60. Configures the extensions
  61. """
  62. # Flask-SQLAlchemy
  63. db.init_app(app)
  64. # Flask-Mail
  65. mail.init_app(app)
  66. # Flask-Cache
  67. cache.init_app(app)
  68. # Flask-Debugtoolbar
  69. debugtoolbar.init_app(app)
  70. # Flask-And-Redis
  71. redis.init_app(app)
  72. # Flask-Login
  73. login_manager.login_view = app.config["LOGIN_VIEW"]
  74. login_manager.refresh_view = app.config["REAUTH_VIEW"]
  75. login_manager.anonymous_user = Guest
  76. @login_manager.user_loader
  77. def load_user(id):
  78. """
  79. Loads the user. Required by the `login` extension
  80. """
  81. unread_count = db.session.query(db.func.count(PrivateMessage.id)).\
  82. filter(PrivateMessage.unread == True,
  83. PrivateMessage.user_id == id).subquery()
  84. u = db.session.query(User, unread_count).filter(User.id == id).first()
  85. if u:
  86. user, user.pm_unread = u
  87. return user
  88. else:
  89. return None
  90. login_manager.init_app(app)
  91. def configure_template_filters(app):
  92. """
  93. Configures the template filters
  94. """
  95. app.jinja_env.filters['markup'] = render_markup
  96. app.jinja_env.filters['format_date'] = format_date
  97. app.jinja_env.filters['time_since'] = time_since
  98. app.jinja_env.filters['is_online'] = is_online
  99. app.jinja_env.filters['crop_title'] = crop_title
  100. app.jinja_env.filters['is_unread'] = is_unread
  101. # Permission filters
  102. app.jinja_env.filters['edit_post'] = can_edit_post
  103. app.jinja_env.filters['delete_post'] = can_delete_post
  104. app.jinja_env.filters['delete_topic'] = can_delete_topic
  105. app.jinja_env.filters['post_reply'] = can_post_reply
  106. app.jinja_env.filters['post_topic'] = can_post_topic
  107. def configure_before_handlers(app):
  108. """
  109. Configures the before request handlers
  110. """
  111. @app.before_request
  112. def update_lastseen():
  113. """
  114. Updates `lastseen` before every reguest if the user is authenticated
  115. """
  116. if current_user.is_authenticated():
  117. current_user.lastseen = datetime.datetime.utcnow()
  118. db.session.add(current_user)
  119. db.session.commit()
  120. @app.before_request
  121. def get_user_permissions():
  122. current_user.permissions = current_user.get_permissions()
  123. if app.config["USE_REDIS"]:
  124. @app.before_request
  125. def mark_current_user_online():
  126. if current_user.is_authenticated():
  127. mark_online(current_user.username)
  128. else:
  129. mark_online(request.remote_addr, guest=True)
  130. def configure_errorhandlers(app):
  131. """
  132. Configures the error handlers
  133. """
  134. @app.errorhandler(403)
  135. def forbidden_page(error):
  136. return render_template("errors/forbidden_page.html"), 403
  137. @app.errorhandler(404)
  138. def page_not_found(error):
  139. return render_template("errors/page_not_found.html"), 404
  140. @app.errorhandler(500)
  141. def server_error_page(error):
  142. return render_template("errors/server_error.html"), 500
  143. def configure_logging(app):
  144. """
  145. Configures logging.
  146. """
  147. logs_folder = os.path.join(app.root_path, os.pardir, "logs")
  148. from logging.handlers import SMTPHandler
  149. formatter = logging.Formatter(
  150. '%(asctime)s %(levelname)s: %(message)s '
  151. '[in %(pathname)s:%(lineno)d]')
  152. info_log = os.path.join(logs_folder, app.config['INFO_LOG'])
  153. info_file_handler = logging.handlers.RotatingFileHandler(
  154. info_log,
  155. maxBytes=100000,
  156. backupCount=10
  157. )
  158. info_file_handler.setLevel(logging.INFO)
  159. info_file_handler.setFormatter(formatter)
  160. app.logger.addHandler(info_file_handler)
  161. error_log = os.path.join(logs_folder, app.config['ERROR_LOG'])
  162. error_file_handler = logging.handlers.RotatingFileHandler(
  163. error_log,
  164. maxBytes=100000,
  165. backupCount=10
  166. )
  167. error_file_handler.setLevel(logging.ERROR)
  168. error_file_handler.setFormatter(formatter)
  169. app.logger.addHandler(error_file_handler)
  170. if app.config["SEND_LOGS"]:
  171. mail_handler = \
  172. SMTPHandler(app.config['MAIL_SERVER'],
  173. app.config['DEFAULT_MAIL_SENDER'],
  174. app.config['ADMINS'],
  175. 'application error, no admins specified',
  176. (
  177. app.config['MAIL_USERNAME'],
  178. app.config['MAIL_PASSWORD'],
  179. ))
  180. mail_handler.setLevel(logging.ERROR)
  181. mail_handler.setFormatter(formatter)
  182. app.logger.addHandler(mail_handler)