Ejemplo n.º 1
0
    def handle(self, *args, **options):

        print '================================'
        print 'init_panelmission'
        print '================================'

        model_mgr = ModelRequestMgr()

        # メンテナンス確認.
        appconfig = BackendApi.get_appconfig(model_mgr)
        if not appconfig.is_maintenance():
            print u'メンテナンスモードにしてください'
            return
        print 'check maintenance...OK'

        delete_target_model_cls_list = (
            PlayerPanelMission,
            PanelMissionData,
        )

        def tr():
            for model_cls in delete_target_model_cls_list:
                tablename = model_cls.get_tablename()
                query_string = "truncate table `%s`;" % tablename
                Query.execute_update(query_string, [], False)
                print 'delete...%s' % tablename

        db_util.run_in_transaction(tr)

        # キャッシュを消す.
        OSAUtil.get_cache_client().flush()

        print '================================'
        print 'all done.'
Ejemplo n.º 2
0
 def reload(self):
     """マスターデータをリロード.
     """
     now_diff = OSAUtil.get_now_diff()
     MasterData.incrementEditCacheVersion()
     rediscache.flush_all()
     OSAUtil.get_cache_client().flush()
     if settings_sub.IS_DEV:
         OSAUtil.set_now_diff(now_diff)
Ejemplo n.º 3
0
    def run(cls, API):

        logger = DbgLogger()
        result = False
        apitest = None
        try:
            apitest = cls()
            apitest.setUp()

            OSAUtil.get_cache_client().flush()  # キャッシュを消しておく.

            apitest.__api_name = API
            print 'API name:%s' % API

            query_params = {
                '_test': 1,
                OSAUtil.KEY_APP_ID: '119733',
            }
            query_params.update(apitest.get_query_params())
            frompagedata = apitest.get_frompagedata()
            if frompagedata is not None:
                frompage_name, frompage_params = frompagedata
                frompage = FromPageUtil()
                frompage.setParams(frompage_name, frompage_params)
                query_params[Defines.URLQUERY_FROM] = '%s' % frompage

            print 'request query_params:%s' % query_params
            args = apitest.get_args()
            print 'request args:%s' % args
            res = cls.__sendRequest('%s%s' % (API, apitest.get_urlargs()),
                                    args, query_params)
            print "response:%s" % res
            if res:
                apitest.response = Json.decode(res)
            else:
                apitest.response = {}

            if 'log' in apitest.response:
                print "\nLog:"
                print apitest.response['log']

            try:
                apitest.check()
            except AppTestError, e:
                print u'AppTestError: %s' % (e.value)
                print '!!!!!!!!!!!!!! NG !!!!!!!!!!!!!!'
            except Exception, e:
                #            print e
                info = sys.exc_info()
                print AppError.makeErrorTraceString(info)
                print '!!!!!!!!!!!!!! NG !!!!!!!!!!!!!!'
Ejemplo n.º 4
0
    def procList(self):
        """一覧表示.
        """
        
        # 絞り込みの引数.
        v_player = self.getViewerPlayer()
        
        client = OSAUtil.get_cache_client()
        
        topic = Defines.PresentTopic.ALL
        page = 0
        sort = "desc"
        if self.request.method == 'GET':
#            topic = client.get(v_player.id, namespace='presentbox:topic') or topic
            sort = client.get(v_player.id, namespace='present:sort') or sort
        
        topic = self.request.get(Defines.URLQUERY_CTYPE, topic)
        page = self.request.get(Defines.URLQUERY_PAGE, page)
        sort = self.request.get(Defines.URLQUERY_SORTBY, sort)
        
        if not str(topic).isdigit() or not str(page).isdigit():
            topic = Defines.PresentTopic.ALL
            page = 0
            if settings_sub.IS_LOCAL:
                raise CabaretError(u'引数が想定外です', CabaretError.Code.ILLEGAL_ARGS)
        else:
            topic = int(topic)
            page = int(page)
        
        self.putPresentList(UrlMaker.present(), topic, page, sort)
        
        if not self.response.isEnd:
            self.writeAppHtml('present')
Ejemplo n.º 5
0
    def writeEvolutionHtml(self, name):
        """HTML書き出し.
        """
        v_player = self.getViewerPlayer()

        _ctype = self.getCtypeOri()
        sortby = self.getSortby()
        page = self.getPage()

        self.html_param[Defines.URLQUERY_CTYPE] = _ctype
        self.html_param[Defines.URLQUERY_SORTBY] = sortby
        self.html_param[Defines.URLQUERY_PAGE] = page

        ctype_items = {'all': u'全て'}
        ctype_items.update(Defines.CharacterType.NAMES)
        self.html_param['ctype_items'] = ctype_items.items()
        self.html_param['sort_items'] = Defines.CardSortType.NAMES.items()

        client = OSAUtil.get_cache_client()
        namespacebase = self.getCacheNameSpaceBase()
        client.set(v_player.id, _ctype, namespace=namespacebase % 'ctype')
        client.set(v_player.id, sortby, namespace=namespacebase % 'sortby')
        client.set(v_player.id, page, namespace=namespacebase % 'page')

        self.writeAppHtml(name)
Ejemplo n.º 6
0
 def procResult(self):
     """結果表示.
     """
     presentidlist = self.__get_present_idlist(True)
     over = False
     try:
         over = bool(int(self.__args.get(1, 0)))
     except:
         pass
     
     model_mgr = self.getModelMgr()
     
     presentlist = BackendApi.get_presents(presentidlist, model_mgr, using=settings.DB_READONLY, received=True)
     self.html_param['presentreceivedlist'] = [Objects.present(self, presentset) for presentset in presentlist]
     
     self.html_param['overlimit'] = over
     
     url_reload = self.addIDQuesyParam(UrlMaker.presentresult(over), presentidlist)
     
     topic = self.request.get(Defines.URLQUERY_CTYPE) or ""
     topic = int(topic) if str(topic).isdigit() else Defines.PresentTopic.ALL
     url_reload = OSAUtil.addQuery(url_reload, Defines.URLQUERY_CTYPE, topic)
     
     client = OSAUtil.get_cache_client()
     v_player = self.getViewerPlayer()
     sort = client.get(v_player.id, namespace='present:sort')
     
     self.putPresentList(url_reload, topic, sort=sort, using=settings.DB_DEFAULT)
     
     if not self.response.isEnd:
         self.writeAppHtml('presentrecieve')
Ejemplo n.º 7
0
 def process(self):
     
     v_player = self.getViewerPlayer()
     
     client = OSAUtil.get_cache_client()
     
     ctype = Defines.CharacterType.ALL
     rare = Defines.Rarity.ALL
     page = 0
     if self.request.method == 'GET':
         namespacebase = 'albumlistargs:%s'
         ctype = client.get(v_player.id, namespace=namespacebase % 'ctype') or ctype
         rare = client.get(v_player.id, namespace=namespacebase % 'rare') or rare
         page = client.get(v_player.id, namespace=namespacebase % 'page') or page
     
     try:
         ctype = int(self.request.get(Defines.URLQUERY_CTYPE, ctype))
         rare = int(self.request.get(Defines.URLQUERY_RARE, rare))
         page = int(self.request.get(Defines.URLQUERY_PAGE, page))
     except:
         ctype = Defines.CharacterType.ALL
         rare = Defines.Rarity.ALL
         page = 0
     
     model_mgr = self.getModelMgr()
     
     # プレイヤー情報.
     v_player = self.getViewerPlayer()
     
     # アルバム情報取得.
     offset = page * Defines.ALBUM_PAGE_CONTENT_NUM
     limit = Defines.ALBUM_PAGE_CONTENT_NUM + 1
     albumlist = BackendApi.get_album_list(self, v_player.id, ctype, rare, offset, limit, using=settings.DB_READONLY)
     has_nextpage = Defines.ALBUM_PAGE_CONTENT_NUM < len(albumlist)
     albumlist = albumlist[:Defines.ALBUM_PAGE_CONTENT_NUM]
     
     # アルバムリスト.
     self.html_param['album_list'] = albumlist
     self.html_param['cur_page'] = page + 1
     self.html_param['page_max'] = self.getAlbumPageNumMax(model_mgr, ctype, rare)
     
     self.html_param['ctype'] = ctype
     self.html_param['rare'] = rare
     
     url_base = UrlMaker.album()
     self.html_param['url_post'] = self.makeAppLinkUrl(url_base)
     
     url_base = OSAUtil.addQuery(url_base, Defines.URLQUERY_CTYPE, ctype)
     url_base = OSAUtil.addQuery(url_base, Defines.URLQUERY_RARE, rare)
     if 0 < page:
         self.html_param['url_page_prev'] = self.makeAppLinkUrl(OSAUtil.addQuery(url_base, Defines.URLQUERY_PAGE, page-1))
     if has_nextpage:
         self.html_param['url_page_next'] = self.makeAppLinkUrl(OSAUtil.addQuery(url_base, Defines.URLQUERY_PAGE, page+1))
     
     namespacebase = 'albumlistargs:%s'
     client.set(v_player.id, ctype, namespace=namespacebase % 'ctype')
     client.set(v_player.id, rare, namespace=namespacebase % 'rare')
     client.set(v_player.id, page, namespace=namespacebase % 'page')
     
     self.writeAppHtml('album/album')
