【发布时间】:2015-05-25 17:48:41
【问题描述】:
我正在使用 requests 库发出 HTTP 请求,并且我想创建一个简单的响应对象来解析我的数据。我遇到的问题如下。将响应对象传递给我的 ApiResponse 时,我将 Response.text 分成几行,对它们进行计数并知道它是多行还是单行。问题是拆分线列表在将 len() 应用于该列表时给了我一个错误,但在控制台中它可以正常工作。
这是课程:
class ApiResponse(object):
pattern = re.compile(r'([a-zA-Z]+): ([a-zA-Z0-9]+)') # original ([a-zA-Z]+)\: ([a-zA-Z0-9]+)
response_type = ResponseType.OK
response_mode = ResponseMode.SINGLE
def __init__(self, r: resp):
self.r = r
self.parse(r)
self.data = None
def parse(self, r: resp):
"""
Method that parses the response from the API
:param r:Response
"""
if r.status_code != 200:
self.response_type = ResponseType.ERR
if len(r.text.splitlines()) > 1:
self.response_mode = ResponseMode.MULTI
for line in r.text.splitlines():
match = self.pattern.search(line)
if match is None:
break
print(match.group(1, 2)) # REMOVE testing
self.response_type = ResponseType[match.group(1)]
这是控制台输出:
>>> import sys
>>> print(sys.version)
3.4.2 (default, Oct 8 2014, 13:08:17)
[GCC 4.9.1]
>>> import requests
>>> from clickapy.response import ApiResponse
>>> r = requests.get(API_URL, {'user': USER, 'password': PASS, 'api_id': API_ID})
>>> api_response = ApiResponse(r)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/eefret/PycharmProjects/clickapy/clickapy/response.py", line 32, in __init__
self.parse(r)
File "/home/eefret/PycharmProjects/clickapy/clickapy/response.py", line 43, in parse
if len(r.text.splitlines()) > 1:
TypeError: object of type 'builtin_function_or_method' has no len()
>>> len(r.text.splitlines())
1
为什么会这样?这对我来说没有意义,我正在执行相同的代码,欢迎任何帮助或反馈。
【问题讨论】:
-
不要将
is或is not与数字一起使用!不要将类属性用作预定义的实例属性。 -
不相关但应该是
if r.status_code != 200: -
已更正,但仍在做同样的事情
-
这是从实际的解释器输出中复制粘贴过来的,对吧?因为到目前为止,最可能的解释是代码实际上是
len(r.text.splitlines)。检查response.pyc文件,如果有则将其删除,然后重新检查response.py文件以确保该行看起来像您认为的那样。 -
是否只发生在需要帐户数据的 URL 上,还是您也可以使用
http://google.com等公共 URL 复制它,以便我们自己尝试?
标签: python string typeerror python-3.4