What's the better way to share a connection_pool in both Application/Handler and other place outside Handler like a test file, or a model file?
in main.py
, I define a db_pool in Application, I could use it in any RequestHandler, what if I want to use it outside RequestHandler?
What's the better practice?
code in main.py
import tornado.web
class Application(tornado.web.Application):
"""
自定义的Application
"""
def __init__(self):
# I have a db_pool here
init_dict = {
'db_pool': PooledDB.PooledDB(MySQLdb, **db_server)
}
super(Application, self).__init__(
[(r'/', IndexHandler, init_dict)],
**settings)
code in test.py
from main import Application
# I want to get db_pool here
code in dao.py
def get_config(user):
# I want to get db_pool in main
db = db_pool.connection()
return
Could you help me?
I would store the connection pool inside the Application
class, instead of passing it to your Handlers
. Then, you could access the application inside your handler by calling self.application
inside your GET/POST methods.
class Application(tornado.web.Application):
def __init__(self):
self.db = PooledDB.PooledDB(MySQLdb, **db_server)
super(Application, self).__init__([(r'/', IndexHandler)], **settings)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.application.db.<put a valid method here>()
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.