I am using python tornado to run non-block function, how should I pass params to main function?
from __future__ import print_function
from tornado import ioloop, gen
import tornado_mysql
import time
@gen.coroutine
def main(index):
conn = yield tornado_mysql.connect(host=db_host, port=3306, user=db_user, passwd=db_psw, db=db_db)
cur = conn.cursor()
sql = 'INSERT INTO `ctp_db`.`if1506` (`bid`) VALUES (%s)'
yield cur.execute(sql, (index))
conn.commit()
cur.close()
conn.close()
ioloop.IOLoop.current().run_sync(main)
The Tornado Web Framework Since it uses asyncio, with Tornado you can create a node. js-like web server that runs asynchronously, thus able to handle many more requests than if it were running synchronously.
An I/O event loop for non-blocking sockets. In Tornado 6.0, IOLoop is a wrapper around the asyncio event loop, with a slightly different interface. The IOLoop interface is now provided primarily for backwards compatibility; new code should generally use the asyncio event loop interface directly. The IOLoop.
The only way to do it is for thread 2 to call ioloop. add_callback(ioloop. stop), which will call stop() on thread 1 in the event loop's next iteration. Rest assured, ioloop.
Method IOLoop.run_sync()
аccepts reference to a function and tries to invoke it.
So, if you want to run non-blocking function with specified params, you should wrap it with another function.
You can do this using additional function, the both examples below are correct:
def run_with_args(func, *args):
return func(*args)
ioloop.IOLoop.current().run_sync(run_with_args(main, index))
The shorter way with lambda
:
ioloop.IOLoop.current().run_sync(lambda: main(index))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With