app.py 16 KB

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