我编写了这个片段,从python中的审查板中提取审查请求状态。它运行得很好,但是我对python非常陌生,我想知道我是否能更好地编写它。
我应该把conn.close放在它自己的try语句中吗?
这个脚本应该作为mercurial的后提交钩子的一部分运行。如果审查板服务器没有响应,我仍然希望能够提交没有任何问题。如果提交不存在,那么空字符串就可以了。
import httplib
import json
def getReviewStatus(reviewboardUrl, id):
try:
conn = httplib.HTTPConnection(reviewboardUrl, 80)
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
}
conn.request("GET", "/api/review-requests/%s/" % id, headers=headers)
return json.loads(conn.getresponse().read())['review_request']['status']
except:
return ""
finally:
conn.close()发布于 2013-05-30 16:55:30
我觉得挺不错的。对于conn.close(),绝对不要把它放在自己的try语句中,因为如果前面的代码有问题,连接可能不会关闭。我知道您没有使用Python3,但是可以考虑使用with语句,让Python来处理关闭过程。参见http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects (本节末尾)和http://docs.python.org/2/library/contextlib.html#contextlib.closing
您的代码可能如下所示:
import httplib
import json
from contextlib import closing
def getReviewStatus(reviewboardUrl, id):
try:
with closing(httplib.HTTPConnection(reviewboardUrl, 80)) as conn:
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
}
conn.request("GET", "/api/review-requests/%s/" % id, headers=headers)
return json.loads(conn.getresponse().read())['review_request']['status']
except:
return ""我发现养成使用with打开资源的习惯是很好的,所以不必担心忘记关闭连接。
https://codereview.stackexchange.com/questions/26762
复制相似问题