Ejemplo n.º 8
0
 def __get_models_from_cache_default(self, model_cls, p_keys, using):
     """キャッシュから取得(デフォルト).
     """
     if using == settings.DB_READONLY and model_cls.__name__ != 'PlayerRequest':
         client = OSAUtil.get_cache_client()
         namespace = model_cls.__name__
         return client.mget(p_keys, namespace)
     else:
         return {}
Ejemplo n.º 9
0
 def getEditCacheVersion():
     """マスターデータを編集した時のバージョンキー.
     マスターデータを編集したらインクリメントする.
     init_gameで差分データを渡すときに新しくならないので...
     """
     client = OSAUtil.get_cache_client()
     version = client.get(MasterData.__makeEditVersionKey())
     if version is None:
         return 0
     return int(version)
Ejemplo n.º 10
0
    def process(self):

        model_mgr = self.getModelMgr()
        appconfig = BackendApi.get_appconfig(model_mgr,
                                             using=settings.DB_READONLY)
        if appconfig.is_maintenance():
            # メンテ中はチェックしない.
            self.send(200)
            return

        if settings_sub.IS_DEV:
            VIEWER_ID = "8350420"
        else:
            VIEWER_ID = "10814964"

        def callback(ret_data, reqkey, dmmid, result):
            try:
                person = ret_data[reqkey].get()
                if type(person) in (list, tuple):
                    person = person[0]
                result[dmmid] = person
            except:
                pass

        request = self.osa_util.makeApiRequest(
            ApiNames.People, PeopleRequestData.createForPeople(VIEWER_ID))
        reqkey = 'check_dmmapi:%s' % VIEWER_ID
        self.addAppApiRequest(reqkey, request)

        client = OSAUtil.get_cache_client()
        error_cnt = int(client.get("check_dmmapi:error") or 0)

        ret_data = self.execute_api()
        success = False
        try:
            ret_data[reqkey].get()
            success = True
        except Exception:
            error_cnt += 1
            if 5 < error_cnt:
                if (error_cnt - 5) % 10 == 1:
                    message = u"""[To:1984418] 藤竿 高志(Takashi FUJISAO)さん\n[To:1980432] 山田 健太(YAMADA Kenta)さん\n[To:1973173] 川合 佑輔(Yusuke Kawai)さん\n[To:2004847] 酒井 崇(Takashi SAKAI)さん\n[To:1973150] 秋谷 亮(RYO Akitani)さん\nΩ\ζ°)チーン<DMMのAPIサーバが死にました…\n上様ご乱心です"""
                    self.sendmessage_to_chatwork(message)
                self.send(500)
                return
        if success:
            if 0 < error_cnt:
                message = u"""DMMのAPIサーバが生き返ったよ!!"""
                self.sendmessage_to_chatwork(message)
            error_cnt = 0
        client.set("check_dmmapi:error", error_cnt)
        self.send(200)
