Просмотр исходного кода

Configure flaskbb from environment variables

Peter Justin 8 лет назад
Родитель
Сommit
31d421b569
2 измененных файлов с 31 добавлено и 2 удалено
  1. 6 1
      flaskbb/app.py
  2. 25 1
      flaskbb/utils/helpers.py

+ 6 - 1
flaskbb/app.py

@@ -35,7 +35,8 @@ from flaskbb.extensions import (db, login_manager, mail, cache, redis_store,
 from flaskbb.utils.helpers import (time_utcnow, format_date, time_since,
                                    crop_title, is_online, mark_online,
                                    forum_is_unread, topic_is_unread,
-                                   render_template, render_markup)
+                                   render_template, render_markup,
+                                   app_config_from_env)
 from flaskbb.utils.translations import FlaskBBDomain
 # permission checks (here they are used for the jinja filters)
 from flaskbb.utils.requirements import (IsAdmin, IsAtleastModerator,
@@ -92,6 +93,10 @@ def configure_app(app, config):
     # try to update the config via the environment variable
     app.config.from_envvar("FLASKBB_SETTINGS", silent=True)
 
+    # Parse the env for FLASKBB_ prefixed env variables and set
+    # them on the config object
+    app_config_from_env(app, prefix="FLASKBB_")
+
 
 def configure_celery_app(app, celery):
     """Configures the celery app."""

+ 25 - 1
flaskbb/utils/helpers.py

@@ -8,6 +8,7 @@
     :copyright: (c) 2014 by the FlaskBB Team.
     :license: BSD, see LICENSE for more details.
 """
+import ast
 import re
 import time
 import itertools
@@ -27,7 +28,7 @@ from flask_babelplus import lazy_gettext as _
 from flask_themes2 import render_theme_template
 from flask_login import current_user
 
-from flaskbb._compat import range_method, text_type
+from flaskbb._compat import range_method, text_type, iteritems
 from flaskbb.extensions import redis_store
 from flaskbb.utils.settings import flaskbb_config
 from flaskbb.utils.markup import markdown
@@ -510,3 +511,26 @@ def get_alembic_branches():
     ]
 
     return branches_dirs
+
+
+def app_config_from_env(app, prefix="FLASKBB_"):
+    """Retrieves the configuration variables from the environment.
+    Set your environment variables like this::
+
+        export FLASKBB_SECRET_KEY="your-secret-key"
+
+    and based on the prefix, it will set the actual config variable
+    on the ``app.config`` object.
+
+    :param app: The application object.
+    :param prefix: The prefix of the environment variables.
+    """
+    for key, value in iteritems(os.environ):
+        if key.startswith(prefix):
+            key = key[len(prefix):]
+            try:
+                value = ast.literal_eval(value)
+            except (ValueError, SyntaxError):
+                pass
+            app.config[key] = value
+    return app