2018-01-16T20:22:10Z

The Flask Mega-Tutorial Part VII: Error Handling

This is the seventh installment of the Flask Mega-Tutorial series, in which I'm going to tell you how to do error handling in a Flask application.

For your reference, below is a list of the articles in this series.

In this chapter I'm taking a break from coding new features into my microblog application, and instead will discuss a few strategies to deal with bugs, which invariably make an appearance in every software project. To help illustrate this topic, I intentionally let a bug slip in the code that I've added in Chapter 6. Before you continue reading, see if you can find it!

The GitHub links for this chapter are: Browse, Zip, Diff.

Error Handling in Flask

What happens when an error occurs in a Flask application? The best way to find out is to experience it first hand. Go ahead and start the application, and make sure you have at least two users registered. Log in as one of the users, open the profile page and click the "Edit" link. In the profile editor, try to change the username to the username of another user that is already registered, and boom! This is going to bring a scary looking "Internal Server Error" page:

Internal Server Error

If you look in the terminal session where the application is running, you will see a stack trace of the error. Stack traces are extremely useful in debugging errors, because they show the sequence of calls in that stack, all the way to the line that produced the error:

(venv) $ flask run
 * Serving Flask app "microblog"
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[2021-06-14 22:40:02,027] ERROR in app: Exception on /edit_profile [POST]
Traceback (most recent call last):
  File "venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", in _execute_context
    context)
  File "venv/lib/python3.6/site-packages/sqlalchemy/engine/default.py", in do_execute
    cursor.execute(statement, parameters)
sqlite3.IntegrityError: UNIQUE constraint failed: user.username

The stack trace indicates what is the bug. The application allows a user to change the username, and does not validate that the new username chosen does not collide with another user already in the system. The error comes from SQLAlchemy, which tries to write the new username to the database, but the database rejects it because the username column is defined with unique=True.

It is important to note that the error page that is presented to the user does not provide much information about the error, and that is good. I definitely do not want users to learn that the crash was caused by a database error, or what database I'm using, or what are some of the table and field names in my database. All that information should be kept internal.

There are a few things that are far from ideal. I have an error page that is very ugly and does not match the application layout. I also have important application stack traces being dumped on a terminal that I need to constantly watch to make sure I don't miss any errors. And of course I have a bug to fix. I'm going to address all these issues, but first, let's talk about Flask's debug mode.

Debug Mode

The way you saw that errors are handled above is great for a system that is running on a production server. If there is an error, the user gets a vague error page (though I'm going to make this error page nicer), and the important details of the error are in the server process output or in a log file.

But when you are developing your application, you can enable debug mode, a mode in which Flask outputs a really nice debugger directly on your browser. To activate debug mode, stop the application, and then set the following environment variable:

(venv) $ export FLASK_ENV=development

If you are on Microsoft Windows, remember to use set instead of export.

After you set FLASK_ENV, restart the server. The output on your terminal is going to be slightly different than what you are used to see:

(venv) microblog2 $ flask run
 * Serving Flask app 'microblog.py' (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 118-204-854

Now make the application crash one more time to see the interactive debugger in your browser:

Flask Debugger

The debugger allows you expand each stack frame and see the corresponding source code. You can also open a Python prompt on any of the frames and execute any valid Python expressions, for example to check the values of variables.

It is extremely important that you never run a Flask application in debug mode on a production server. The debugger allows the user to remotely execute code in the server, so it can be an unexpected gift to a malicious user who wants to infiltrate your application or your server. As an additional security measure, the debugger running in the browser starts locked, and on first use will ask for a PIN number, which you can see in the output of the flask run command.

Since I am in the topic of debug mode, I should mention the second important feature that is enabled with debug mode, which is the reloader. This is a very useful development feature that automatically restarts the application when a source file is modified. If you run flask run while in debug mode, you can then work on your application and any time you save a file, the application will restart to pick up the new code.

Custom Error Pages

Flask provides a mechanism for an application to install its own error pages, so that your users don't have to see the plain and boring default ones. As an example, let's define custom error pages for the HTTP errors 404 and 500, the two most common ones. Defining pages for other errors works in the same way.

To declare a custom error handler, the @errorhandler decorator is used. I'm going to put my error handlers in a new app/errors.py module.

app/errors.py: Custom error handlers

from flask import render_template
from app import app, db

@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_error(error):
    db.session.rollback()
    return render_template('500.html'), 500

The error functions work very similarly to view functions. For these two errors, I'm returning the contents of their respective templates. Note that both functions return a second value after the template, which is the error code number. For all the view functions that I created so far, I did not need to add a second return value because the default of 200 (the status code for a successful response) is what I wanted. In this case these are error pages, so I want the status code of the response to reflect that.

The error handler for the 500 errors could be invoked after a database error, which was actually the case with the username duplicate above. To make sure any failed database sessions do not interfere with any database accesses triggered by the template, I issue a session rollback. This resets the session to a clean state.

Here is the template for the 404 error:

app/templates/404.html: Not found error template

{% extends "base.html" %}

{% block content %}
    <h1>File Not Found</h1>
    <p><a href="{{ url_for('index') }}">Back</a></p>
{% endblock %}

And here is the one for the 500 error:

app/templates/500.html: Internal server error template

{% extends "base.html" %}

{% block content %}
    <h1>An unexpected error has occurred</h1>
    <p>The administrator has been notified. Sorry for the inconvenience!</p>
    <p><a href="{{ url_for('index') }}">Back</a></p>
{% endblock %}

Both templates inherit from the base.html template, so that the error page has the same look and feel as the normal pages of the application.

To get these error handlers registered with Flask, I need to import the new app/errors.py module after the application instance is created:

app/__init__.py: Import error handlers

# ...

from app import routes, models, errors

If you set FLASK_ENV=production in your terminal session and then trigger the duplicate username bug one more time, you are going to see a slightly more friendly error page.

Custom 500 Error Page

Sending Errors by Email

The other problem with the default error handling provided by Flask is that there are no notifications, stack trace for errors are printed to the terminal, which means that the output of the server process needs to be monitored to discover errors. When you are running the application during development, this is perfectly fine, but once the application is deployed on a production server, nobody is going to be looking at the output, so a more robust solution needs to be put in place.

I think it is very important that I take a proactive approach regarding errors. If an error occurs on the production version of the application, I want to know right away. So my first solution is going to be to configure Flask to send me an email immediately after an error, with the stack trace of the error in the email body.

The first step is to add the email server details to the configuration file:

config.py: Email configuration

class Config(object):
    # ...
    MAIL_SERVER = os.environ.get('MAIL_SERVER')
    MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
    MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
    MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
    MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
    ADMINS = ['your-email@example.com']

The configuration variables for email include the server and port, a boolean flag to enable encrypted connections, and optional username and password. The five configuration variables are sourced from their environment variable counterparts. If the email server is not set in the environment, then I will use that as a sign that emailing errors needs to be disabled. The email server port can also be given in an environment variable, but if not set, the standard port 25 is used. Email server credentials are by default not used, but can be provided if needed. The ADMINS configuration variable is a list of the email addresses that will receive error reports, so your own email address should be in that list.

Flask uses Python's logging package to write its logs, and this package already has the ability to send logs by email. All I need to do to get emails sent out on errors is to add a SMTPHandler instance to the Flask logger object, which is app.logger:

app/__init__.py: Log errors by email

import logging
from logging.handlers import SMTPHandler

# ...

if not app.debug:
    if app.config['MAIL_SERVER']:
        auth = None
        if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
            auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
        secure = None
        if app.config['MAIL_USE_TLS']:
            secure = ()
        mail_handler = SMTPHandler(
            mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
            fromaddr='no-reply@' + app.config['MAIL_SERVER'],
            toaddrs=app.config['ADMINS'], subject='Microblog Failure',
            credentials=auth, secure=secure)
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)

As you can see, I'm only going to enable the email logger when the application is running without debug mode, which is indicated by app.debug being True, and also when the email server exists in the configuration.

Setting up the email logger is somewhat tedious due to having to handle optional security options that are present in many email servers. But in essence, the code above creates a SMTPHandler instance, sets its level so that it only reports errors and not warnings, informational or debugging messages, and finally attaches it to the app.logger object from Flask.

There are two approaches to test this feature. The easiest one is to use the SMTP debugging server from Python. This is a fake email server that accepts emails, but instead of sending them, it prints them to the console. To run this server, open a second terminal session and run the following command on it:

(venv) $ python -m smtpd -n -c DebuggingServer localhost:8025

Leave the debugging SMTP server running and go back to your first terminal and set export MAIL_SERVER=localhost and MAIL_PORT=8025 in the environment (use set instead of export if you are using Microsoft Windows). Make sure the FLASK_ENV variable is set to production or not set at all, since the application will not send emails in debug mode. Run the application and trigger the SQLAlchemy error one more time to see how the terminal session running the fake email server shows an email with the full stack trace of the error.

A second testing approach for this feature is to configure a real email server. Below is the configuration to use your Gmail account's email server:

export MAIL_SERVER=smtp.googlemail.com
export MAIL_PORT=587
export MAIL_USE_TLS=1
export MAIL_USERNAME=<your-gmail-username>
export MAIL_PASSWORD=<your-gmail-password>

If you are using Microsoft Windows, remember to use set instead of export in each of the statements above.

The security features in your Gmail account may prevent the application from sending emails through it unless you explicitly allow "less secure apps" access to your Gmail account. You can read about this here, and if you are concerned about the security of your account, you can create a secondary account that you configure just for testing emails, or you can enable less secure apps only temporarily to run this test and then revert back to the default.

Yet another alternative is to use a dedicated email service such as SendGrid, which allows you to send up to 100 emails per day on a free account. The SendGrid blog has a detailed tutorial on using the service in a Flask application.

Logging to a File

Receiving errors via email is nice, but sometimes this isn't enough. There are some failure conditions that do not end in a Python exception and are not a major problem, but they may still be interesting enough to save for debugging purposes. For this reason, I'm also going to maintain a log file for the application.

To enable a file based log another handler, this time of type RotatingFileHandler, needs to be attached to the application logger, in a similar way to the email handler.

app/__init__.py: Logging to a file

# ...
from logging.handlers import RotatingFileHandler
import os

# ...

if not app.debug:
    # ...

    if not os.path.exists('logs'):
        os.mkdir('logs')
    file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240,
                                       backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)

    app.logger.setLevel(logging.INFO)
    app.logger.info('Microblog startup')