Ejemplo n.º 11
0
    def saveSortParams(self):
        v_player = self.getViewerPlayer()
        uid = v_player.id

        _ctype = self.getCtypeOri()
        sortby = self.getSortby()
        ckind_type = self.getCKindType()
        maxrare = self.getMaxRare()

        client = OSAUtil.get_cache_client()
        namespacebase = self.getCacheNameSpaceBase()
        client.set(uid, _ctype, namespace=namespacebase % 'ctype')
        client.set(uid, sortby, namespace=namespacebase % 'sortby')
        client.set(uid, ckind_type, namespace=namespacebase % 'ckind_type')
        client.set(uid, maxrare, namespace=namespacebase % 'maxrare')
Ejemplo n.º 12
0
    def initCache():
        client = OSAUtil.get_cache_client()

        host = socket.gethostname()
        pid = os.getpid()
        localcache_host = '%s:%s' % (host, pid)
        key = localcache.CHECKED_HOST_LIST_KEY
        host_list = client.get(key)
        do_write_cache = False

        if host_list is None:
            host_list = []
            do_write_cache = True
        if localcache_host not in host_list:
            localcache._resetCacheData()
            host_list.append(localcache_host)
            do_write_cache = True

        if do_write_cache:
            client.set(key, host_list)
Ejemplo n.º 13
0
    def process(self):

        v_player = self.getViewerPlayer()

        # セッションを切っておく.
        client = OSAUtil.get_cache_client()
        client.delete(self.osa_util.viewer_id, namespace='session')
        client.delete('payment_checked:%s' % v_player.id)

        paymentId = self.request.get('paymentId')

        if not settings_sub.IS_LOCAL:
            if not paymentId:
                raise "paymentId is None"
            # APIで課金情報を取得.
            data = PaymentGetRequestData()
            data.paymentId = paymentId
            data.guid = self.osa_util.viewer_id

            request = self.osa_util.makeApiRequest(ApiNames.PaymentGet, data)
            self.addAppApiRequest('payment_check', request)
            ret_data = self.execute_api()
            paymentdata = ret_data['payment_check'].get()
            if paymentdata.status != PaymentData.Status.START:
                raise "Illegal status"

        model_mgr, entry = db_util.run_in_transaction(Handler.tr_update_entry,
                                                      v_player.id, paymentId)
        model_mgr.write_end()

        if settings_sub.IS_LOCAL:
            self.set_masterid(entry.iid)
            url = UrlMaker.gachaanim(entry.iid, v_player.req_confirmkey)
            url = OSAUtil.addQuery(url, 'paymentId', paymentId)
            url = OSAUtil.addQuery(url, Defines.URLQUERY_STATE,
                                   PaymentData.Status.COMPLETED)
            self.response.set_status(200)
            self.appRedirect(self.makeAppLinkUrl(url, add_frompage=False))
        else:
            self.response.set_status(200)
            self.response.end()
Ejemplo n.º 14
0
    def getLastUpdateVersion(model_mgr=None):
        # 現時点で最後に更新した時間の数値を返す.
        memcache_key = 'getLastUpdateVersion:%s' % MasterData.getEditCacheVersion(
        )
        client = OSAUtil.get_cache_client()
        last_update_version = client.get(memcache_key)

        model_mgr = model_mgr or ModelRequestMgr()

        if last_update_version is None:
            update_time = OSAUtil.get_datetime_min()
            last_update = update_time
            for kls in [MasterData.CLASSES[i] for i in MasterData.USE_CLIENT]:
                for obj in model_mgr.get_mastermodel_all(kls,
                                                         fetch_deleted=True):
                    edit_time = getattr(obj, Defines.MASTER_EDITTIME_COLUMN)
                    if MasterData.is_update(last_update, edit_time):
                        if last_update < edit_time:
                            last_update = edit_time
            last_update_version = MasterData.toMasterVersion(last_update)
            client.set(memcache_key, last_update_version)
        return last_update_version
