-1

This is my structure. I have problem about implementing flask large application.

├─flasky
│  ├─app/
│  │  ├─templates/
│  │  ├─static/
│  │  ├─main/
│  │  │  ├─__init__.py
│  │  │  ├─errors.py
│  │  │  ├─forms.py
│  │  │  └─views.py
│  │  ├─__init__.py
│  │  ├─email.py
│  │  └─models.py
│  ├─migrations/
│  ├─tests/
│  │  ├─__init__.py
│  │  └─test*.py
│  ├─venv/
│  ├─requirements.txt
│  ├─config.py
│  └─manage.py
...

I encountered some problem When I was coding in email.py.

def send_email(to, subject, template, **kwargs):
    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
                  sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
    with the_app.app_context():
        msg.body = render_template(template + '.txt', **kwargs)
        msg.html = render_template(template + '.html', **kwargs)
        thr = Thread(target=send_async_email, args=[app, msg])
        thr.start()
        return thr

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

I don't know how to call modules to implement the_app.app_context(). I hope that it can direct send_email function to get app/templates of location to be successful.

Burger King
  • 2,945
  • 3
  • 20
  • 45

1 Answers1

0

I found what the problem was. I needed to define a flask app in email.py:

import os
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
the_app = Flask(__name__, template_folder=tmpl_dir)

I encountered a new problem with werkzeug.routing.BuildError, and I am searching for a solution. I found "Flask error: werkzeug.routing.BuildError" mentioned my problem.

werkzeug.routing.BuildError
BuildError: ('index', {}, None) 

Because views.py had a typo arg of url_for(), I should type 'main.index'. It's right.

@main.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        ...
        return redirect(url_for('main.index'))
    return render_template('index.html',
                           form=form, name=session.get('name'),
                           known=session.get('known', False),
                           current_time=datetime.utcnow())

But it can't enable the feature of sending email. I found "Python Flask Email KeyError KeyError: 'mail'" mentioned my problem. I needed to downgrade to flask_mail==0.9.0, which solved the problems.

Community
  • 1
  • 1
Burger King
  • 2,945
  • 3
  • 20
  • 45