首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >制作在线用户的对象数组

制作在线用户的对象数组
EN

Stack Overflow用户
提问于 2018-07-27 13:13:26
回答 1查看 48关注 0票数 0

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

现在的结果是这样的,它来自于

request.__class__.online_now_ips = res

代码语言:javascript
复制
"ips": [
    {
        "ip": "127.0.0.1"
    },
    {
        "agent": "PostmanRuntime/7.1.5"
    }
]

但我想得到这样的结果?我怎么能这么做?安士

代码语言:javascript
复制
"ips": [
    {
        "ip": "127.0.0.1","agent": "PostmanRuntime/7.1.5"
    },
    {
        ....
    }
]

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

代码语言:javascript
复制
   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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-27 13:19:03

别附加-

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51558745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档