[英]String error in my python api wrapper class
I'm writing an API wrapper to a couple of different web services. 我正在为几个不同的Web服务编写API包装器。
I have a method that has an article url, and I want to extract text from it using alchemyapi. 我有一个文章网址的方法,我想用alchemyapi从中提取文本。
def extractText(self):
#All Extract Text Methods ---------------------------------------------------------//
#Extract page text from a web URL (ignoring navigation links, ads, etc.).
if self.alchemyapi == True:
self.full_text = self.alchemyObj.URLGetText(self.article_link)
which goes to the following code in the python wrapper 它转到python包装器中的以下代码
def URLGetText(self, url, textParams=None):
self.CheckURL(url)
if textParams == None:
textParams = AlchemyAPI_TextParams()
textParams.setUrl(url)
return self.GetRequest("URLGetText", "url", textParams)
def GetRequest(self, apiCall, apiPrefix, paramObject):
endpoint = 'http://' + self._hostPrefix + '.alchemyapi.com/calls/' + apiPrefix + '/' + apiCall
endpoint += '?apikey=' + self._apiKey + paramObject.getParameterString()
handle = urllib.urlopen(endpoint)
result = handle.read()
handle.close()
xpathQuery = '/results/status'
nodes = etree.fromstring(result).xpath(xpathQuery)
if nodes[0].text != "OK":
raise 'Error making API call.'
return result
However I get this error --- 但是我得到这个错误---
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "text_proc.py", line 97, in __init__
self.alchemyObj.loadAPIKey("api_key.txt");
File "text_proc.py", line 115, in extractText
if self.alchemyapi == True:
File "/Users/Diesel/Desktop/AlchemyAPI.py", line 502, in URLGetText
return self.GetRequest("URLGetText", "url", textParams)
File "/Users/Diesel/Desktop/AlchemyAPI.py", line 618, in GetRequest
raise 'Error making API call.'
I know I'm somehow passing the url string to the api wrapper in a faulty format, but I can't figure out how to fix it. 我知道我以某种方式将url字符串以错误的格式传递给api包装器,但我无法弄清楚如何修复它。
您应该引发Exception或其子类,而不是字符串。
The information provided is not actually very helpful to diagnose or solve the problem. 提供的信息实际上对诊断或解决问题并没有多大帮助。 Have you considered taking a look at the response from the server?
您是否考虑过查看服务器的响应? You might inspect a complete traffic log using Fiddler .
您可以使用Fiddler检查完整的流量日志。
Additionally, the SDK provided by Alchemy doesn't seem to be of - cough, cough - the greatest quality. 此外,Alchemy提供的SDK似乎不是 - 咳嗽,咳嗽 - 最高质量。 Since it really consists only of around 600 lines of source code, I'd consider writing a shorter, more robust / pythonic / whatever SDK.
由于它实际上只包含大约600行源代码,因此我考虑编写一个更短,更健壮/ pythonic /任何SDK。
I might also add that right now, even the on-site demo at the Alchemy web site is failing, so maybe your problem is related to that. 我现在也可以补充说,即使Alchemy网站上的现场演示失败了,所以也许你的问题与此有关。 I really suggest taking a look at the traffic.
我真的建议看一下流量。
You're getting the error because your function GetRequest()
raising a string as an exception: 您收到错误是因为您的函数
GetRequest()
将字符串作为异常引发:
if nodes[0].text != "OK":
raise 'Error making API call.'
If that's not what you want, you have two options: 如果那不是你想要的,你有两个选择:
return
the string or None
, or return
字符串或None
,或 Exception
(as suggested by knutin ) Exception
的真实子类(由knutin建议) In either case, if you are assigning that return value to a variable, you can handle it accordingly. 在任何一种情况下,如果要将该返回值分配给变量,则可以相应地处理它。 Here is an example:
这是一个例子:
Option 1 Let's assume you decide to have GetRequest()
return None
: 选项1假设您决定让
GetRequest()
返回None
:
def URLGetText(self, url, textParams=None):
self.CheckURL(url)
if textParams == None:
textParams = AlchemyAPI_TextParams()
textParams.setUrl(url)
# Capture the value of GetRequest() before returning it
retval = self.GetRequest("URLGetText", "url", textParams)
if retval is None:
print 'Error making API call.' # print the error but still return
return retval
def GetRequest(self, apiCall, apiPrefix, paramObject):
# ...
if nodes[0].text != "OK":
return None
return result
This option is a little ambiguous. 这个选项有点含糊不清。 How do you know that it was really an error, or the return value truly was
None
? 你怎么知道它确实是一个错误,或者返回值真的是
None
?
Option 2 This is probably the better way to do it: 选项2这可能是更好的方法:
First create an subclass of Exception
: 首先创建
Exception
的子类:
class GetRequestError(Exception):
"""Error returned from GetRequest()"""
pass
Then raise it in GetRequest()`: 然后在GetRequest()中提升它:
def URLGetText(self, url, textParams=None):
self.CheckURL(url)
if textParams == None:
textParams = AlchemyAPI_TextParams()
textParams.setUrl(url)
# Attempt to get a legit return value & handle errors
try:
retval = self.GetRequest(apiCall, apiPrefix, paramObject)
except GetRequestError as err:
print err # prints 'Error making API call.'
# handle the error here
retval = None
return retval
def GetRequest(self, apiCall, apiPrefix, paramObject):
# ...
if nodes[0].text != "OK":
raise GetRequestError('Error making API call.')
return result
This way you're raising a legitimate error when GetRequest() doesn't return the desired result, and then you can handle the error using a try..except
block and optionally print the error, stop the program there, or keep going (which is what I think you want to do based on your question). 这样,当GetRequest()没有返回所需的结果时,你就会引发一个合法的错误,然后你可以使用
try..except
块处理错误,并可选择打印错误,在那里停止程序,或继续(这是我认为你想根据你的问题做的事情)。
This is Shaun from AlchemyAPI. 这是来自AlchemyAPI的Shaun。 We just posted a new version of the python SDK that raises exceptions properly.
我们刚刚发布了一个新版本的python SDK,可以正常引发异常。 You can get it here http://www.alchemyapi.com/tools/ .
你可以在http://www.alchemyapi.com/tools/找到它。
If you have any other feedback about the SDK, please message me. 如果您对SDK有任何其他反馈,请给我留言。 Thanks for using our NLP service.
感谢您使用我们的NLP服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.