简体   繁体   中英

make array of object of online user

my code to get online users ips and agent is the following code:

now result is like this it is comes from
request.__class__.online_now_ips = res

"ips": [
    {
        "ip": "127.0.0.1"
    },
    {
        "agent": "PostmanRuntime/7.1.5"
    }
]

but i want get result like this? how can i do that ? thanls

"ips": [
    {
        "ip": "127.0.0.1","agent": "PostmanRuntime/7.1.5"
    },
    {
        ....
    }
]

main code (online user middleware):

   def process_request(self, request):
        # Check the IP address
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        the_agent = request.META['HTTP_USER_AGENT']
        if x_forwarded_for:
            user_ip = x_forwarded_for.split(',')[0]
        else:
            user_ip = request.META.get('REMOTE_ADDR')
        # Get the list of the latest online users
        online = cache.get('online_now')
        online_age = cache.get('online_now_agent')

        res = []


        # Check the active IP addresses
        if online:
            online = [ip for ip in online if cache.get(ip)]
            for ip in online:
                if cache.get(ip):
                    res.append({"ip": user_ip})
        else:
            online = []

        if online_age:
            online_age = [ip for ip in online_age if cache.get(ip)]
            for ip in online_age:
                if cache.get(ip):
                    res.append({"agent":the_agent})
        else:
            online_age = []
        # Add the new IP to cache
        cache.set(user_ip, user_ip, 600)
        cache.set(the_agent, the_agent, 600)
        # Add the new IP to list if doesn't exist
        if user_ip not in online:
            online.append(user_ip)

        if the_agent not in online_age:
            online_age.append(the_agent)
        # Set the new online list
        cache.set('online_now', online)
        cache.set('online_now_agent', online_age)

        # Add the number of online users to request
        request.__class__.online_now = len(online)
        request.__class__.online_now_ips = res
    pass

Don't append -

res = []
res_dict = {"ip": "", "agent": ""}
if online:
    online = [ip for ip in online if cache.get(ip)]
    for ip in online:
        if cache.get(ip):
            # res.append({"ip": user_ip})
            res_dict["ip"]: user_ip
    else:
        online = []

if online_age:
    online_age = [ip for ip in online_age if cache.get(ip)]
    for ip in online_age:
        if cache.get(ip):
            # res.append({"agent":the_agent})
            res_dict["agent"]: the_agent
    else:
        online_age = []

# and append to res here
res.append(res_dict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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