Ejemplo n.º 15
0
            apitest.finish()
        except:
            info = sys.exc_info()

            t = str(info[0]).replace('<', '').replace('>', '')
            ex = '%s:%s' % (t, info[1])
            t_list = traceback.extract_tb(info[2])
            trace = ['%s:%s\r\n- %s' % (t[0], t[1], t[2]) for t in t_list]
            trace.append(ex)
            logger.error('\r\n'.join(trace))
            result = False
        finally:
            if apitest:
                apitest._remove_dummy_all()  # 作ったダミーを削除.
            OSAUtil.get_cache_client().flush()  # キャッシュを消しておく.
        return result

    def check(self):
        print 'override me!'

    def finish(self):
        # チェック後にやりたいこと.
        pass

    def create_dummy(self, dummy_type, *args, **kwgs):
        # ダミーデータ作る.
        return self.__df.create_dummy(dummy_type, *args, **kwgs)

    def _remove_dummy_all(self):
        # ダミーデータ消す.
Ejemplo n.º 16
0
    def loadSortParams(self,
                       default_ctype='all',
                       default_sortby=Defines.CardSortType.CTIME_REV,
                       default_ckind_type=None,
                       default_maxrare=None,
                       default_skillid=None):
        v_player = self.getViewerPlayer()
        uid = v_player.id

        client = OSAUtil.get_cache_client()

        ctype = default_ctype
        sortby = default_sortby
        page = 0
        ckind_type = default_ckind_type or Defines.CardKind.ListFilterType.CAST_ONLY
        maxrare = default_maxrare if default_maxrare is not None else Defines.Rarity.HIGH_NORMAL

        if self.request.method == 'GET':
            namespacebase = self.getCacheNameSpaceBase()
            ctype = client.get(uid, namespace=namespacebase % 'ctype') or ctype
            sortby = client.get(uid,
                                namespace=namespacebase % 'sortby') or sortby
            ckind_type = client.get(
                uid, namespace=namespacebase % 'ckind_type') or ckind_type
            maxrare = client.get(
                uid, namespace=namespacebase % 'maxrare') or maxrare

        _ctype = self.request.get(Defines.URLQUERY_CTYPE, ctype)
        sortby = self.request.get(Defines.URLQUERY_SORTBY, sortby)
        page = self.request.get(Defines.URLQUERY_PAGE, page)
        ckind_type = self.request.get(Defines.URLQUERY_CKIND, ckind_type)
        maxrare = self.request.get(Defines.URLQUERY_RARE, maxrare)
        skillid = self.request.get(Defines.URLQUERY_SKILL, None)

        ctype = _ctype
        if _ctype in ('all', str(Defines.CharacterType.ALL)):
            ctype = None
        elif str(_ctype).isdigit():
            _ctype = int(_ctype)

        if str(ckind_type).isdigit():
            ckind_type = int(ckind_type)
        else:
            ckind_type = Defines.CardKind.ListFilterType.CAST_ONLY

        if str(maxrare).isdigit():
            maxrare = int(maxrare)
        else:
            maxrare = Defines.Rarity.HIGH_NORMAL

        if str(skillid).isdigit():
            skillid = int(skillid)
        else:
            skillid = None

        if (ctype is not None
                and not str(ctype).isdigit()) or not str(page).isdigit(
                ) or not Defines.CardSortType.NAMES.has_key(sortby):
            raise CabaretError(u'引数が想定外です', CabaretError.Code.ILLEGAL_ARGS)

        if ctype:
            ctype = int(ctype)
        if page:
            page = int(page)

        self.__ctype_ori = _ctype
        self.__ctype = ctype
        self.__sortby = sortby
        self.__page = page
        self.__ckind_type = ckind_type
        self.__maxrare = maxrare
        self.__skillid = skillid
Ejemplo n.º 17
0
 def flush(self):
     localcache._resetCacheData()
     key = localcache.CHECKED_HOST_LIST_KEY
     client = OSAUtil.get_cache_client()
     client.delete(key)
Ejemplo n.º 18
0
 def __save_models_to_cache_for_none(self, model_cls, key, ttl=None):
     """キャッシュに保存(NoneType用).
     """
     client = OSAUtil.get_cache_client()
     namespace = model_cls.__name__
     client.set(key, 'None', namespace=namespace)
