2015-05-25 26 views
3

我正在做一個HTTP請求與requests庫,我想做一個簡單的響應對象,解析我的數據。我遇到的問題如下。當將響應對象傳遞給我的ApiResponse時,我將線條中的Response.text分開,對它們進行計數並知道它是否有多行或單行。問題是分叉列表給我一個錯誤時應用len(),但在控制檯中,它工作正常。奇怪的行爲與len和str.splitlines()

這是類:

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 

爲什麼發生這種情況?對我來說沒有意義,我正在執行相同的代碼段,歡迎任何幫助或反饋。

+0

不使用'is'或'是not'與數字!不要將類屬性用作預定義的實例屬性。 – Daniel

+0

無關,但它應該是'如果r.status_code!= 200:' –

+0

更正,但仍然這樣做 – Eefret

回答

1

我的一個朋友(所有學分Mariano Garcia)已經幫我和他沒有SO佔我將發佈什麼解決了這個問題,我的控制檯被執行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)]