使用Python检查dev_appserver是否在本地运行
我有一个脚本,用来连接到localhost:8080,以便在dev_appserver实例上运行一些命令。我使用了remote_api_stub
和httplib.HTTPConnection
这两种工具。在我调用这两个工具之前,我想先确认一下服务器是否真的在运行。
在Python中,判断以下两点的“最佳做法”是什么呢:
- 如何确认localhost:8080上是否有任何网页服务器在运行?
- 如何确认dev_appserver是否在localhost:8080上运行?
3 个回答
0
我有一个用来构建项目的脚本,它通过远程接口来执行一些操作。为了确认服务器是否在运行,我只需要用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>
你也可以在Python中用call
来做到同样的事情(前提是你的电脑上安装了curl)。
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
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