pythonWeb blinker signal frame flask used to solve business code decoupling mechanism ImportError: can not import name 'app', in order to send messages asynchronously Example

Baidu most of the day, do not know how, until learning the blinker to think about solutions, because before you write java files are separate,

Therefore, E-mail service code is also placed inside the view, but requires the use of asynchronous thread App, pain egg other modules can not import any variable from app.py:

which is: 

app.py master file, view.py are business documents, I need to use the app in view of variables in how to do, Baidu a lot, there is no way to find

Here you can achieve with a signal, the first record it:

python3 built blinker, can be used directly, first define the signal in view in:

 

Then connect the app.py which function you want to use (this function needs to use app, we can only write in appp.py years), app can import other modules of the variables:

# The Flask-Mail in the send () function uses current_app, you must activate the application context. 
# However, the implementation of mail.send in different threads () function, the application context to be used app.app_context () to create artificial 
DEF send_async_email (msg):
     Print ( " --- start sending --- " ) 
    with app.app_context (): 
        mail.send (MSG) 


# amount signal is introduced into the view, the asynchronous transmission function and connected 
signal.connect (send_async_email)

 

The last view using the function of signal calling app:

 

user.route @ ( ' / sendsync / ' )
 DEF send_sync_mail (): 
    MSG = the Message (= Subject " the Hello World! " , 
                  SENDER = " [email protected] " , 
                  Recipients = [ " [email protected] " ]) 
    msg.body = " test asynchronous transmit " 
    msg.html = " <H2> test asynchronous transmission </ H2> " 
    Thr = the Thread (target = signal.send, args = [MSG,]) 
    Thr.start()
    return "ok"

 

The last test was successful:

Here you can also use the sender accepts only specified parameters, such as:

Only when the time is 2, will enter round_two method

Guess you like

Origin www.cnblogs.com/houzheng/p/10990372.html