app.py 15 KB

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