我开发了一个Python模块,用于将PDF文件上传到我的Parse.com项目。我使用了"请求"用于与https Parse.com服务器通信。这些代码试图涵盖与Parse通信时可能遇到的所有可能异常,因为我有一个公司防火墙。
import env
import json
import requests
def uploadFile(fileFullPath):
result = False
print "Attempting to upload file: " + fileFullPath
headers = {"X-Parse-Application-Id": env.X_Parse_Application_Id,
"X-Parse-REST-API-Key": env.X_Parse_REST_API_Key,
"Content-Type": "application/json"}
try:
f = open(fileFullPath, 'r')
files = {'file': f}
r = requests.post(env.PARSE_HOSTNAME + env.PARSE_FILES_ENDPOINT + "/" + env.PARSE_UPLOADED_FILE_NAME, files=files, headers=headers)
jsonResult = r.json()
if 'error' in jsonResult:
print "An error occurred while trying to upload the file to Parse.com. Details: " + (jsonResult["error"])
else:
print jsonResult["name"]
print jsonResult["url"]
print "Completed uploading the file."
result = True
# Unable to open the file
except IOError as ex:
print 'IOError thrown. Details: ' + ' %s' % ex
# If file cannot be opened, IOError is thrown as well, so exit the function to avoid calling "f.close()" in "finally"
# In the event of a network problem (e.g. DNS failure, refused connection, etc)
except ConnectionError as ex:
print 'ConnectionError thrown. Details: ' + ' %s' % ex
# In the event of an invalid HTTP response
except HTTPError as ex:
print 'HTTPError thrown. Details: ' + ' %s' % ex
# If time-out occurs
except Timeout as ex:
print 'Timeout exception thrown. Details: ' + ' %s' % ex
# If a request exceeds the configured number of maximum redirections
except TooManyRedirects as ex:
print 'TooManyRedirects exception thrown. Details: ' + ' %s' % ex
# All other exceptions
except Exception as ex:
print 'Unexpected error. Details:' + ' %s' % ex
else:
f.close()
finally:
return result
if __name__ == "__main__":
myFilePath = r'D:/myfile.pdf'
print uploadFile(myFilePath)
我的问题是这些例外的顺序是否正确。 IOError是否总是取代任何其他错误?