2

Recently I've been practicing to build a website with flask. Now i encounter a problem.
There is a function which to achieve registration. The code like this:

    def register():
        ...
        some judgment
        ...
        if true:
        sendmail()
        return redirect(url_for('onepage'))

My question is :
When preforming sendmail(), it needs much time. So the users have to wait for a moment to get "onepage", about 4-5s. This will bring a bad experience. I know that using threading can let these two functions independently of each other, but I have learnt programming for a very short time so I have no experience in threading programming, Could anybody provide some ideas or code examples for me at this problem?

0

3 Answers 3

5

What you want is threading rather than the low-level thread (which has been renamed to _thread in Python 3). For a case this simple, there will be no need of subclassing threading.Thread, so you could just replace sendmail() by:

threading.Thread(target=sendmail).start()

after:

import threading
Sign up to request clarification or add additional context in comments.

Comments

2

There are several ways of implementing threading in Python. One very simple solution for you would be

    import thread
    def register():
        ...
        some judgment
        ...
        if true:
        thread.start_new_thread(sendmail,())
        return redirect(url_for('onepage'))

This will start sendmail() asynchronously. However, if sendmail fails or returns something, you will need to use something else.

There are plenty of tutorials about Threading in python, I found this quite nice http://www.tutorialspoint.com/python/python_multithreading.htm

2 Comments

Thanks elactic! It's really useful for me !
You're, welcome. But Evpok is right, threading might be the better choice over Thread.
1

I have not threading solution: I'm using celery for hard operations: send email, fetch url, create many database records, periodic tasks.

+ you can use flask application and celery instances on different servers

- you need backend (rabbitmq, redis, mongodb and etc.)

2 Comments

ok. Thanks tbicr. I'll take a look at flask-celery. Hoping it can help me. Thanks~
From celery 3.0 you can use just celery without flask-celery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.