# Twisted, the Framework of Your Internet # Copyright (C) 2001 Matthew W. Lefkowitz # # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ Example: Making database calls from a Resource. One of the most common web development tasks involves connecting to a database, retrieving some data, formatting it as HTML, and returning it to a web browser. There are two primary means of accomplishing this task within the Twisted framework, either via twisted.enterprise (the preferred method), or via twisted.internet.threads. This example demonstrates the second approach; this is mostly useful in cases where you need something "quick and dirty", or where the use of twisted.enterprise would be overkill. """ # python DBAPI imports. Replace with the DBAPI module of your choice. import cx_Oracle # twisted framework imports from twisted.internet.threads import deferToThread from twisted.web.resource import Resource from twisted.web.server import NOT_DONE_YET class DatabaseResource(Resource): """ A resource that performs database access in a separate thread. """ def runQuery(self): """ UNDOCUMENTED """ # replace with your database connection information. connection = cx_Oracle.connect("uid/pwd@database") cursor = connection.cursor() # replace with your SQL query. cursor.execute("SELECT COUNT(*) FROM User_Tables") count = cursor.fetchall()[0][0] cursor.close() connection.close() return count def _cbGotResult(self, result, request): """ Callback for handling the result of the query """ request.write("""\