pythonflaskflask-mail

Flask configuration handling from external file


I have set all configurations inside Configure class belonging to settings.py module

import os, secrets
basedir = os.path.abspath(os.path.dirname(__file__))

class Config():
    SECRET_KEY = secrets.token_hex(16)
    SQLALCHEMY_DATABASE_URI ='sqlite:///' + os.path.join(basedir, 'sqlitedb/data.sqlite')
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    MAIL_SERVER = 'smtp.gmail.com'
    MAIL_PORT = 587
    MAIL_USE_TLS = True
    ...........

Which is initialized by main app.py

from flask import Flask
from MyProject.extensions import db, mail, bootstrap, migrate
**from MyProject.settings import Config**
from werkzeug.security import generate_password_hash, check_password_hash


def create_app():
    app = Flask(__name__.split('.')[0])
    app.url_map.strict_slashes = False
    **app.config.from_object(Config)**
    register_extensions(app)
    register_blueprints(app)
    return app

My task is to handover the SECRET_KEY value as an argument to the function which is inside other (mail.py) module

from itsdangerous import URLSafeTimedSerializer
from Myproject.app import mail
from Myproject import app
def send_congrats_email(user):
    confirm_serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
    confirm_url = url_for(
        'confirm_email',
        token=confirm_serializer.dumps(user, salt='email-confirmation-salt'),
        _external=True)

    send_email('[Congrats] You are registered',
               sender= "NICOLAS",
               recipients=[user.email],
               html_body=render_template('users/email_confirmation.html',
                                         user=user))

Please, advice what is the right/proper way of doing this task?


Solution

  • Solution to such problem is the following:

    from flask import current_app
    

    and then modify:

    confirm_serializer = URLSafeTimedSerializer(app.config['SECRET_KEY'])
    

    to

    confirm_serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])