简体   繁体   English

如何迭代 Python 中的字节对象?

[英]How to iterate over a bytes object in Python?

I am doing a POST request in Django and I am receiving a bytes object.我正在 Django 中做一个 POST 请求,我正在接收一个字节对象。 I need to count the number of times a particular user appears on this object but I am receiving the following error TypeError: 'int' object is not subscriptable .我需要计算特定用户出现在此对象上的次数,但我收到以下错误TypeError: 'int' object is not subscriptable This is what I have so far:这是我到目前为止:

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'>

How can I count the number of times that user001 appears by using the the peform_count() function?如何使用 peform_count() 函数计算 user001 出现的次数? Which modification does this function require to work?此功能需要进行哪些修改才能工作?

You do receive bytes, yes, but you then have the requests library decode it (via the response.text attribute, which automatically decodes the data ), which you then re-encode yourself:您确实收到了字节,是的,但是您让requests库对其进行解码(通过response.text属性,它会自动对数据进行解码),然后您自己重新编码

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

Apart from just using the response.content attribute instead to avoid the decode -> encode round-trip, you should really just decode the data as JSON :除了仅使用response.content属性来避免解码 -> 编码往返之外,您实际上应该将数据解码为 JSON

data = filter_url(user).json()

Now data is a list of dictionaries, and your perform_count() function can operate on that directly.现在data是一个字典列表,您的perform_count()函数可以直接对其进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM