app.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.app
  4. ~~~~~~~~~~~~~~~~~~~~
  5. manages the app creation and configuration process
  6. :copyright: (c) 2014 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, 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.forum.models import Post, Topic, Category, Forum
  24. # extenesions
  25. from flaskbb.extensions import db, login_manager, mail, cache, redis, \
  26. debugtoolbar, migrate, themes, plugin_manager
  27. from flask.ext.whooshalchemy import whoosh_index
  28. # various helpers
  29. from flaskbb.utils.helpers import format_date, time_since, crop_title, \
  30. is_online, render_markup, mark_online, forum_is_unread, topic_is_unread, \
  31. render_template
  32. # permission checks (here they are used for the jinja filters)
  33. from flaskbb.utils.permissions import can_post_reply, can_post_topic, \
  34. can_delete_topic, can_delete_post, can_edit_post, can_lock_topic, \
  35. can_move_topic
  36. from flaskbb.plugins import hooks
  37. def create_app(config=None):
  38. """
  39. Creates the app.
  40. """
  41. # Initialize the app
  42. app = Flask("flaskbb")
  43. # Use the default config and override it afterwards
  44. app.config.from_object('flaskbb.configs.default.DefaultConfig')
  45. # Update the config
  46. app.config.from_object(config)
  47. # try to update the config via the environment variable
  48. app.config.from_envvar("FLASKBB_SETTINGS", silent=True)
  49. configure_blueprints(app)
  50. configure_extensions(app)
  51. configure_template_filters(app)
  52. configure_before_handlers(app)
  53. configure_errorhandlers(app)
  54. configure_logging(app)
  55. app.logger.debug("Loading plugins...")
  56. plugin_manager.init_app(app)
  57. # Just a temporary solution to enable the plugins.
  58. plugin_manager.enable_plugins()
  59. app.logger.debug(
  60. "({}) {} Plugins loaded."
  61. .format(len(plugin_manager.plugins),
  62. plugin_manager.plugins)
  63. )
  64. app.jinja_env.globals.update(hooks=hooks)
  65. return app
  66. def configure_blueprints(app):
  67. app.register_blueprint(forum, url_prefix=app.config["FORUM_URL_PREFIX"])
  68. app.register_blueprint(user, url_prefix=app.config["USER_URL_PREFIX"])
  69. app.register_blueprint(auth, url_prefix=app.config["AUTH_URL_PREFIX"])
  70. app.register_blueprint(admin, url_prefix=app.config["ADMIN_URL_PREFIX"])
  71. def configure_extensions(app):
  72. """
  73. Configures the extensions
  74. """
  75. # Flask-SQLAlchemy
  76. db.init_app(app)
  77. # Flask-Migrate
  78. migrate.init_app(app, db)
  79. # Flask-Mail
  80. mail.init_app(app)
  81. # Flask-Cache
  82. cache.init_app(app)
  83. # Flask-Debugtoolbar
  84. debugtoolbar.init_app(app)
  85. # Flask-Themes
  86. themes.init_themes(app, app_identifier="flaskbb")
  87. # Flask-And-Redis
  88. redis.init_app(app)
  89. # Flask-WhooshAlchemy
  90. with app.app_context():
  91. whoosh_index(app, Post)
  92. whoosh_index(app, Topic)
  93. whoosh_index(app, Forum)
  94. whoosh_index(app, Category)
  95. whoosh_index(app, User)
  96. # Flask-Login
  97. login_manager.login_view = app.config["LOGIN_VIEW"]
  98. login_manager.refresh_view = app.config["REAUTH_VIEW"]
  99. login_manager.anonymous_user = Guest
  100. @login_manager.user_loader
  101. def load_user(id):
  102. """
  103. Loads the user. Required by the `login` extension
  104. """
  105. unread_count = db.session.query(db.func.count(PrivateMessage.id)).\
  106. filter(PrivateMessage.unread == True,
  107. PrivateMessage.user_id == id).subquery()
  108. u = db.session.query(User, unread_count).filter(User.id == id).first()
  109. if u:
  110. user, user.pm_unread = u
  111. return user
  112. else:
  113. return None
  114. login_manager.init_app(app)
  115. def configure_template_filters(app):
  116. """
  117. Configures the template filters
  118. """
  119. app.jinja_env.filters['markup'] = render_markup
  120. app.jinja_env.filters['format_date'] = format_date
  121. app.jinja_env.filters['time_since'] = time_since
  122. app.jinja_env.filters['is_online'] = is_online
  123. app.jinja_env.filters['crop_title'] = crop_title
  124. app.jinja_env.filters['forum_is_unread'] = forum_is_unread
  125. app.jinja_env.filters['topic_is_unread'] = topic_is_unread
  126. # Permission filters
  127. app.jinja_env.filters['edit_post'] = can_edit_post
  128. app.jinja_env.filters['delete_post'] = can_delete_post
  129. app.jinja_env.filters['delete_topic'] = can_delete_topic
  130. app.jinja_env.filters['move_topic'] = can_move_topic
  131. app.jinja_env.filters['lock_topic'] = can_lock_topic
  132. app.jinja_env.filters['post_reply'] = can_post_reply
  133. app.jinja_env.filters['post_topic'] = can_post_topic
  134. def configure_before_handlers(app):
  135. """
  136. Configures the before request handlers
  137. """
  138. @app.before_request
  139. def update_lastseen():
  140. """
  141. Updates `lastseen` before every reguest if the user is authenticated
  142. """
  143. if current_user.is_authenticated():
  144. current_user.lastseen = datetime.datetime.utcnow()
  145. db.session.add(current_user)
  146. db.session.commit()
  147. @app.before_request
  148. def get_user_permissions():
  149. current_user.permissions = current_user.get_permissions()
  150. if app.config["REDIS_ENABLED"]:
  151. @app.before_request
  152. def mark_current_user_online():
  153. if current_user.is_authenticated():
  154. mark_online(current_user.username)
  155. else:
  156. mark_online(request.remote_addr, guest=True)
  157. def configure_errorhandlers(app):
  158. """
  159. Configures the error handlers
  160. """
  161. @app.errorhandler(403)
  162. def forbidden_page(error):
  163. return render_template("errors/forbidden_page.html"), 403
  164. @app.errorhandler(404)
  165. def page_not_found(error):
  166. return render_template("errors/page_not_found.html"), 404
  167. @app.errorhandler(500)
  168. def server_error_page(error):
  169. return render_template("errors/server_error.html"), 500
  170. def configure_logging(app):
  171. """
  172. Configures logging.
  173. """
  174. logs_folder = os.path.join(app.root_path, os.pardir, "logs")
  175. from logging.handlers import SMTPHandler
  176. formatter = logging.Formatter(
  177. '%(asctime)s %(levelname)s: %(message)s '
  178. '[in %(pathname)s:%(lineno)d]')
  179. info_log = os.path.join(logs_folder, app.config['INFO_LOG'])
  180. info_file_handler = logging.handlers.RotatingFileHandler(
  181. info_log,
  182. maxBytes=100000,
  183. backupCount=10
  184. )
  185. info_file_handler.setLevel(logging.INFO)
  186. info_file_handler.setFormatter(formatter)
  187. app.logger.addHandler(info_file_handler)
  188. error_log = os.path.join(logs_folder, app.config['ERROR_LOG'])
  189. error_file_handler = logging.handlers.RotatingFileHandler(
  190. error_log,
  191. maxBytes=100000,
  192. backupCount=10
  193. )
  194. error_file_handler.setLevel(logging.ERROR)
  195. error_file_handler.setFormatter(formatter)
  196. app.logger.addHandler(error_file_handler)
  197. if app.config["SEND_LOGS"]:
  198. mail_handler = \
  199. SMTPHandler(app.config['MAIL_SERVER'],
  200. app.config['MAIL_DEFAULT_SENDER'],
  201. app.config['ADMINS'],
  202. 'application error, no admins specified',
  203. (
  204. app.config['MAIL_USERNAME'],
  205. app.config['MAIL_PASSWORD'],
  206. ))
  207. mail_handler.setLevel(logging.ERROR)
  208. mail_handler.setFormatter(formatter)
  209. app.logger.addHandler(mail_handler)