制作在线用户的对象数组

时间:2018-07-27 13:13:26

标签: python django python-3.x django-rest-framework

我获取在线用户ips和代理的代码是以下代码:

现在结果是这样的,来自
     request.__class__.online_now_ips = res

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

但是我想要这样的结果?我怎样才能做到这一点 ?吨

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

主要代码(在线用户中间件):

   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

1 个答案:

答案 0 :(得分:0)

不添加-

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)