[英]How to iterate over a bytes object in Python?
我正在 Django 中做一個 POST 請求,我正在接收一個字節對象。 我需要計算特定用戶出現在此對象上的次數,但我收到以下錯誤TypeError: 'int' object is not subscriptable
。 這是我到目前為止:
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 出現的次數? 此功能需要進行哪些修改才能工作?
您確實收到了字節,是的,但是您讓requests
庫對其進行解碼(通過response.text
屬性,它會自動對數據進行解碼),然后您自己重新編碼:
response = filter_url(user).text.encode('utf-8')
除了僅使用response.content
屬性來避免解碼 -> 編碼往返之外,您實際上應該將數據解碼為 JSON :
data = filter_url(user).json()
現在data
是一個字典列表,您的perform_count()
函數可以直接對其進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.