Flask sends email slowly (even asynchronously)

Flask sends QQ email too slowly (even asynchronously). The original 150ms response page has been changed to 5s by adding email. Do you have a solution that is relatively simple ?

now I am very confused that since I have opened a new thread to send email, the view business will not wait for him to send the email but will continue to respond directly, but the actual situation is that the view business is blocked for 5s

.

part of the code (written by dogs):

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


def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(app.config["FLASKY_MAIL_SUBJECT_PREFIX"] + subject,
               sender=app.config["FLASKY_MAIL_SENDER"], recipients=[to])
    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
Jun.09,2022

I don't know much about flask , and I don't quite understand what you're writing, but for one thing, do you change from 150ms to 5s asynchronously? There's a big problem here. There should be only three possibilities.

  1. the part of waiting for the network iMab O is not in the asynchronous task at all (you may have put the unimportant part in the asynchronous task as the time-consuming part)
  2. the variables used by the new thread are locked and are not released until the mail has been sent, while the thread processing the request has been waiting for the sending thread to release the lock before finishing processing the request (or the mechanism of the thread handling the request causes blocking, or you actively call .join before the request processing ends)
  3. in your scenario, sending email is a CPU-intensive task, and the extra 4 seconds is spent on CPU desperately figuring out how to send email

the third is unlikely. Add a few more lines of output and check the first two possibilities


has solved the problem. The slow speed is due to Message initialization. Just put Message initialization into async.
Optimization Code:

  see my blog  

for more details.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e873f2-46c22.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e873f2-46c22.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?