I'm writing the log file with name microblog.log in a logs directory, which I create if it doesn't already exist.

The RotatingFileHandler class is nice because it rotates the logs, ensuring that the log files do not grow too large when the application runs for a long time. In this case I'm limiting the size of the log file to 10KB, and I'm keeping the last ten log files as backup.

The logging.Formatter class provides custom formatting for the log messages. Since these messages are going to a file, I want them to have as much information as possible. So I'm using a format that includes the timestamp, the logging level, the message and the source file and line number from where the log entry originated.

To make the logging more useful, I'm also lowering the logging level to the INFO category, both in the application logger and the file logger handler. In case you are not familiar with the logging categories, they are DEBUG, INFO, WARNING, ERROR and CRITICAL in increasing order of severity.

As a first interesting use of the log file, the server writes a line to the logs each time it starts. When this application runs on a production server, these log entries will tell you when the server was restarted.

Fixing the Duplicate Username Bug

I have exploited the username duplication bug for too long. Now that I have showed you how to prepare the application to handle this type of errors, I can go ahead and fix it.

If you recall, the RegistrationForm already implements validation for usernames, but the requirements of the edit form are slightly different. During registration, I need to make sure the username entered in the form does not exist in the database. On the edit profile form I have to do the same check, but with one exception. If the user leaves the original username untouched, then the validation should allow it, since that username is already assigned to that user. Below you can see how I implemented the username validation for this form:

app/forms.py: Validate username in edit profile form.

class EditProfileForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    about_me = TextAreaField('About me', validators=[Length(min=0, max=140)])
    submit = SubmitField('Submit')

    def __init__(self, original_username, *args, **kwargs):
        super(EditProfileForm, self).__init__(*args, **kwargs)
        self.original_username = original_username

    def validate_username(self, username):
        if username.data != self.original_username:
            user = User.query.filter_by(username=self.username.data).first()
            if user is not None:
                raise ValidationError('Please use a different username.')

The implementation is in a custom validation method, but there is an overloaded constructor that accepts the original username as an argument. This username is saved as an instance variable, and checked in the validate_username() method. If the username entered in the form is the same as the original username, then there is no reason to check the database for duplicates.

