简体   繁体   中英

Asynchronous Service Calls Python

I am working on a service wherein we have to store the user data in DB and send an email to the user as a notification and return the success response and it is taking some time to complete this process.

As Python script execute synchronously I want to run this process asynchronously, for example, user details are stored and return the success response and then mail process has to be done asynchronously (later after returning the success response) such that the overall response should not depend on this mail execution

    def userregistration(details):
        #store user details
         result = storeuserdb(details)
         print("storeuserdb result", result)
         result["status"] == True:  
             sendmailtouser()     #have to be asynchronously
         return result

    def storeuserdb(details)
       #store code goes here


    def sendmailtouser()
       #email code goes here

Is there any chance to run again after returning the response to service? Like this

    def userregistration(details):
        #store user details
         result = storeuserdb(details)
         print("storeuserdb result", result)
         return result
         result["status"] == True:  
             sendmailtouser()     #have to be asynchronously

You can use Threads. Here is a little example:

import threading

def worker(num):
    """thread worker function"""
    print 'Worker: %s\n' % num 
    if num == 1:
        print 'I am number 1'
        raw_input("Press Enter to continue...")
    return

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

Output:

Worker: 3
Worker: 0
Worker: 1
Worker: 2
Worker: 4

I am number 1
Press Enter to continue...

The program does not stop when the worker 1 is handled. Although an input is expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM