在内部服务器错误(500)后自动重新运行Python脚本?

时间:2015-05-22 08:33:22

标签: python-2.7 urllib2

我有一个连接到远程服务器以下载数据的python脚本。偶尔我会得到500内部服务器错误,我必须手动重新运行脚本。是否有任何代码可以添加到脚本本身,如果发生这种情况会自动重启,所以我不必手动执行此操作?如果它很重要,我正在使用urrlib2来访问Web服务器。非常感谢任何反馈!

编辑:

我尝试了下面发布的答案,但现在得到一个JSON对象错误 - 这是我的功能:

def get_response(url, query='', get_json=True):
    opener = urllib2.build_opener(
             urllib2.HTTPHandler(),
             urllib2.HTTPSHandler(),
             urllib2.ProxyHandler(
                {'https': 'http://u:pw@s:p',
                 'http': 'http://u:pw@s:p'}
    ))
    urllib2.install_opener(opener)
    encoded = urllib.urlencode(query)
    request = urllib2.Request(url, encoded)
    if get_json:
        try:
            return json.loads(urllib2.urlopen(request).read())
        except urllib2.HTTPError, e:
            print '500 error'
            if e.getcode() == 500:
                get_response(url, query='', get_json=True)
    return urllib2.urlopen(request).read()

编辑:

当我将print urllib2.urlopen(request).read()作为try块中的第一行运行时,我得到:

{"token" : "1BgKWHBCyjviLz2skV2eI6RdHK4xi05Mq0CKcq_Ik3-15mpndnlodtSp6-SkOKVIHc8hBk_XwAIfdUurhubybZ8b4Yi176NNXgU75jD7HglQzFcG-wcEe4Ged8AGo_-dkAdVQ2ODf1ai-duxt5tJRQ..","expires" : 1432290875094,"ssl" : false}
{"currentVersion":10.3,"serviceDescription":"Dienst zur Erfassung von Baumschäden zur Erfüllung der Verkehrssicherungspflicht","hasVersionedData":false,"supportsDisconnectedEditing":false,"hasStaticData":false,"maxRecordCount":1000,"supportedQueryFormats":"JSON","capabilities":"Create,Delete,Query,Update,Editing,Extract,Sync","description":"Dienst zur Erfassung von Baumschäden im Rahmen der Erfüllung der Verkehrssicherungspflicht","copyrightText":"","spatialReference":{"wkid":25832,"latestWkid":25832},"initialExtent":{"xmin":348536.13803965045,"ymin":5660234.086535966,"xmax":405622.75221288018,"ymax":5696302.1586721111,"spatialReference":{"wkid":25832,"latestWkid":25832}},"fullExtent":{"xmin":344091.1291496334,"ymin":5640930.047927889,"xmax":410067.76110289729,"ymax":5712908.95763933,"spatialReference":{"wkid":25832,"latestWkid":25832}},"allowGeometryUpdates":true,"units":"esriMeters","size":507904,"syncEnabled":true,"syncCapabilities":{"supportsAsync":true,"supportsRegisteringExistingData":true,"supportsSyncDirectionControl":true,"supportsPerLayerSync":true,"supportsPerReplicaSync":true,"supportsSyncModelNone":true,"supportsRollbackOnFailure":true},"editorTrackingInfo":{"enableEditorTracking":true,"enableOwnershipAccessControl":false,"allowOthersToUpdate":true,"allowOthersToDelete":true},"xssPreventionInfo":{"xssPreventionEnabled":true,"xssPreventionRule":"InputOnly","xssInputRule":"rejectInvalid"},"layers":[{"id":0,"name":"Baumkontrolle AGS-online","parentLayerId":-1,"defaultVisibility":true,"subLayerIds":null,"minScale":0,"maxScale":0},{"id":1,"name":"20110920-VSP-GewUnterh","parentLayerId":-1,"defaultVisibility":true,"subLayerIds":null,"minScale":0,"maxScale":0},{"id":2,"name":"20110920-VSP-Talsp","parentLayerId":-1,"defaultVisibility":true,"subLayerIds":null,"minScale":0,"maxScale":0},{"id":3,"name":"20130211-VSP-BuN_utm","parentLayerId":-1,"defaultVisibility":true,"subLayerIds":null,"minScale":0,"maxScale":0},{"id":4,"name":"20130313-VSP-T3_Badestellen","parentLayerId":-1,"defaultVisibility":true,"subLayerIds":null,"minScale":0,"maxScale":0},{"id":5,"name":"VSP_Strassen","parentLayerId":-1,"defaultVisibility":true,"subLayerIds":null,"minScale":0,"maxScale":0}],"tables":[]}
{"transportType":"esriTransportTypeUrl","responseUrl":"http://services1.arcgis.com/0cr41EdkajvOA232/ArcGIS/rest/services/Forstmobil/replicafiles/e598ff9192da40c98781a90151dc1101.zip"}
500 error
<html>
<head>
  <title>Home</title>
  <link href='/ESRI.ArcGIS.SDS.REST.css' rel='stylesheet' type='text/css'>
  <link rel='SHORTCUT ICON' href='/favicon.ico'>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
  <meta name="keywords" content="ArcGIS REST Services Directory Root">
</head>
<body>
<table width="100%" class="userTable">
<tr>
<td class="titlecell">ArcGIS REST Services Directory</td>
</tr>
</table>
<table class="navTable" width="100%">
<tbody>
<tr valign="top">
<td class="breadcrumbs">
<a href="/0cr41EdkajvOA232/ArcGIS/rest/services">Home</a> > <a href="/0cr41EdkajvOA232/ArcGIS/rest/services">services</a> </td>
<td align="right">
<a href="http://resources.arcgis.com/en/help/arcgis-rest-api/" target="_blank">API Reference</a></td>
</tr>
</tbody>
</table>
<table>
<tr>
<td class="apiref">
<a href="?f=pjson" target="_blank">JSON</a>
</td>
</tr>
</table>
<div class='restHeader'>
<h2>Home</h2>
</div>
<div class='restBody'>
<div class="restErrors">
Token Required<br/>
</div>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您需要捕获错误,然后通过调用脚本自行处理:

def main():
  try:
    # Your script
  except urllib2.HTTPError, e:
    if e.getcode() == 500:
      main()

main()