app.py 15 KB

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