我正在與Twisted的Web服務工作,負責調用我以前在命令行上使用過的幾個包。這些軟件包處理的例程正在自行開發,但現在已準備好集成到我們的Web服務中。扭曲的Web服務-sql連接丟失
總之,我有幾個不同的模塊,它們都在其原始命令行窗體中內部創建一個mysql連接屬性。藉此,例如:
class searcher:
def __init__(self,lat,lon,radius):
self.conn = getConnection()[1]
self.con=self.conn.cursor();
self.mgo = getConnection(True)
self.lat = lat
self.lon = lon
self.radius = radius
self.profsinrange()
self.cache = memcache.Client(["173.220.194.84:11211"])
的GetConnection函數只是分別返回蒙戈或MySQL光標一個幫手。再次,這是全部原型:)
我遇到的問題是當作爲一個持續運行的服務器使用Twisted的WSGI資源實現時,在init超時創建的sql連接,並且後續請求似乎不會重新生成它。對於小型服務器應用程序的示例代碼:
from twisted.web import server
from twisted.web.wsgi import WSGIResource
from twisted.python.threadpool import ThreadPool
from twisted.internet import reactor
from twisted.application import service, strports
import cgi
import gnengine
import nn
wsgiThreadPool = ThreadPool()
wsgiThreadPool.start()
# ensuring that it will be stopped when the reactor shuts down
reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop)
def application(environ, start_response):
start_response('200 OK', [('Content-type','text/plain')])
params = cgi.parse_qs(environ['QUERY_STRING'])
try:
lat = float(params['lat'][0])
lon = float(params['lon'][0])
radius = int(params['radius'][0])
query_terms = params['query']
s = gnengine.searcher(lat,lon,radius)
query_terms = ' '.join(query_terms)
json = s.query(query_terms)
return [json]
except Exception, e:
return [str(e),str(params)]
return ['error']
wsgiAppAsResource = WSGIResource(reactor, wsgiThreadPool, application)
# Hooks for twistd
application = service.Application('Twisted.web.wsgi Hello World Example')
server = strports.service('tcp:8080', server.Site(wsgiAppAsResource))
server.setServiceParent(application)
最初的幾個要求做工精細,但mysqls wait_timeout
到期後,恐懼錯誤2006年「MySQL已經走了」錯誤的表面。我的理解是,對WSGI Twisted資源的每個請求都將運行應用程序函數,從而重新生成搜索器對象並重新租用連接。如果情況並非如此,我如何能夠像這樣處理請求?在這種意義上,這種Twisted部署不是事務性的嗎?謝謝!
編輯:每請求時,這裏是原型輔助函數調用的連接:
def getConnection(mong = False):
if mong == False:
connection = mysql.connect(host = db_host,
user = db_user,
passwd = db_pass,
db = db,
cursorclass=mysql.cursors.DictCursor)
cur = connection.cursor();
return (cur,connection)
else:
return pymongo.Connection('173.220.194.84',27017).gonation_test
你的MySQL連接創建邏輯隱藏在省略'getConnection'功能。如果包含該函數的定義以及發生的確切異常(並且最好是回溯),則問題可能會更清晰且更易於回答。 –