以下函数连接到API并返回json对象。虽然它只适用于开发。在生产服务器中,它只返回False。
为什么它在不同的服务器上不起作用的任何想法?
def request_api(api_call, post_fields, authentication_data = None):
try:
log.debug("Connecting To API: " + settings.API_URL + api_call)
curl = pycurl.Curl()
curl.setopt(pycurl.URL, settings.API_URL + api_call)
except:
log.debug("Can't connect To API: " + settings.API_URL + api_call)
if post_fields:
try:
log.debug("Post Fields: " + post_fields)
curl.setopt(curl.POSTFIELDS, str(post_fields))
except:
log.debug("Error setting post fields.")
if authentication_data:
try:
log.debug("Authentication Fields: " + authentication_data)
curl.setopt(pycurl.USERPWD, authentication_data)
except:
log.debug("Error during authentication.")
try:
contents = StringIO.StringIO()
curl.setopt(pycurl.WRITEFUNCTION, contents.write)
curl.perform()
except:
log.debug("Error on curl.")
try:
responseCode = curl.getinfo(pycurl.HTTP_CODE);
log.debug("Response Code: " + str(responseCode))
except:
log.debug("Response Code: Error")
try:
log.debug("Response: " + contents.getvalue())
except:
log.debug("Response: Error")
try:
pyobj = json.loads(contents.getvalue())
log.debug("Response In Json Format: " + str(pyobj))
except:
log.debug("Response In Json Format: Error")
return pyobj
错误:
Exception Type: UnboundLocalError
Exception Value:
local variable 'pyobj' referenced before assignment
日志文件:
[18/Sep/2012 04:07:52] DEBUG [contests.views:29] Connecting To API: https://my-api/v1/token
[18/Sep/2012 04:07:52] DEBUG [contests.views:39] Authentication Fields: test@user.com:test@user.com
[18/Sep/2012 04:49:32] DEBUG [contests.views:51] Error on curl.
[18/Sep/2012 04:49:32] DEBUG [contests.views:54] Response Code: 0
[18/Sep/2012 04:49:32] DEBUG [contests.views:58] Response:
[18/Sep/2012 04:49:32] DEBUG [contests.views:65] Response In Json Format: Error
答案 0 :(得分:2)
造成即时错误的原因是:
try:
pyobj = json.loads(contents.getvalue())
log.debug("Response In Json Format: " + str(pyobj))
except:
log.debug("Response In Json Format: Error")
return pyobj
try
子句失败,正如您在日志中看到的那样,这意味着pyobj
未被定义。当您在函数末尾尝试return
时,它不存在,因此您获得UnboundLocalError
。
为什么此部分失败将导致contents.getValue
崩溃或将不适当的内容传递给json.loads
。但是,因为您正在捕获所有异常并返回自己的错误消息,您隐藏了所有相关的追溯信息,这些信息可以帮助您了解问题的确切位置。回溯将告诉您完全错误是什么以及错误发生在文件&代码行,对你来说比Response In Json Format: Error
更有用。