我正在用requests库发出一个HTTP请求,我想创建一个简单的响应对象来解析我的数据。我现在的问题是。当将response对象传递给我的ApiResponse时,我将response.text分成几行,对它们进行计数,并知道它是否有多行或单行。问题是splitlines列表在对其应用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
为什么会这样?这对我来说没有意义,我正在执行相同的代码,任何帮助或反馈都是受欢迎的。
最佳答案
我的一个朋友(所有Mariano Garcia
的学分)帮助了我,由于他没有这样的帐户,我将发布解决此行为的方法,我的控制台正在强制执行utf-8
,但在内部,文本仍然需要编码,所以解决此问题的方法是将此if len(r.text.splitlines()) > 1:
更改为此if len(r.text.encode("utf-8").splitlines()) > 1:
完整代码:
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.encode("utf-8").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)]
关于python - len和str.splitlines()的怪异行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30443548/