BaseHTTPRequestHandler,HTTPServer

python在繼承中,基類的構造函數(init)方法不會被自動調用,它需要在其派生類的構造函數中顯示調用。
比如我需要在BaseHTTPRequestHandler類中做一下初始化工作,比如連接數據庫。

 class RequestHandler(BaseHTTPRequestHandler):
     def __init__(self, request, client_address, server):
         BaseHTTPRequestHandler.__init__(self, request, client_address, server)
         try:
             self.conn = MySQLdb.connect(host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, \
                     passwd=MYSQL_PASSWD, db=MYSQL_DB,charset=MYSQL_CHARSET)
         except Exception, e:
             print e
         print 'connect database success'

比如我需要在HTTPServer類中做一下初始化工作,比如連接數據庫。

 class MyHTTPServer(HTTPServer):
     def __init__(self, server_address, RequestHandlerClass):
         HTTPServer.__init__(self, server_address, RequestHandlerClass)
         try:
             self.conn = MySQLdb.connect(host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, \
                     passwd=MYSQL_PASSWD, db=MYSQL_DB,charset=MYSQL_CHARSET)
         except Exception, e:
             print e
         print 'connect database success'
發佈了53 篇原創文章 · 獲贊 20 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章