app.py 7.3 KB

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