To use this new validation method, I need to add the original username argument in the view function, where the form object is created:

app/routes.py: Validate username in edit profile form.

@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm(current_user.username)
    # ...

Now the bug is fixed and duplicates in the edit profile form will be prevented in most cases. This is not a perfect solution, because it may not work when two or more processes are accessing the database at the same time. In that situation, a race condition could cause the validation to pass, but a moment later when the rename is attempted the database was already changed by another process and cannot rename the user. This is somewhat unlikely except for very busy applications that have a lot of server processes, so I'm not going to worry about it for now.

At this point you can try to reproduce the error one more time to see how the new form validation method prevents it.

275 comments

  • #126 Miguel Grinberg said 2019-07-23T07:15:32Z

    @sunny: something in your virtual environment isn't right. Trash the environment, make a new one, install all the dependencies from scratch.

  • #127 Nicholas said 2019-07-25T15:23:51Z

    @miguel

    I ran into the same problem as Sunny, just trashed and reinstalled all of the dependencies and it's giving me the same error.

    "No module named C:\Users\shado\python-scripts\microblog\venv\Scripts\flask"

    I am using Powershell so I used $env:FLASK_ENV="development" to turn on debugging

  • #128 Miguel Grinberg said 2019-07-25T15:59:57Z

    @Nicholas: unfortunately I do not have a Windows machine at hand right now to test this. Can I ask you to run two tests for me? First test, downgrade Flask to version 1.0.2 (I assume you are on the new 1.1.0 or 1.1.1?). I'd like to know if the problem exists on the older Flask release.

    If the 1.0.2 release also does it, then can I ask you to do this on the command prompt window? It's a long shot, but I have also used the command prompt and never saw this issue.

  • #129 Nicholas said 2019-07-25T16:54:33Z

    I was running 1.1.1 and downgraded to 1.0.2 like you asked and it did the same thing in command prompt and also Git Bash.

  • #130 Nicholas said 2019-07-25T18:12:09Z

    @miguel

    I found a fix. I don't know what the problem is but if you use "python -m flask run" it will bypass the issue. The person who showed me this fix explained that it is something to do with the newest version of Werkzeug. I just downgraded from 0.15.5 to 0.15.4 and was able to run flask normally with "flask run".

  • #131 Miguel Grinberg said 2019-07-25T18:58:54Z

    @Nicholas: Ah, okay, I was close, I thought it could be a Flask update, but was Werkzeug. It appears the ".exe" suffix for flask is missing on this latest release of Werkzeug. There is an open issue for it: https://github.com/pallets/werkzeug/issues/1614.

  • #132 Nicholas said 2019-07-25T20:05:16Z

    @Miguel Thank you for the help Miguel and this tutorial as well.

    I'm running into another issue with the debugging server, the emails aren't printing out in Powershell. I noticed others in the comments were having a similar issue but didn't see any fixes.

  • #133 Miguel Grinberg said 2019-07-25T22:34:20Z

    @Nicholas: is this specific to PowerShell? Do you see the emails when you run the debugging SMTP server from a command prompt window?

  • #134 Nicholas said 2019-07-25T23:09:40Z

    It is not specific to Powershell as I tried it in Git Bash as well and it did not work, but it did work in command prompt.

  • #135 Sanya said 2019-07-28T10:48:27Z

    @Miguel Instead of using an overloaded constructor, I just made some tweaks to the custom validation method. It seems too simple to be correct so I was wondering if there are any corner cases I may have missed.

    def validate_username(self, username): user = User.query.filter_by(username=username.data).first() if username.data != current_user.username and user is not None: raise ValidationError('Please use a different username.')

  • #136 Miguel Grinberg said 2019-07-28T11:00:15Z

    @Sanya: this has been suggested before. It's fine, but what I don't like about this solution is that creates a dependency between Flask-WTF and Flask-Login. In general I favor decoupled designs, my solution helps keep these two extensions independent of each other.

  • #137 Sanya said 2019-07-29T22:33:42Z

    @Miguel That makes sense! Thanks for clearing that up.

    I was having some trouble understanding what you're doing in the overloaded constructor since I'm not familiar with using args and *kwargs but a quick Google Search explained that. What I don't get is why you're using them here.

  • #138 Miguel Grinberg said 2019-07-29T22:50:05Z

    @Sanya: you use args and kwargs when you want to capture all arguments sent into the function, regardless of how many there are. This is a standard pattern when you create a function that acts as a wrapper for another. It allows you to create the wrapper without having to know what are the arguments of the wrapped function, you can just get all arguments and pass them on without knowing what they are.

  • #139 Lincoln said 2019-08-09T10:54:35Z

    This is Just to help anyone else that follows this tutorial after me I guess.

    This is the problem I encountered. -FLASK_DEBUG=1 and executing $ flask run

    this produced this error: No module named C:\Users\slickLink\microblog\venv\Scripts\flask

    virtual environment was active, and I've been following the tutorial just fine up until now. checked if flask was installed on the my venv (Windows 10 btw) I tried everything

    THE PROBLEM( I think, i'm still learning ) - python can't find flask even though it's installed and I even manually located it :( - The key thing is i'm using a windows machine, and python is looking for a file named flask in this ( C:\Users\slickLink\microblog\venv\Scripts\ ) directory. But windows uses .exe files, so python is looking for flask and only flask.exe exists.

    SOLUTION( for now I think lol ) - create a file windows batch file name 'flask' with no extension ( dont put .bat, it wont work) in the venv\Scripts directory. - and since the file i want to run is in the same directory, your newly created file should only have "flask.exe" as it's content (excluding the quotations) - and then $ flask run

    Just thought it might help.

  • #140 Cesar Amaral said 2019-08-21T22:26:39Z

    Hello, Miguel!

    Congratulations for the excellent work in this tutorial!

    I followd until part 7 without problem. However, I'm not being able to activate the debug mode. I'm using Windows 10. I exported the variable FLASK_DEBUG=1, but when I run "flask run" I'm receiving the following return:

    $ flask run * Serving Flask app "microblog.py" (lazy loading) * Environment: development * Debug mode: on * Restarting with stat d:...\microblog\venv\scripts\python.exe: No module named D:...\microblog\venv\Scripts\flask (venv)

    However, the file 'flask' is in the folder 'Scripts'. Also, when the debug is off, this problem does not happen. I tried some possible solutions I found in Stack Overflow, exporting other variables like FLASK_ENV, FLASK_APP but the error remains the same. I exported the variables using set in Windows CMD and also using $env in Windows Power Shell, but again, nothing different.

    Can you help me?

  • #141 Miguel Grinberg said 2019-08-21T22:33:39Z

    @Cesar: This is a bug in Werkzeug, a dependency of Flask. See https://stackoverflow.com/questions/57114348/flask-reloader-crashes-with-no-module-named-scripts-flask-on-windows for a workaround until this bug is fixed.

  • #142 David Tahvildaran said 2019-09-01T17:29:29Z

    Hi,

    In case anyone is having/has had the issue I just resolved -- remember to update your ADMINS list in config.py if you are changing/adding an email account to send error logs.

    I originally had my personal email at first but decided to make a 'tech-admin-support' email but forgot to add it to the ADMINS list and was really confused for a bit why I wasn't seeing any emails in the inbox of that new gmail account I had made. All is working now.

    Thanks Miguel for this wonderful in-depth tutorial! David

  • #143 chefe said 2019-09-08T16:39:16Z

    Hello Miguel,

    At forms.py you forgot to import ValidationError from wtforms.validators and this generates an error stating the object as not defined

  • #144 Miguel Grinberg said 2019-09-09T10:15:03Z

    @chefe: the snippets only show changes you need to make to each file. The ValidationError import was made in a previous chapter, so it should have been already included.

  • #145 XIAOQI YAN said 2019-09-25T07:44:20Z

    Hi Miguel, nice tutorial. I have a question about the class attribute and instance attribute here. Why you make username about_me...etc as user class attribute. But use original_username as instance attribute?

  • #146 Miguel Grinberg said 2019-09-25T17:57:24Z

    @XIAOQI: that is a common pattern used by several Python libraries, for example SQLAlchemy and WTForms. I agree that it may seem that something is wrong there, but that's how these work, the class variables define the schema of the table or form, but once an object is instantiated they have to be used as instance variables.

  • #147 Keith Edmunds said 2019-09-25T18:09:20Z

    I couldn't get mail to send from the error handler. Stack trace in shell session and on web page, but no mail. Eventually found https://www.reddit.com/r/learnpython/comments/3ivwx3/unable_to_send_logging_email_via_flask_and/, and as a result I replaced the last line with:

    logging.getLogger('werkzeug').addHandler(mail_handler)

    That now sends mail, although I get multiple mails with one line per mail (and no stack trace). Six separate mails for the "change profile name" error with the contents being:

    127.0.0.1 - - [25/Sep/2019 18:49:42] "POST /edit_profile HTTP/1.1" 500

    127.0.0.1 - - [25/Sep/2019 18:49:42] "GET /edit_profile?debugger=yes&cmd=resource&f=style.css HTTP/1.1" 200 -

    127.0.0.1 - - [25/Sep/2019 18:49:42] "GET /edit_profile?debugger=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -

    127.0.0.1 - - [25/Sep/2019 18:49:42] "GET /edit_profile?debugger=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -

    127.0.0.1 - - [25/Sep/2019 18:49:43] "GET /edit_profile?debugger=yes&cmd=resource&f=console.png HTTP/1.1" 200 -

    127.0.0.1 - - [25/Sep/2019 18:49:43] "GET /edit_profile?debugger=yes&cmd=resource&f=console.png HTTP/1.1" 200 -

    I will try to investigate more, but any pointers gratefully received.

  • #148 Miguel Grinberg said 2019-09-26T12:37:13Z

    @Keith: the mail handler should already be added to the app logger, so it should not need to be added again as you did. You should have a line that reads:

    app.logger.addHandler(mail_handler)

    This should be sufficient to get the errors sent by email, and with this one the whole stack trace should be sent in a single email.

  • #149 Zuzanna said 2019-09-30T13:44:34Z

    Wonderful tutorial. So far everything you showed worked when I did it on my own apart from this lesson. I am getting following error. I was trying to search on-line for how other people dealt with this error, but I couldnt find anything related enough to my issue.

    Traceback (most recent call last): File "c:\users\zuzan\microblog\venv\lib\site-packages\flask\app.py", line 2446, in wsgi_app response = self.full_dispatch_request() File "c:\users\zuzan\microblog\venv\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\zuzan\microblog\venv\lib\site-packages\flask\app.py", line 1820, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\zuzan\microblog\venv\lib\site-packages\flask_compat.py", line 39, in reraise raise value File "c:\users\zuzan\microblog\venv\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request rv = self.dispatch_request() File "c:\users\zuzan\microblog\venv\lib\site-packages\flask\app.py", line 1935, in dispatch_request return self.view_functionsrule.endpoint File "C:\Users\zuzan\microblog\venv\app\routes.py", line 162, in reset_password_request send_password_reset_email(user) File "C:\Users\zuzan\microblog\venv\app\email.py", line 20, in send_password_reset_email user=user, token=token)) File "C:\Users\zuzan\microblog\venv\app\email.py", line 10, in send_email mail.send(msg) File "c:\users\zuzan\microblog\venv\lib\site-packages\flask_mail.py", line 491, in send with self.connect() as connection: File "c:\users\zuzan\microblog\venv\lib\site-packages\flask_mail.py", line 144, in enter self.host = self.configure_host() File "c:\users\zuzan\microblog\venv\lib\site-packages\flask_mail.py", line 158, in configure_host host = smtplib.SMTP(self.mail.server, self.mail.port) File "C:\Users\zuzan\Anaconda3\lib\smtplib.py", line 251, in init (code, msg) = self.connect(host, port) File "C:\Users\zuzan\Anaconda3\lib\smtplib.py", line 335, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Users\zuzan\Anaconda3\lib\smtplib.py", line 306, in _get_socket self.source_address) File "C:\Users\zuzan\Anaconda3\lib\socket.py", line 712, in create_connection raise err File "C:\Users\zuzan\Anaconda3\lib\socket.py", line 703, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it 127.0.0.1 - - [30/Sep/2019 14:34:53] "POST /reset_password_request HTTP/1.1" 500

    Thanks, for looking at it :)

  • #150 Miguel Grinberg said 2019-10-02T10:36:05Z

    @Zuzanna: the application is trying to send an email, but the email configuration that you have is likely wrong.

Leave a Comment