Ejemplo n.º 19
0
 def __delete_models_to_cache_default(self, model_cls, keys):
     """キャッシュから削除(デフォルト).
     """
     client = OSAUtil.get_cache_client()
     namespace = model_cls.__name__
     client.mdelete(keys, namespace)
Ejemplo n.º 20
0
    def putPresentList(self, url_reload, topic, page=0, sort="desc", using=settings.DB_READONLY):
        """プレゼントリストをHTMLに埋め込む.
        """
        model_mgr = self.getModelMgr()
        
        # 絞り込みの引数.
        v_player = self.getViewerPlayer()
        
        overlimit = v_player.cardlimit <= BackendApi.get_cardnum(v_player.id, model_mgr, using=settings.DB_READONLY)
        
        # プレゼントを取得.
        offset = page * Defines.PRESENT_PAGE_CONTENT_NUM
        limit = Defines.PRESENT_PAGE_CONTENT_NUM + 1
        presentidlist = BackendApi.get_present_idlist(v_player.id, topic, offset, limit, model_mgr, using=using, desc=sort=="desc")
        has_next_page = len(presentidlist) == limit
        presentidlist = presentidlist[:Defines.PRESENT_PAGE_CONTENT_NUM]
        presentlist = BackendApi.get_presents(presentidlist, model_mgr, using=using)
        if presentlist is None:
            # うまく取れなかった.リダイレクトさせておくか.
            BackendApi._save_presentidlist(v_player.id, model_mgr, topic, using=using)
            url = url_reload
            url = OSAUtil.addQuery(url, Defines.URLQUERY_CTYPE, topic)
            url = OSAUtil.addQuery(url, Defines.URLQUERY_PAGE, page)
            self.appRedirect(self.makeAppLinkUrlRedirect(url))
            return
        
        self.html_param['presentlist'] = [Objects.present(self, presentset, overlimit, cur_topic=topic) for presentset in presentlist]
        
        # 絞り込み用のURL.
        url_base = OSAUtil.addQuery(UrlMaker.present(), Defines.URLQUERY_SORTBY, sort)
        self.html_param['url_all'] = self.makeAppLinkUrl(OSAUtil.addQuery(url_base, Defines.URLQUERY_CTYPE, Defines.PresentTopic.ALL))
        self.html_param['url_card'] = self.makeAppLinkUrl(OSAUtil.addQuery(url_base, Defines.URLQUERY_CTYPE, Defines.PresentTopic.CARD))
        self.html_param['url_item'] = self.makeAppLinkUrl(OSAUtil.addQuery(url_base, Defines.URLQUERY_CTYPE, Defines.PresentTopic.ITEM))
        self.html_param['url_etc'] = self.makeAppLinkUrl(OSAUtil.addQuery(url_base, Defines.URLQUERY_CTYPE, Defines.PresentTopic.ETC))
        
        # ソート切り替え.
        url_base = OSAUtil.addQuery(UrlMaker.present(), Defines.URLQUERY_CTYPE, topic)
        self.html_param['url_desc'] = self.makeAppLinkUrl(OSAUtil.addQuery(url_base, Defines.URLQUERY_SORTBY, "desc"))
        self.html_param['url_asc'] = self.makeAppLinkUrl(OSAUtil.addQuery(url_base, Defines.URLQUERY_SORTBY, "asc"))
        self.html_param['cur_sort'] = "desc" if sort == "desc" else "asc"
        
        # ページ切り替えURL.
        url_base = OSAUtil.addQuery(url_base, Defines.URLQUERY_SORTBY, sort)
        if 0 < page:
            self.html_param['url_prev'] = self.makeAppLinkUrl(OSAUtil.addQuery(url_base, Defines.URLQUERY_PAGE, page - 1))
        if has_next_page:
            self.html_param['url_next'] = self.makeAppLinkUrl(OSAUtil.addQuery(url_base, Defines.URLQUERY_PAGE, page + 1))
        
        # まとめて受け取るUrl.
        url = UrlMaker.presentdo()
        url = OSAUtil.addQuery(url, Defines.URLQUERY_CTYPE, topic)
        url = OSAUtil.addQuery(url, Defines.URLQUERY_SORTBY, sort)
        self.html_param['url_receive_all'] = self.makeAppLinkUrl(self.addIDQuesyParam(url, presentidlist))
        
        # チェックボックスのキー.
        self.html_param['key_except_card'] = Defines.URLQUERY_CHECK_CARD
        self.html_param['key_except_gold'] = Defines.URLQUERY_CHECK_GOLD
        
        self.html_param['cur_topic'] = topic
        
        client = OSAUtil.get_cache_client()
