app.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. from flask_debugtoolbar import DebugToolbarExtension
  15. # Import the user blueprint
  16. from flaskbb.user.views import user
  17. from flaskbb.user.models import User, Guest, PrivateMessage
  18. # Import the auth blueprint
  19. from flaskbb.auth.views import auth
  20. # Import the admin blueprint
  21. from flaskbb.admin.views import admin
  22. # Import the forum blueprint
  23. from flaskbb.forum.views import forum
  24. from flaskbb.extensions import db, login_manager, mail, cache
  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. configure_app(app, config)
  45. configure_extensions(app)
  46. configure_blueprints(app, blueprints)
  47. configure_template_filters(app)
  48. configure_before_handlers(app)
  49. configure_errorhandlers(app)
  50. configure_logging(app)
  51. return app
  52. def configure_app(app, config):
  53. """
  54. Configures the app. If no configuration file is choosen,
  55. the app will use the example configuration.
  56. """
  57. # Get the configuration file
  58. if config is None:
  59. from flaskbb.configs.default import DefaultConfig
  60. app.config.from_object(DefaultConfig)
  61. app.logger.info("No configuration specified. Using the Default config")
  62. else:
  63. app.config.from_object(config)
  64. def configure_extensions(app):
  65. """
  66. Configures the extensions
  67. """
  68. # Flask-SQLAlchemy
  69. db.init_app(app)
  70. # Flask-Mail
  71. mail.init_app(app)
  72. # Flask-Cache
  73. cache.init_app(app)
  74. # Flask-Debugtoolbar
  75. DebugToolbarExtension(app)
  76. # Flask-Login
  77. login_manager.login_view = app.config["LOGIN_VIEW"]
  78. login_manager.refresh_view = app.config["REAUTH_VIEW"]
  79. login_manager.anonymous_user = Guest
  80. @login_manager.user_loader
  81. def load_user(id):
  82. """
  83. Loads the user. Required by the `login` extension
  84. """
  85. unread_count = db.session.query(db.func.count(PrivateMessage.id)).\
  86. filter(PrivateMessage.unread == True,
  87. PrivateMessage.user_id == id).subquery()
  88. u = db.session.query(User, unread_count).filter(User.id == id).first()
  89. if u:
  90. user, user.pm_unread = u
  91. return user
  92. else:
  93. return None
  94. login_manager.init_app(app)
  95. def configure_blueprints(app, blueprints):
  96. """
  97. Configures the blueprints
  98. """
  99. for blueprint, url_prefix in blueprints:
  100. app.register_blueprint(blueprint, url_prefix=url_prefix)
  101. def configure_template_filters(app):
  102. """
  103. Configures the template filters
  104. """
  105. app.jinja_env.filters['markup'] = render_markup
  106. app.jinja_env.filters['format_date'] = format_date
  107. app.jinja_env.filters['time_since'] = time_since
  108. app.jinja_env.filters['is_online'] = is_online
  109. app.jinja_env.filters['crop_title'] = crop_title
  110. app.jinja_env.filters['is_unread'] = is_unread
  111. # Permission filters
  112. app.jinja_env.filters['edit_post'] = can_edit_post
  113. app.jinja_env.filters['delete_post'] = can_delete_post
  114. app.jinja_env.filters['delete_topic'] = can_delete_topic
  115. app.jinja_env.filters['post_reply'] = can_post_reply
  116. app.jinja_env.filters['post_topic'] = can_post_topic
  117. def configure_before_handlers(app):
  118. """
  119. Configures the before request handlers
  120. """
  121. @app.before_request
  122. def update_lastseen():
  123. """
  124. Updates `lastseen` before every reguest if the user is authenticated
  125. """
  126. if current_user.is_authenticated():
  127. current_user.lastseen = datetime.datetime.utcnow()
  128. db.session.add(current_user)
  129. db.session.commit()
  130. @app.before_request
  131. def get_user_permissions():
  132. current_user.permissions = current_user.get_permissions()
  133. if app.config["USE_REDIS"]:
  134. @app.before_request
  135. def mark_current_user_online():
  136. if current_user.is_authenticated():
  137. mark_online(current_user.username)
  138. else:
  139. mark_online(request.remote_addr, guest=True)
  140. def configure_errorhandlers(app):
  141. """
  142. Configures the error handlers
  143. """
  144. @app.errorhandler(403)
  145. def forbidden_page(error):
  146. return render_template("errors/forbidden_page.html"), 403
  147. @app.errorhandler(404)
  148. def page_not_found(error):
  149. return render_template("errors/page_not_found.html"), 404
  150. @app.errorhandler(500)
  151. def server_error_page(error):
  152. return render_template("errors/server_error.html"), 500
  153. def configure_logging(app):
  154. """
  155. Configures logging.
  156. """
  157. logs_folder = os.path.join(app.root_path, os.pardir, "logs")
  158. from logging.handlers import SMTPHandler
  159. formatter = logging.Formatter(
  160. '%(asctime)s %(levelname)s: %(message)s '
  161. '[in %(pathname)s:%(lineno)d]')
  162. info_log = os.path.join(logs_folder, app.config['INFO_LOG'])
  163. info_file_handler = logging.handlers.RotatingFileHandler(
  164. info_log,
  165. maxBytes=100000,
  166. backupCount=10
  167. )
  168. info_file_handler.setLevel(logging.INFO)
  169. info_file_handler.setFormatter(formatter)
  170. app.logger.addHandler(info_file_handler)
  171. error_log = os.path.join(logs_folder, app.config['ERROR_LOG'])
  172. error_file_handler = logging.handlers.RotatingFileHandler(
  173. error_log,
  174. maxBytes=100000,
  175. backupCount=10
  176. )
  177. error_file_handler.setLevel(logging.ERROR)
  178. error_file_handler.setFormatter(formatter)
  179. app.logger.addHandler(error_file_handler)
  180. if app.config["SEND_LOGS"]:
  181. mail_handler = \
  182. SMTPHandler(app.config['MAIL_SERVER'],
  183. app.config['DEFAULT_MAIL_SENDER'],
  184. app.config['ADMINS'],
  185. 'application error, no admins specified',
  186. (
  187. app.config['MAIL_USERNAME'],
  188. app.config['MAIL_PASSWORD'],
  189. ))
  190. mail_handler.setLevel(logging.ERROR)
  191. mail_handler.setFormatter(formatter)
  192. app.logger.addHandler(mail_handler)