app.py 16 KB

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