posts - 431,  comments - 344,  trackbacks - 0
          原文地址:http://groups.google.it/group/django-users/browse_thread/thread/4ba5652bcbd1f958/958c6e7733a26a9c?hl=it&lnk=gst&q=average+time&rnum=3#958c6e7733a26a9c

          So, here is my version, using the cache backend:

          from datetime import timedelta, datetime
          from django.core.cache import cache
          from django.contrib.sites.models import Site

          ONLINE_MINUTES = 10
          CACHE_KEY = '%s_online_user_ids' % Site.objects.get_current().domain

          _last_purged = datetime.now()

          def get_online_user_ids():
              user_dict = cache.get(CACHE_KEY)
              return hasattr(user_dict, 'keys') and user_dict.keys() or []

          class OnlineUsers(object):
              def process_request(self, request):
                  if request.user.is_anonymous():
                      return

                  user_dict = cache.get(CACHE_KEY)
                  if not user_dict:
                      # initialization
                      user_dict = {}

                  now = datetime.now()
                  user_dict[request.user.id] = now

                  # purge
                  global _last_purged
                  if _last_purged + timedelta(minutes=ONLINE_MINUTES) < now:
                      purge_older_than = now - timedelta(minutes=ONLINE_MINUTES)
                      for user_id, last_seen in user_dict.items():
                          if last_seen < purge_older_than:
                              del(user_dict[user_id])
                      _last_purged = now

                  cache.set(CACHE_KEY, user_dict, 60*60*24)

          This stores a dictionary in the form: {user_id: last_seen_time, ...}
          in the cache and updates the cache once for every request by an
          authenticated user.

          An alternative would be to store a structure like Jeremy's,
          {minute_seen: set(user_id, ...), ...} which I think will result in
          nearly the same amount of cache hits on average.

          I would like to hear your comments.

          posted on 2009-07-08 08:41 周銳 閱讀(757) 評論(1)  編輯  收藏 所屬分類: Python
          主站蜘蛛池模板: 吴堡县| 贵州省| 酒泉市| 青铜峡市| 甘洛县| 南部县| 沁水县| 宁城县| 额尔古纳市| 姜堰市| 象山县| 隆化县| 当雄县| 泰和县| 辽宁省| 白河县| 全椒县| 万盛区| 正镶白旗| 海晏县| 分宜县| 南溪县| 山丹县| 文水县| 抚顺县| 澎湖县| 绥中县| 锦州市| 安庆市| 正宁县| 多伦县| 吴江市| 正定县| 湾仔区| 赣州市| 扎鲁特旗| 大名县| 武夷山市| 金山区| 海兴县| 临夏县|