I meet the same situation just now, then go through some examples on github and do it.
I split my files as follows:
- server.py: run the application
- urls.py: define handlers and ui_modules
- da.py: identify useful methods for accessing data.
Below is a brief description of each file, I think this will help you solve your problem.
urls.py
import main import topic handlers=[] handlers.extend(main.handlers) handlers.extend(topic.handlers) ui_modules={}
da.py
import tornado.database
from tornado.options import define,options define("mysql_host", default="127.0.0.1:3306", help="database host") define("mysql_database", default="forum", help="database name") define("mysql_user", default="root", help="database user") define("mysql_password", default="111111", help="database password") db = tornado.database.Connection( host=options.mysql_host, database=options.mysql_database, user=options.mysql_user, password=options.mysql_password)
server.py
import os import tornado.database import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options define("port", default=8888, help="run on the given port", type=int) import da class Application(tornado.web.Application): def __init__(self): from urls import handlers,ui_modules settings = dict( template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), xsrf_cookies=True, cookie_secret="11oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=", login_url="/signin", ui_modules=ui_modules, debug=True, ) super(Application,self).__init__(handlers,**settings)
You can use db only 'from da import *', and then everything will be fine, or you can write BaseHandler extends tornado.web.RequestHandler and define the property:
class BaseHandler(tornado.web.RequestHandler): @property def db(self): return self.application.db
Each handler that extends BaseHandler can use self.db to perform database operations.