def process(self): args = self.getUrlArgs('/promotionconditionget/') try: appname = args.get(0, '') requirement_idlist = [ int(s) for s in args.get(1, '').split(',') if s.isdigit() ] except: self.__sendErrorResponse(404) return model_mgr = self.getModelMgr() config = BackendApi.get_promotionconfig(model_mgr, appname, using=settings.DB_READONLY) if config is None: # アプリが存在しない. self.__sendErrorResponse(404) return if requirement_idlist: requirementlist = BackendApi.get_promotionrequirementmaster_list( model_mgr, appname, requirement_idlist, using=settings.DB_READONLY) else: # 全て検索. requirementlist = BackendApi.get_promotionrequirementmaster_all( model_mgr, appname, using=settings.DB_READONLY) json_obj = {} for requirement in requirementlist: text = requirement.text json_obj[str(requirement.id)] = text json_data = StrUtil.to_s(Json.encode(json_obj, ensure_ascii=False)) self.response.set_status(200) self.osa_util.write_json_data(json_data)
def process(self): args = self.getUrlArgs('/greet_complete/') oid = args.get(0, None) errcode = args.get(1, None) point_pre = args.get(2, None) point_post = args.get(3, None) logid = args.get(4, None) if not (str(oid).isdigit() and str(errcode).isdigit() and str(point_pre).isdigit() and str(point_post).isdigit()): raise CabaretError(u'不正なアクセスです', CabaretError.Code.ILLEGAL_ARGS) oid = int(args.get(0, None)) errcode = int(args.get(1, None)) point_pre = int(args.get(2, None)) point_post = int(args.get(3, None)) if logid: logid = int(logid) o_player = BackendApi.get_players(self, [oid], [], using=settings.DB_READONLY) if o_player: o_player = o_player[0] else: raise CabaretError(u'不正なアクセスです', CabaretError.Code.ILLEGAL_ARGS) if not logid: url = UrlMaker.profile(o_player.id) url = self.makeAppLinkUrlRedirect(url) self.appRedirect(url) return persons = BackendApi.get_dmmplayers(self, [o_player], using=settings.DB_READONLY) self.html_param['person'] = Objects.person(self, o_player, persons.get(o_player.dmmid)) is_overlimit = False is_duplicate = False if errcode == CabaretError.Code.OK: pass elif errcode == CabaretError.Code.ALREADY_RECEIVED: is_duplicate = True elif errcode == CabaretError.Code.OVER_LIMIT: is_overlimit = True self.html_param['is_duplicate'] = is_duplicate self.html_param['is_overlimit'] = is_overlimit self.html_param['gacha_pt_pre'] = point_pre self.html_param['gacha_pt_post'] = point_post self.html_param['gacha_pt_add'] = point_post - point_pre url = UrlMaker.profile(oid) self.html_param['url_profile'] = self.makeAppLinkUrl(url) url = UrlMaker.greet_complete(o_player.id, errcode, point_pre, point_post, logid) self.html_param['url_self'] = self.makeAppLinkUrl(url) errtext = False comment = u'' if self.request.method == 'POST': comment = self.request.get(self.KEY_GREET_COMMENT) if comment == u'': errtext = True # コメントのバイト数で比較 if StrUtil.getByteLength(comment) > ( Defines.GREET_COMMENT_TEXT_MAX * 2): errtext = True if not errtext and self.is_pc: # JS API経由でtextidを取得済み textid = self.request.get(self.KEY_GREET_TEXTID) elif not errtext: data = InspectionPostRequestData() data.data = comment request = self.osa_util.makeApiRequest(ApiNames.InspectionPost, data) self.addAppApiRequest('inspection_start', request) ret_data = self.execute_api() result = ret_data['inspection_start'].get() if isinstance(result, InspectionData): textid = result.textId else: if not settings_sub.IS_LOCAL: errtext = True else: textid = '0000' if not errtext: v_player = self.getViewerPlayer() point_pre = v_player.gachapt point_post = v_player.gachapt model_mgr = self.getModelMgr() is_friend = BackendApi.check_friend(v_player.id, o_player.id, model_mgr, using=settings.DB_READONLY) try: model_mgr = db_util.run_in_transaction( Handler.tr_write, v_player.id, o_player.id, is_friend, logid, textid) model_mgr.write_end() playergachapt = model_mgr.get_wrote_model( PlayerGachaPt, v_player.id) if playergachapt: point_post = playergachapt.gachapt except CabaretError, e: if e.code in (CabaretError.Code.NOT_DATA): url = UrlMaker.greet(o_player.id) url = self.makeAppLinkUrlRedirect(url) self.appRedirect(url) return else: raise errcode = 0 if point_pre >= point_post: errcode = CabaretError.Code.ALREADY_RECEIVED url = UrlMaker.greet_comment_comp(o_player.id, errcode, point_pre, point_post) url = self.makeAppLinkUrlRedirect(url) self.appRedirect(url) return
def handle(self, *args, **options): print '================================' print 'copy_img' print '================================' out = args[0] # ガチャのマスターを取得. gachalist = GachaMaster.fetchValues(filters={ 'consumetype__in': Defines.GachaConsumeType.PAYMENT_TYPES, 'schedule__gt': 0 }, using=backup_db) # ガチャのボックスデータを作成. read_boxids = [] card_dict = {} for gacha in gachalist: if gacha.boxid in read_boxids: continue schedule = ScheduleMaster.getByKey(gacha.schedule, using=backup_db) name = u'%s(%s-%s)' % (gacha.name, schedule.stime.strftime('%m/%d'), schedule.stime.strftime('%m/%d')) boxmaster = GachaBoxMaster.getByKey(gacha.boxid, using=backup_db) gachamasterset = GachaMasterSet(gacha, boxmaster, schedule) gachabox = GachaBox(gachamasterset, GachaPlayData.makeInstance( GachaPlayData.makeID(0, gacha.boxid)), blank=True) grouplist = GachaGroupMaster.getByKey(gachabox.get_group_id_list(), using=backup_db) # カードIDとガチャのIDをひもづける. for group in grouplist: if 1 < len(group.table): continue cardid = group.table[0]['id'] arr = card_dict[cardid] = card_dict.get(cardid) or [] arr.append(name) # カードマスターを取得. cardmasterlist = CardMaster.getByKey(card_dict.keys(), order_by='id', using=backup_db) # CSVを作成. rows = [] def makeRow(row): arr = [] for v in row: s = u'%s' % v s = s.replace('"', '""') arr.append(u'"%s"' % s) return u','.join(arr) for cardmaster in cardmasterlist: cardsortmaster = CardSortMaster.getByKey(cardmaster.id, using=backup_db) row = [ cardmaster.id, cardmaster.name, Defines.Rarity.NAMES[cardsortmaster.rare], Defines.CharacterType.NAMES[cardsortmaster.ctype] ] row.extend(card_dict[cardmaster.id]) str_row = makeRow(row) print str_row rows.append(str_row) csv_data = StrUtil.to_s(u'\n'.join(rows), dest_enc='shift-jis') f = None try: f = open(out, "w") f.write(csv_data) f.close() except: if f: f.close() f = None raise print '================================' print 'output:%s' % out print 'all done..'
def __getResponseApi(self, funcMakeRequest): ope_url = self.get_url() post_data = self.get_postdata() queryparams = self.get_queryparams() http_method = self.get_http_method() if type(post_data) == unicode: post_data = StrUtil.to_s(post_data, 'utf-8') self.osa_util.logger.trace('ope_url:' + ope_url) request = funcMakeRequest(queryparams) headers = request.to_header() xoauth_requestor_id = queryparams.get('xoauth_requestor_id') if xoauth_requestor_id: headers['Authorization'] = '%s, xoauth_requestor_id="%s"' % ( headers['Authorization'], xoauth_requestor_id) # del queryparams['xoauth_requestor_id'] headers['Content-Type'] = self.get_content_type() # Query the user's personal info and print them if queryparams: uri = '%s?%s' % (request.get_normalized_http_url(), urllib.urlencode(queryparams)) else: uri = request.get_normalized_http_url() body = self.get_body() logs = [ "HTTP Method:%s" % http_method, "API_URI:%s" % uri, ] logs.append('request headers:') logs.extend(['\t%s: %s' % (k, v) for k, v in headers.items()]) logs.append('request body:') logs.append(body) log = '\n'.join(logs) self.osa_util.logger.trace(log) if self._is_batch_mode: timeout = None else: timeout = 3 tmp = None try: tmp = self.osa_util.httpopen(uri, body, http_method, headers, self.get_certificate(), timeout=timeout) response = tmp.read() self.osa_util.logger.info('getResponseApi response:%s' % response) return response except urllib2.HTTPError, er: if tmp is not None and tmp.fp: tmp.fp._sock.recv = None if self.osa_util.is_dbg: if er.fp is None: error_message = str(er) else: error_message = er.read() self.osa_util.logger.error(self.osa_util.logger.to_string()) self.osa_util.logger.error('getResponseApi er_code:%s %s' % (er.code, error_message)) if er.code == 401: info = str(er) now = OSAUtil.get_now(timezone.TZ_DEFAULT) delta = self.osa_util.getElpsedTime() str_body = None try: str_body = '%s' % post_data except: self.osa_util.logger.error( 'str_body can not translate... %s' % ErrorUtil.getLastErrorMessage()) pass er_response = '' if er.fp is not None: er_response = er.read() temp_log = ('getResponseApi log:%s' % log + 'now:%s\n' % now + 'elapsed time: %d.%06d sec.\n' % (delta.seconds, delta.microseconds) + 'body:%s' % str_body + 'er info:%s\n' % info + 'er read:%s\n' % er_response + 'error:%s\n' % er) self.osa_util.logger.warning(temp_log) return self.processHttpError(er)
def __proc_load_csv(self): if self.request.method == 'POST': fixture = None tmp_data = None if settings_sub.IS_LOCAL: # ローカルだとアップできないので.. f = None try: f = open(self.__local_datafileurl, 'r') tmp_data = f.read() except IOError: tmp_data = None finally: if f: f.close() else: request_files = self.request.files form = UploadFileForm(self.request.body, request_files) if form.is_valid(): req_file = request_files['data_file'] csv_name = self.__get_csv_name() if req_file.name != csv_name: url = self.makeModelEditLinkUrl() url = self.setAlert( url, u'ファイル名が不正です.正しいファイル名は%sです.' % csv_name, AlertCode.ERROR) self.redirect(url) return tmp_data = req_file.read() if tmp_data: src_enc = StrUtil.guess_charset(tmp_data) fixture = io.StringIO(StrUtil.to_u(tmp_data, src_enc), newline=None) sheet_columns = AdminModelEditHandler.__make_sheet_columns( self.model_form_cls) pkey_name = self.model_cls.get_primarykey_column() sheet_pkey_name = pkey_name.replace('_', '') model_all = self.model_cls.fetchValues(using=settings.DB_DEFAULT) model_dict = {} for model in model_all: model_dict[model.key()] = model save_models = [] if fixture: cnt = 0 indexes = {} for row in csv.reader(fixture): if cnt == 0: # ここはカラム名. index = 0 for column_name in row: indexes[column_name] = index index += 1 else: # ここは値. pkey = row[indexes.get(sheet_pkey_name, 0)] model = model_dict.get( pkey, self.model_cls(**{pkey_name: pkey})) field_dict = dict([ (field.attname, field) for field in self.model_cls.get_fields() ]) for column in self.get_formfields(): sheet_column = column.replace('_', '') if not sheet_column in sheet_columns: continue field = field_dict.get( column ) or self.model_form_cls.declared_fields.get( column) index = indexes.get(sheet_column, None) if index is not None: str_v = row[index] try: v = self.str_to_fieldvalue(field, str_v) except Exception, e: raise CabaretError( '[field=%s,value=%s,row=%s,data=%s]%s:%s' % (column, str_v, cnt, row, e.__class__.__name__, e)) else: # modelにはあるが実際のシートに無い場合. v = getattr(model, column, None) if v is None: raise CabaretError( u'dataError:[field=%s,pkey=%s,data=%s]' % (column, pkey, row)) if hasattr(model, 'set_%s' % column): getattr(model, 'set_%s' % column)(v) else: setattr(model, column, v) save_models.append(model) cnt += 1 url = self.__write_instances(save_models) if not url: url = self.makeModelEditLinkUrl() url = self.setAlert(url, u'データがありません', AlertCode.ERROR) self.redirect(url)