2017-08-01 44 views
-3

我正在做一個POST請求在Django,我收到一個字節對象。我需要計算特定用戶在此對象上出現的次數,但我收到以下錯誤TypeError: 'int' object is not subscriptable。這是我到目前爲止有:如何迭代Python中的字節對象?

def filter_url(user): 
    ''' do the POST request, this code works ''' 

    filters = {"filter": { 
    "filters": [{ 
     "field": "Issue_Status", 
     "operator": "neq", 
     "value": "Queued" 
    }], 
    "logic": "and"}} 

    url = "http://10.61.202.98:8081/Dev/api/rows/cat/tickets?" 
    response = requests.post(url, json=filters) 
    return response 

def request_count(): 
    '''This code requests a POST method and then it stores the result of all the data 
    for user001 as a bytes object in the response variable. Afterwards, a call to the 
    perform_count function is made to count the number of times that user user001 appeared.''' 

    user = "user001" 
    response = filter_url(user).text.encode('utf-8') 
    weeks_of_data = []  
    weeks_of_data.append(perform_count(response)) 

def perform_count(response): 
    ''' This code does not work, int object is not subscriptable ''' 
    return Counter([k['user_id'] for k in response) 

#structure of the bytes object 
b'[{"id":1018002,"user_id":"user001","registered_first_time":"Yes", ...}]' 

# This is the result that indicates that response is a bytes object. 
print(type(response)) 
<class 'bytes'> 

我怎麼能算的是001出現使用該peform_count()函數的次數?該功能需要哪些修改才能工作?

+0

stacktrace會加... –

+1

這是怎麼回事?你需要我做什麼,我可以提供有關這個問題的更多細節? –

+1

@AjjandroRamos:所以我們可以理解哪一行代碼會拋出異常以及Python如何到達那裏,是的。 –

回答

1

你收到了字節,是的,但你必須在requests庫解碼它(通過response.text屬性,它automatically decodes the data),然後您可以重新編碼自己:

response = filter_url(user).text.encode('utf-8') 

除了剛使用response.content attribute來避免解碼 - >編碼往返,你真的應該只是decode the data as JSON

data = filter_url(user).json() 

現在data是詞典列表,您的perform_count()函數可以直接操作。