如何在Python中迭代bytes对象?

2024-04-23 06:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django中执行POST请求,并接收到一个bytes对象。我需要计算一个特定用户出现在这个对象上的次数,但是我收到了以下错误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出现的次数?此功能需要哪些修改才能工作?在


Tags: oftheurlbytesobjectisresponsedef
1条回答
网友
1楼 · 发布于 2024-04-23 06:15:54

您确实收到字节,是的,但是您让requests库对其进行解码(通过response.text属性,automatically decodes the data),然后由您自己对其重新编码:

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

除了使用^{} attribute来避免解码-gt;编码往返之外,您实际上应该只使用decode the data as JSON

^{pr2}$

现在data是一个字典列表,您的perform_count()函数可以直接对其进行操作。在

相关问题 更多 >