app.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 logging
  10. import logging.config
  11. import os
  12. import sys
  13. import time
  14. from functools import partial
  15. from flask import Flask, request
  16. from flask_login import current_user
  17. from sqlalchemy import event
  18. from sqlalchemy.engine import Engine
  19. from sqlalchemy.exc import OperationalError, ProgrammingError
  20. from flaskbb._compat import iteritems, string_types
  21. from flaskbb.auth.views import auth
  22. # extensions
  23. from flaskbb.extensions import (alembic, allows, babel, cache, celery, csrf,
  24. db, debugtoolbar, limiter, login_manager, mail,
  25. redis_store, themes, whooshee)
  26. from flaskbb.forum.views import forum
  27. from flaskbb.management.views import management
  28. from flaskbb.message.views import message
  29. from flaskbb.plugins import spec
  30. from flaskbb.plugins.manager import FlaskBBPluginManager
  31. from flaskbb.plugins.models import PluginRegistry
  32. from flaskbb.plugins.utils import remove_zombie_plugins_from_db, template_hook
  33. # models
  34. from flaskbb.user.models import Guest, User
  35. # views
  36. from flaskbb.user.views import user
  37. # various helpers
  38. from flaskbb.utils.helpers import (app_config_from_env, crop_title,
  39. format_date, forum_is_unread,
  40. get_alembic_locations, get_flaskbb_config,
  41. is_online, mark_online, render_markup,
  42. render_template, time_since, time_utcnow,
  43. topic_is_unread)
  44. # permission checks (here they are used for the jinja filters)
  45. from flaskbb.utils.requirements import (CanBanUser, CanEditUser, IsAdmin,
  46. IsAtleastModerator, TplCanDeletePost,
  47. TplCanDeleteTopic, TplCanEditPost,
  48. TplCanModerate, TplCanPostReply,
  49. TplCanPostTopic)
  50. # whooshees
  51. from flaskbb.utils.search import (ForumWhoosheer, PostWhoosheer,
  52. TopicWhoosheer, UserWhoosheer)
  53. # app specific configurations
  54. from flaskbb.utils.settings import flaskbb_config
  55. from flaskbb.utils.translations import FlaskBBDomain
  56. logger = logging.getLogger(__name__)
  57. def create_app(config=None, instance_path=None):
  58. """Creates the app.
  59. :param instance_path: An alternative instance path for the application.
  60. By default the folder ``'instance'`` next to the
  61. package or module is assumed to be the instance
  62. path.
  63. See :ref:`Instance Folders <flask:instance-folders>`.
  64. :param config: The configuration file or object.
  65. The environment variable is weightet as the heaviest.
  66. For example, if the config is specified via an file
  67. and a ENVVAR, it will load the config via the file and
  68. later overwrite it from the ENVVAR.
  69. """
  70. app = Flask(
  71. "flaskbb",
  72. instance_path=instance_path,
  73. instance_relative_config=True
  74. )
  75. # instance folders are not automatically created by flask
  76. if not os.path.exists(app.instance_path):
  77. os.makedirs(app.instance_path)
  78. configure_app(app, config)
  79. configure_celery_app(app, celery)
  80. configure_extensions(app)
  81. load_plugins(app)
  82. configure_blueprints(app)
  83. configure_template_filters(app)
  84. configure_context_processors(app)
  85. configure_before_handlers(app)
  86. configure_errorhandlers(app)
  87. configure_migrations(app)
  88. configure_translations(app)
  89. app.pluggy.hook.flaskbb_additional_setup(app=app, pluggy=app.pluggy)
  90. return app
  91. def configure_app(app, config):
  92. """Configures FlaskBB."""
  93. # Use the default config and override it afterwards
  94. app.config.from_object('flaskbb.configs.default.DefaultConfig')
  95. config = get_flaskbb_config(app, config)
  96. # Path
  97. if isinstance(config, string_types):
  98. app.config.from_pyfile(config)
  99. # Module
  100. else:
  101. # try to update the config from the object
  102. app.config.from_object(config)
  103. # Add the location of the config to the config
  104. app.config["CONFIG_PATH"] = config
  105. # Environment
  106. # Get config file from envvar
  107. app.config.from_envvar("FLASKBB_SETTINGS", silent=True)
  108. # Parse the env for FLASKBB_ prefixed env variables and set
  109. # them on the config object
  110. app_config_from_env(app, prefix="FLASKBB_")
  111. # Setting up logging as early as possible
  112. configure_logging(app)
  113. if not isinstance(config, string_types) and config is not None:
  114. config_name = "{}.{}".format(config.__module__, config.__name__)
  115. else:
  116. config_name = config
  117. logger.info("Using config from: {}".format(config_name))
  118. app.pluggy = FlaskBBPluginManager('flaskbb', implprefix='flaskbb_')
  119. def configure_celery_app(app, celery):
  120. """Configures the celery app."""
  121. app.config.update({'BROKER_URL': app.config["CELERY_BROKER_URL"]})
  122. celery.conf.update(app.config)
  123. TaskBase = celery.Task
  124. class ContextTask(TaskBase):
  125. def __call__(self, *args, **kwargs):
  126. with app.app_context():
  127. return TaskBase.__call__(self, *args, **kwargs)
  128. celery.Task = ContextTask
  129. def configure_blueprints(app):
  130. app.register_blueprint(forum, url_prefix=app.config["FORUM_URL_PREFIX"])
  131. app.register_blueprint(user, url_prefix=app.config["USER_URL_PREFIX"])
  132. app.register_blueprint(auth, url_prefix=app.config["AUTH_URL_PREFIX"])
  133. app.register_blueprint(
  134. management, url_prefix=app.config["ADMIN_URL_PREFIX"]
  135. )
  136. app.register_blueprint(
  137. message, url_prefix=app.config["MESSAGE_URL_PREFIX"]
  138. )
  139. app.pluggy.hook.flaskbb_load_blueprints(app=app)
  140. def configure_extensions(app):
  141. """Configures the extensions."""
  142. # Flask-WTF CSRF
  143. csrf.init_app(app)
  144. # Flask-SQLAlchemy
  145. db.init_app(app)
  146. # Flask-Alembic
  147. alembic.init_app(app, command_name="db")
  148. # Flask-Mail
  149. mail.init_app(app)
  150. # Flask-Cache
  151. cache.init_app(app)
  152. # Flask-Debugtoolbar
  153. debugtoolbar.init_app(app)
  154. # Flask-Themes
  155. themes.init_themes(app, app_identifier="flaskbb")
  156. # Flask-And-Redis
  157. redis_store.init_app(app)
  158. # Flask-Limiter
  159. limiter.init_app(app)
  160. # Flask-Whooshee
  161. whooshee.init_app(app)
  162. # not needed for unittests - and it will speed up testing A LOT
  163. if not app.testing:
  164. whooshee.register_whoosheer(PostWhoosheer)
  165. whooshee.register_whoosheer(TopicWhoosheer)
  166. whooshee.register_whoosheer(ForumWhoosheer)
  167. whooshee.register_whoosheer(UserWhoosheer)
  168. # Flask-Login
  169. login_manager.login_view = app.config["LOGIN_VIEW"]
  170. login_manager.refresh_view = app.config["REAUTH_VIEW"]
  171. login_manager.login_message_category = app.config["LOGIN_MESSAGE_CATEGORY"]
  172. login_manager.needs_refresh_message_category = \
  173. app.config["REFRESH_MESSAGE_CATEGORY"]
  174. login_manager.anonymous_user = Guest
  175. @login_manager.user_loader
  176. def load_user(user_id):
  177. """Loads the user. Required by the `login` extension."""
  178. user_instance = User.query.filter_by(id=user_id).first()
  179. if user_instance:
  180. return user_instance
  181. else:
  182. return None
  183. login_manager.init_app(app)
  184. # Flask-Allows
  185. allows.init_app(app)
  186. allows.identity_loader(lambda: current_user)
  187. def configure_template_filters(app):
  188. """Configures the template filters."""
  189. filters = {}
  190. filters['markup'] = render_markup
  191. filters['format_date'] = format_date
  192. filters['time_since'] = time_since
  193. filters['is_online'] = is_online
  194. filters['crop_title'] = crop_title
  195. filters['forum_is_unread'] = forum_is_unread
  196. filters['topic_is_unread'] = topic_is_unread
  197. permissions = [
  198. ('is_admin', IsAdmin),
  199. ('is_moderator', IsAtleastModerator),
  200. ('is_admin_or_moderator', IsAtleastModerator),
  201. ('can_edit_user', CanEditUser),
  202. ('can_ban_user', CanBanUser),
  203. ]
  204. filters.update([
  205. (name, partial(perm, request=request)) for name, perm in permissions
  206. ])
  207. # these create closures
  208. filters['can_moderate'] = TplCanModerate(request)
  209. filters['post_reply'] = TplCanPostReply(request)
  210. filters['edit_post'] = TplCanEditPost(request)
  211. filters['delete_post'] = TplCanDeletePost(request)
  212. filters['post_topic'] = TplCanPostTopic(request)
  213. filters['delete_topic'] = TplCanDeleteTopic(request)
  214. app.jinja_env.filters.update(filters)
  215. app.jinja_env.globals["run_hook"] = template_hook
  216. app.pluggy.hook.flaskbb_jinja_directives(app=app)
  217. def configure_context_processors(app):
  218. """Configures the context processors."""
  219. @app.context_processor
  220. def inject_flaskbb_config():
  221. """Injects the ``flaskbb_config`` config variable into the
  222. templates.
  223. """
  224. return dict(flaskbb_config=flaskbb_config, format_date=format_date)
  225. def configure_before_handlers(app):
  226. """Configures the before request handlers."""
  227. @app.before_request
  228. def update_lastseen():
  229. """Updates `lastseen` before every reguest if the user is
  230. authenticated."""
  231. if current_user.is_authenticated:
  232. current_user.lastseen = time_utcnow()
  233. db.session.add(current_user)
  234. db.session.commit()
  235. if app.config["REDIS_ENABLED"]:
  236. @app.before_request
  237. def mark_current_user_online():
  238. if current_user.is_authenticated:
  239. mark_online(current_user.username)
  240. else:
  241. mark_online(request.remote_addr, guest=True)
  242. app.pluggy.hook.flaskbb_request_processors(app=app)
  243. def configure_errorhandlers(app):
  244. """Configures the error handlers."""
  245. @app.errorhandler(403)
  246. def forbidden_page(error):
  247. return render_template("errors/forbidden_page.html"), 403
  248. @app.errorhandler(404)
  249. def page_not_found(error):
  250. return render_template("errors/page_not_found.html"), 404
  251. @app.errorhandler(500)
  252. def server_error_page(error):
  253. return render_template("errors/server_error.html"), 500
  254. app.pluggy.hook.flaskbb_errorhandlers(app=app)
  255. def configure_migrations(app):
  256. """Configure migrations."""
  257. plugin_dirs = app.pluggy.hook.flaskbb_load_migrations()
  258. version_locations = get_alembic_locations(plugin_dirs)
  259. app.config['ALEMBIC']['version_locations'] = version_locations
  260. def configure_translations(app):
  261. """Configure translations."""
  262. # we have to initialize the extension after we have loaded the plugins
  263. # because we of the 'flaskbb_load_translations' hook
  264. babel.init_app(app=app, default_domain=FlaskBBDomain(app))
  265. @babel.localeselector
  266. def get_locale():
  267. # if a user is logged in, use the locale from the user settings
  268. if current_user and \
  269. current_user.is_authenticated and current_user.language:
  270. return current_user.language
  271. # otherwise we will just fallback to the default language
  272. return flaskbb_config["DEFAULT_LANGUAGE"]
  273. def configure_logging(app):
  274. """Configures logging."""
  275. if app.config.get('USE_DEFAULT_LOGGING'):
  276. configure_default_logging(app)
  277. if app.config.get('LOG_CONF_FILE'):
  278. logging.config.fileConfig(
  279. app.config['LOG_CONF_FILE'], disable_existing_loggers=False
  280. )
  281. if app.config["SQLALCHEMY_ECHO"]:
  282. # Ref: http://stackoverflow.com/a/8428546
  283. @event.listens_for(Engine, "before_cursor_execute")
  284. def before_cursor_execute(
  285. conn, cursor, statement, parameters, context, executemany
  286. ):
  287. conn.info.setdefault('query_start_time', []).append(time.time())
  288. @event.listens_for(Engine, "after_cursor_execute")
  289. def after_cursor_execute(
  290. conn, cursor, statement, parameters, context, executemany
  291. ):
  292. total = time.time() - conn.info['query_start_time'].pop(-1)
  293. app.logger.debug("Total Time: %f", total)
  294. def configure_default_logging(app):
  295. # TODO: Remove this once Flask 0.13 is released
  296. app.config["LOGGER_NAME"] = "flask.app"
  297. # Load default logging config
  298. logging.config.dictConfig(app.config["LOG_DEFAULT_CONF"])
  299. if app.config["SEND_LOGS"]:
  300. configure_mail_logs(app)
  301. def configure_mail_logs(app, formatter):
  302. from logging.handlers import SMTPHandler
  303. formatter = logging.Formatter(
  304. "%(asctime)s %(levelname)-7s %(name)-25s %(message)s"
  305. )
  306. mail_handler = SMTPHandler(
  307. app.config['MAIL_SERVER'], app.config['MAIL_DEFAULT_SENDER'],
  308. app.config['ADMINS'], 'application error, no admins specified',
  309. (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
  310. )
  311. mail_handler.setLevel(logging.ERROR)
  312. mail_handler.setFormatter(formatter)
  313. app.logger.addHandler(mail_handler)
  314. def load_plugins(app):
  315. app.pluggy.add_hookspecs(spec)
  316. # have to find all the flaskbb modules that are loaded this way
  317. # otherwise sys.modules might change while we're iterating it
  318. # because of imports and that makes Python very unhappy
  319. # we are not interested in duplicated plugins or invalid ones
  320. # ('None' - appears on py2) and thus using a set
  321. flaskbb_modules = set(
  322. module for name, module in iteritems(sys.modules)
  323. if name.startswith('flaskbb')
  324. )
  325. for module in flaskbb_modules:
  326. app.pluggy.register(module, internal=True)
  327. try:
  328. with app.app_context():
  329. plugins = PluginRegistry.query.all()
  330. except (OperationalError, ProgrammingError) as exc:
  331. logger.debug("Database is not setup correctly or has not been "
  332. "setup yet.", exc_info=exc)
  333. return
  334. for plugin in plugins:
  335. if not plugin.enabled:
  336. app.pluggy.set_blocked(plugin.name)
  337. app.pluggy.load_setuptools_entrypoints('flaskbb_plugins')
  338. app.pluggy.hook.flaskbb_extensions(app=app)
  339. loaded_names = set([p[0] for p in app.pluggy.list_name_plugin()])
  340. registered_names = set([p.name for p in plugins])
  341. unregistered = [
  342. PluginRegistry(name=name) for name in loaded_names - registered_names
  343. # ignore internal FlaskBB modules
  344. if not name.startswith('flaskbb.') and name != 'flaskbb'
  345. ]
  346. with app.app_context():
  347. db.session.add_all(unregistered)
  348. db.session.commit()
  349. removed = 0
  350. if app.config["REMOVE_DEAD_PLUGINS"]:
  351. removed = remove_zombie_plugins_from_db()
  352. logger.info("Removed Plugins: {}".format(removed))
  353. # we need a copy of it because of
  354. # RuntimeError: dictionary changed size during iteration
  355. tasks = celery.tasks.copy()
  356. disabled_plugins = [
  357. p.__package__ for p in app.pluggy.get_disabled_plugins()
  358. ]
  359. for task_name, task in iteritems(tasks):
  360. if task.__module__.split(".")[0] in disabled_plugins:
  361. logger.debug("Unregistering task: '{}'".format(task))
  362. celery.tasks.unregister(task_name)