#        client.set(v_player.id, topic, namespace='presentbox:topic')
        client.set(v_player.id, sort, namespace='present:sort')
Ejemplo n.º 21
0
 def incrementEditCacheVersion():
     client = OSAUtil.get_cache_client()
     client.set(MasterData.__makeEditVersionKey(),
                MasterData.getEditCacheVersion() + 1)
     # マスターデータもリロード..
     rediscache.flush_all()
Ejemplo n.º 22
0
 def __save_models_to_cache_default(self, modeldict, namespace, ttl):
     """キャッシュに保存(デフォルト).
     """
     client = OSAUtil.get_cache_client()
     client.mset(modeldict, time=ttl, namespace=namespace)
Ejemplo n.º 23
0
    def handle(self, *args, **options):

        print '================================'
        print 'battleevent_teaseropen'
        print '================================'

        now = OSAUtil.get_now()

        model_mgr = ModelRequestMgr()
        # メンテナンス確認.
        appconfig = BackendApi.get_appconfig(model_mgr)
        if not appconfig.is_maintenance():
            print u'メンテナンスモードにしてください'
            return
        print 'check maintenance...OK'

        config = BackendApi.get_current_battleeventconfig(model_mgr)
        if config.mid == 0:
            print 'Event is not set.'
            return
        elif config.starttime <= now:
            print 'Event has already beguns.'
            return
        eventmaster = BackendApi.get_battleevent_master(
            model_mgr, config.mid, using=settings.DB_READONLY)
        if eventmaster is None:
            print 'Event is not found.'
            return
        print 'check eventmaster...OK'

        rankmaster_dict = dict([
            (master.rank, master)
            for master in BattleEventRankMaster.fetchValues(
                filters={'eventid': config.mid},
                fetch_deleted=True,
                using=settings.DB_READONLY)
        ])
        eventrankmaster = rankmaster_dict.get(eventmaster.rankstart)
        if eventrankmaster is None:
            print 'BattleEventMaster.rankstart is not set.'
            return
        print 'check eventrankmaster...OK'

        print '================================'
        print 'delete battleeventdata.'
        # Redisのバトルイベント関係を削除.
        RedisBattleEvent.getDB().flushdb()
        print 'delete...redis'

        BattleEventRanking.getDB().delete(
            BattleEventRanking.makeKey(eventmaster.id))
        BattleEventRanking.getDB().delete(
            BattleEventRankingBeginer.makeKey(eventmaster.id))
        print 'delete...ranking'

        tmp_time = config.starttime
        while tmp_time < config.endtime:
            keys = [
                BattleEventDailyRanking.makeKey(
                    BattleEventDailyRanking.makeRankingId(
                        tmp_time, eventmaster.id, rankmaster.rank))
                for rankmaster in rankmaster_dict.values()
            ]
            BattleEventDailyRanking.getDB().delete(*keys)
            tmp_time += datetime.timedelta(days=1)
        print 'delete...daily_ranking'

        delete_target_model_cls_list = (
            BattleEventFlags,
            BattleEventRank,
            BattleEventScore,
            BattleEventGroup,
            BattleEventGroupLog,
            BattleEventRevenge,
            BattleEventBattleLog,
            BattleEventGroupRankingPrize,
            BattleEventScorePerRank,
            BattleEventPresentData,
            BattleEventPresentCounts,
            UserLogBattleEventPresent,
        )

        def tr():
            for model_cls in delete_target_model_cls_list:
                tablename = model_cls.get_tablename()
                query_string = "truncate table `%s`;" % tablename
                Query.execute_update(query_string, [], False)
                print 'delete...%s' % tablename

        db_util.run_in_transaction(tr)

        OSAUtil.get_cache_client().flush()