Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass params to python tornado IOLoop run_sync(main) function

Tags:

python

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)
like image 772
Ben Charlie Avatar asked Jun 11 '15 13:06

Ben Charlie


People also ask

Does tornado use Asyncio?

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.

What is Tornado IOLoop?

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.

How do you stop a tornado 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.


1 Answers

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))
like image 196
pupizoid Avatar answered Oct 27 '22 05:10

pupizoid