2011-04-22 155 views
3

我有一個腳本用於連接到localhost:8080以在dev_appserver實例上運行一些命令。我使用remote_api_stubhttplib.HTTPConnection的組合。在我對任何一個API進行調用之前,我想確保服務器實際上正在運行。使用python來檢查dev_appserver是否在本地主機上運行

什麼是Python中的 「最佳實踐」 的方式來確定:

  1. 如果任何 Web服務器上的本地主機上運行:8080
  2. 如果dev_appserver是在本地主機上運行:8080?

回答

2

這應做到:

import httplib 

NO_WEB_SERVER = 0 
WEB_SERVER = 1 
GAE_DEV_SERVER_1_0 = 2 
def checkServer(host, port, try_only_ssl = False): 
    hh = None 
    connectionType = httplib.HTTPSConnection if try_only_ssl \ 
              else httplib.HTTPConnection 
    try: 
     hh = connectionType(host, port) 
     hh.request('GET', '/_ah/admin') 
     resp = hh.getresponse() 
     headers = resp.getheaders() 
     if headers: 
      if (('server', 'Development/1.0') in headers): 
       return GAE_DEV_SERVER_1_0|WEB_SERVER 
      return WEB_SERVER 
    except httplib.socket.error: 
     return NO_WEB_SERVER 
    except httplib.BadStatusLine: 
     if not try_only_ssl: 
      # retry with SSL 
      return checkServer(host, port, True) 
    finally: 
     if hh: 
      hh.close() 
    return NO_WEB_SERVER 

print checkServer('scorpio', 22) # will print 0 an ssh server 
print checkServer('skiathos', 80) # will print 1 for an apache web server 
print checkServer('skiathos', 8080) # will print 3, a GAE Dev Web server 
print checkServer('no-server', 80) # will print 0, no server 
print checkServer('www.google.com', 80) # will print 1 
print checkServer('www.google.com', 443) # will print 1 
+1

我注意到你沒有關閉套接字連接 - 多久連接活路,如果你不」明確地關閉它?是否應該有'finally'來確保套接字被關閉? – 2011-04-22 16:31:51

+0

非常好,我修改了它 – gae123 2011-04-22 17:31:18

0

我有一個Ant構建腳本使用remote_api的,做的東西。要驗證服務器正在運行,我只使用curl並確保它沒有返回錯誤。

<target name="-local-server-up"> 
    <!-- make sure local server is running --> 
    <exec executable="curl" failonerror="true"> 
     <arg value="-s"/> 
     <arg value="${local.host}${remote.api}"/> 
    </exec> 
    <echo>local server running</echo> 
    </target> 

你可以只使用call做同樣在Python(假設你有你的機器上捲曲)。

0

我會去像這樣的東西:

import httplib 

GAE_DEVSERVER_HEADER = "Development/1.0" 

def is_HTTP_server_running(host, port, just_GAE_devserver = False): 
    conn= httplib.HTTPConnection(host, port) 
    try: 
     conn.request('HEAD','/') 
     return not just_GAE_devserver or \ 
      conn.getresponse().getheader('server') == GAE_DEVSERVER_HEADER 
    except (httplib.socket.error, httplib.HTTPException): 
     return False 
    finally: 
     conn.close() 

測試了:

assert is_HTTP_server_running('yahoo.com','80') == True 
assert is_HTTP_server_running('yahoo.com','80', just_GAE_devserver = True) == False 
assert is_HTTP_server_running('localhost','8088') == True 
assert is_HTTP_server_running('localhost','8088', just_GAE_devserver = True) == True 
assert is_HTTP_server_running('foo','8088') == False 
assert is_HTTP_server_running('foo','8088', just_GAE_devserver = True) == False 
相關問題