Ying.Zhao
Ying.Zhao

Reputation: 164

threading programming in python

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?

Upvotes: 2

Views: 3072

Answers (3)

Evpok
Evpok

Reputation: 4485

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

Upvotes: 5

tbicr
tbicr

Reputation: 26070

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.)

Upvotes: 1

Johannes Jasper
Johannes Jasper

Reputation: 921

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

Upvotes: 2

Related Questions