Search code examples
pythoncherrypy

Can I connect to multiple databases in CherryPy?


cherrypy.engine subscribe()s a function to connect to a database, and this cherrypy.engine start()s with that database subscribed.

If I want to fetch multiple sets of data from different databases, I would need to connect to different databases.

Is there any way to do it in CherryPy without too much change in code?


Solution

  • You will need to use 2 cursors or at least initialize the same one twice. Try something like this...

    import cherrypy 
    import MySQLdb 
    
    def connect(thread_index): 
        # Create a connection and store it in the current thread 
        cherrypy.thread_data.db = MySQLdb.connect('host', 'user', 'password', 'dbname') 
        cherrypy.thread_data.db2 = MySQLdb.connect('host', 'user', 'password', 'dbname2') 
    
    # Tell CherryPy to call "connect" for each thread, when it starts up 
    cherrypy.engine.subscribe('start_thread', connect)
    
    
    class Root: 
        def index(self): 
            # Sample page that displays the number of records in "table" 
            # Open a cursor, using the DB connection for the current thread 
            c = cherrypy.thread_data.db.cursor() 
            c.execute('select count(*) from table') 
            res = c.fetchone() 
            c.close() 
    
            c = cherrypy.thread_data.db2.cursor() 
            c.execute('select count(*) from table2') 
            res = c.fetchone() 
            return "<html><body>Hello, you have %d records in your table</body></html>" % res[0] 
        index.exposed = True 
    
    cherrypy.quickstart(Root())
    

    Hope this helps!