2017-08-01 45 views
-3

私はDjangoでPOSTリクエストを行い、バイトオブジェクトを受信して​​います。特定のユーザーがこのオブジェクトに表示された回数をカウントする必要がありますが、次のエラーが表示されます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'> 

にはどうすればpeform_count()関数を使用してUSER001出現する回数を数えることができますか?この機能を使用するには、どのような変更が必要ですか?

+0

stacktraceはプラスになります... –

+1

これはどうですか?私はこの質問の詳細を提供するために私に何が必要なのですか? –

+1

@AlejandroRamos:どのコード行で例外がスローされ、どのようにPythonがそこに到達したのか理解できます。 –

答えて

1

は、[はい、バイトを受信んが、その後、(response.text属性を経由して、automatically decodes the datarequestsライブラリデコードそれを、持っているあなた、その後再エンコード自分:

離れてちょうどから
response = filter_url(user).text.encode('utf-8') 

data = filter_url(user).json() 

: - デコードを避けるために、代わりにresponse.content attributeを使用して>エンコード往復、あなたは本当にただdecode the data as JSONべきは辞書のリストであり、あなたのperform_count()関数はそれを直接操作できます。