def register_xm_account(user_id): identity = Identity.get(user_id) local_account = Account.get(user_id) xm_account = XMAccount.get_by_local(user_id) if not local_account.mobile: raise MissingMobilePhoneError if not identity: raise MissingIdentityError if xm_account: return xm_account try: response = xinmi.create_account(user_id=user_id, person_name=identity.person_name, person_ricn=identity.person_ricn, mobile=local_account.mobile) except BusinessError as e: raise MismatchUserError(u'%s,如有问题,请联系客服' % e) else: if not response.is_new: if not current_app.debug: rsyslog.send( u'您的身份信息(%s,%s,%s,%s) 已经被注册过,如有问题,请联系客服' % (user_id, identity.person_ricn, identity.person_name, local_account.mobile), 'xm_dup_register') return XMAccount.bind(user_id, response.user_id)
def download(project_name, version=None): project = Project.get_by_name(project_name) or abort(404) releases = project.list_releases() # strips draft if not version: releases = ( r for r in releases if r.status is not Release.Status.draft) # strips inhouse if not check_is_inhouse(): releases = ( r for r in releases if r.status is not Release.Status.inhouse) # chooses version if version is None: release = max(releases, key=obtain_public_version) else: releases = ( r for r in releases if obtain_public_version(r) == parse_version(version)) release = first(releases, None) if not release: abort(404) if release.status is Release.Status.absent: abort(410) else: fs = make_filestore(project.bucket_name, BASE_URLS[project.bucket_name]) url = fs.get_url( release.file_path, is_private=True, expires=timedelta(minutes=30)) rsyslog.send(release.file_path, tag='download_release') return redirect(url)
def register_zhiwang_account(user_id): identity = Identity.get(user_id) local_account = Account.get(user_id) zhiwang_account = ZhiwangAccount.get_by_local(user_id) if not local_account.mobile: raise MissingMobilePhoneError if not identity: raise MissingIdentityError if zhiwang_account: return zhiwang_account try: response = zhiwang.user_create(user_id, identity.person_ricn, identity.person_name, local_account.mobile) except RemoteError as e: raise MismatchUserError(u'绑定账号失败: %s,如有问题,请联系客服' % e.args[1]) else: if not response.is_new: if not current_app.debug: rsyslog.send( u'您的身份信息(%s,%s,%s,%s) 已经被注册过,如有问题,请联系客服' % (user_id, identity.person_ricn, identity.person_name, local_account.mobile), 'zhiwang_dup_register') return ZhiwangAccount.bind(user_id, response.zw_user_code)
def get_income(self, from_day, to_day): ''' 以from_day对比to_day日收益情况 ''' funds = self.get_funds_m2m() income = 0 for fund in funds: # 基金成立日净值 create_time_data = Fundata.get_by_fund_day(fund.fund.code, datetime.date(from_day)) if not create_time_data: rsyslog.send('not found create_time fundata %s %s' % (fund.fund.code, from_day), tag='fund') return 0 # 当日净值 today_data = Fundata.get_by_fund_day(fund.fund.code, datetime.date(to_day)) if not today_data: rsyslog.send('not found today fundata %s %s' % (fund.fund.code, to_day), tag='fund') return 0 income += (today_data.net_worth / create_time_data.net_worth - 1) * Decimal(fund.rate) return income
def log_request(request, response, module_name): """Record request log""" try: req_id = uuid4().hex req_remote_addr = request.remote_addr req_host = request.host req_url = request.path req_args = request.args.to_dict().__str__() body_args = request.form.to_dict() body_json = request.get_json() if body_json: body_args = dict(body_args, **request.get_json()) for k in body_args: if k in hidden_fields: body_args[k] = '***' req_body = body_args.__str__() req_head = request.headers.items().__str__() request_log_format = ( 'req_id={0}, req_remote_addr={1},, host={2}, url={3}, head={4},' 'args={5}, req_body={6}, resp_status={7}, resp_body={8}') response_body = response.data if response.status_code not in [ 200, 201 ] else '' response_body = str(response_body).replace('\n', '').replace(' ', '') log_content = request_log_format.format(req_id, req_remote_addr, req_host, req_url, req_head, req_args, req_body, response.status_code, response_body) rsyslog.send(log_content, tag=module_name) except Exception as e: rsyslog.send(str(e), tag='log_request') pass
def on_order_succeeded(sender): order = HoarderOrder.get(sender.id_) # 清除产品销售额缓存 HoarderOrder.clear_local_sold_amount_cache(order.product_id) # 确认优惠已被消费使用 # order.confirm_bonus() # 增加或更新银行卡信息 BankcardBinding.add_or_update(order.user_id, order.bankcard_id, order.product.vendor.id_) # 记录成功订单日志 rsyslog.send('\t'.join([ order.id_, order.product_id, order.user_id, order.creation_time.isoformat(), order.order_code, order.bankcard_id, str(round(order.amount, 2)) ]), tag='hoarder_order_succeeded') # 发送订单成功短信 send_order_success_sms(order) if order.product.kind is HoarderProduct.Kind.child: hoarder_order_use_gift_tracking.produce(order.id_)
def main(): tasks = [ hoarder_payment_tracking, hoarder_redeem_tracking, hoarder_asset_fetching ] for task in tasks: mq = task.get_broker() counter = Counter() while True: job = mq.peek_buried() if not job: break info = {'body': job.body, 'task': task} if counter[job.body] >= MAX_RETRY: log = 'Job of tube is deleted' rsyslog.send('%s: %r' % (log, info), tag='cron_hoarder_sync_kick_ruined') sentry.captureMessage(log, extra=info) job.delete() continue mq.kick() rsyslog.send('Kicking job %(body)s of tube %(task)s' % info, tag='cron_hoarder_sync_kick_history') counter[job.body] += 1
def create_account(self, sms_code): if self.need_to_create(): try: with WalletBankcardBinding.record_for_binding( self.bankcard, self.provider): zslib.create_account( transaction_id=self.make_transaction_id(), user_id=self.wallet_account.secret_id, bank_id=self.bankcard.bank.zslib_id, card_number=self.bankcard.card_number, person_name=self.identity.person_name, person_ricn=self.identity.person_ricn, mobile_phone=self.bankcard.mobile_phone, password=self.wallet_account.secret_token, sms_code=sms_code) except BusinessError as e: if e.kind is BusinessError.kinds.account_activated: self.wallet_account.transfer_status(self.statuses.success) rsyslog.send( 'account_activated %r' % self.wallet_account.id_, 'wallet_programming') else: self.wallet_account.transfer_status(self.statuses.failure) raise except: self.wallet_account.transfer_status(self.statuses.failure) raise else: self.wallet_account.transfer_status(self.statuses.success) return self.wallet_account
def send_gift_worker(str_user_gift): str_log = ('SendGitWorkerPid: {0}').format(os.getpid()) rsyslog.send(str_log, tag='send_gift_worker') user_id, gift_id = str_user_gift.split(':') gift_id = int(gift_id) UserLotteryRecord.add(user_id, gift_id) LotteryGiftMgr.send_gift(user_id, gift_id)
def main(): """Downloads the product data of sxb.""" with app.app_context(): rs = sxb.query_products(ProductType.ririying) products = [fillup_local(product_info) for product_info in rs] new_comer_products = [ fillup_local(product_info, is_child_product=True) for product_info in rs ] products.extend(new_comer_products) rsyslog.send(','.join([str(p.remote_id) for p in products]), tag='sxb_updating_products') # 短时策略:0点-10点产品默认下架售罄,10点开售新手标,10~11点普通产品仍为下架状态,11点后开售普通类产品 # 注意: 如果12点后依然没有产品,则12点后创建的产品将只能由运营人员手动上架 hour = datetime.now().hour for p in products: if hour < 10: p.go_off_sale() elif hour == 10: if p.kind is Product.Kind.child: if p.is_taken_down: p.go_on_sale() else: p.go_off_sale() else: if p.is_taken_down: p.go_on_sale()
def on_order_exited(sender): msg = '\t'.join([ sender.id_, sender.service_id, sender.user_id, sender.creation_time.isoformat(), str(round(sender.order_amount, 2)) ]) rsyslog.send(msg, tag='savings_exited')
def consulting(): if not g.user: if not session.get('uuid'): session['uuid'] = str(uuid.uuid4()) if not session.get('ins_plan_consulting_log'): rsyslog.send(session['uuid'] + '\t' + request.remote_addr, tag='ins_plan_consulting') session['ins_plan_consulting_log'] = 'logged' session_dict = {} if session.get('ins_plan'): session_dict = json.loads(session.get('ins_plan')) session_dict['is_login'] = False return render_template('ins/plan_consulting.html', plan=json.dumps(session_dict)) else: user_id = g.user.id plan_id = request.args.get('plan_id') if not plan_id and not Plan.get_user_plan_dict(user_id): return render_template('ins/plan_consulting.html', plan=session.get('ins_plan', '{}')) if plan_id and Plan.belong_to_user(plan_id, g.user.id): plan_dict = Plan.get(plan_id).data.data plan_json_str = session.get('login_ins_plan' + str(plan_id)) if plan_json_str: session_plan = json.loads(plan_json_str) plan_dict.update(session_plan) plan_dict['is_login'] = True plan_json = json.dumps(plan_dict) session['plan_id'] = plan_id return render_template('ins/plan_consulting.html', plan=plan_json) return redirect(url_for('ins.plan.index'))
def distribute_welfare_gift(user, welfare_package_kind, voucher=None, allow_piling_firewood=True): # voucher是获取礼包的凭证根据(如用户、订单、资产等),亦可无条件发放 from core.models.group import welfare_reminder_group from core.models.notification import Notification from core.models.notification.kind import welfare_gift_notification package = welfare_package_kind.distributor.bestow(user, voucher) if package: # 拆包发礼券 # 针对新结算产品,动态分配抵扣金 package.unpack(user, allow_piling_firewood=allow_piling_firewood) # 本地记录 rsyslog.send('\t'.join([user.id_, package.id_]), tag='welfare_package_distribution') notification_voucher = (welfare_package_kind.coupon_wrappers or welfare_package_kind.firewood_wrapper.worth) if notification_voucher: # 提醒用户新增福利 welfare_reminder_group.add_member(user.id_) # 添加消息通知 Notification.create(user.id_, welfare_gift_notification, dict(welfare_package_id=package.id_)) return package
def act_after_setting_status(self, new_status): old_status = self._status # 本身已是成功状态则直接舍弃。 if self.Status(old_status) is self.Status.success: return self._status = new_status.value rsyslog.send('order %s status changes from %s to %s' % (self.id_, old_status, self._status), tag='hoarder_order_status_change') if new_status in [self.Status.shelved, self.Status.paying]: # 当支付未完成时将订单放入状态跟踪MQ self.track_for_payment() return if new_status is self.Status.success: # 当支付成功时将订单放入获取资产MQ并发送成功广播信号 rsyslog.send('fetch asset for order %s' % self.id_, tag='hoarder_fetch_asset') hoarder_asset_fetching.produce(self.id_) hoarder_order_succeeded.send(self) return if new_status is self.Status.failure: # 当支付失败时发送失败广播信号 hoarder_order_failed.send(self)
def send_gift_async(cls, user_id, gift_id): lottery_log = 'User: {0}, gift_id: {1}'.format(user_id, gift_id) rsyslog.send(lottery_log, tag='LotteryGiftMgr') if gift_id == cls.KEY_NONE: return str_task = ('{0}:{1}').format(user_id, gift_id) send_gift_worker.produce(str_task)
def _remove_legacy(cls, user_id, error=None): backward = BackwardProfile(user_id) rsyslog.send('%s\t%s\t%s\t%r' % (backward.account_id, backward.person_name, backward.person_ricn, error), tag='profile_identity_used_error') backward.remove()
def main(): """Downloads the product data of Yixin.""" with app.app_context(): response = yixin.query.p2p_service_list() for service_info in response.data: service = YixinService.add(service_info) rsyslog.send(service.uuid.hex, tag='yixin_updating_services')
def restore(cls, id_, user_id): if not Account.get(user_id): raise ValueError('invalid user %r' % user_id) instance = cls(id_, user_id, None, None, None, None) new_card = cls.get_by_card_number(instance.card_number) if new_card: raise BankCardChanged(new_card.id_) card_number_sha1 = calculate_checksum(instance.card_number) bank_id_sha1 = calculate_checksum(instance.bank_id) sql = ('insert into {.table_name} (id, user_id, card_number_sha1,' ' bank_id_sha1, status) ' 'values (%s, %s, %s, %s, %s)').format(cls) params = (id_, user_id, card_number_sha1, bank_id_sha1, cls.Status.active.value) db.execute(sql, params) db.commit() bankcard = cls.get(id_) rsyslog.send('\t'.join([ str(id_), str(user_id), str(bankcard.card_number), str(bankcard.bank_id), str(bankcard.mobile_phone), str(bankcard.province_id), str(bankcard.city_id), str(bankcard.local_bank_name), ]), tag='restore_bankcard') return bankcard
def assign_channel(user): if not request: return tag = request.cookies.get('channel', type=bytes) rsyslog.send('%s\t%s' % (user.id_, tag), tag='bd_channel') if tag: user.assign_channel_via_tag(tag)
def register_account(user_id): identity = Identity.get(user_id) local_account = Account.get(user_id) if not local_account.mobile: raise MissingMobilePhoneError if not identity: raise MissingIdentityError vendor = Vendor.get_by_name(Provider.sxb) sxb_account = SxbAccount.get_by_local(vendor.id_, user_id) if sxb_account: return sxb_account try: response = sxb.create_account(user_id=user_id, person_name=identity.person_name, id_card_no=identity.person_ricn, mobile=local_account.mobile) except BusinessError as e: raise MismatchUserError(u'%s,如有问题,请联系客服' % e) else: if not response.is_new: if not current_app.debug: rsyslog.send( u'您的身份信息(%s,%s,%s,%s) 已经被注册过,如有问题,请联系客服' % (user_id, identity.person_ricn, identity.person_name, local_account.mobile), 'sxb_dup_register') return SxbAccount.bind(vendor.id_, user_id, response.user_id)
def on_order_confirmed(sender): msg = '\t'.join([ sender.id_, sender.service_id, sender.user_id, sender.creation_time.isoformat(), sender.fin_order_id or '0', sender.order_id, sender.bankcard_id or '0', str(round(sender.order_amount, 2)) ]) rsyslog.send(msg, tag='savings_paid')
def log_register_source(uid, request): dcm = request.args.get('dcm', request.cookies.get('dcm', '0')) dcs = request.args.get('dcs', request.cookies.get('dcs', '0')) referer = request.args.get('refer', request.referrer) ip = request.remote_addr bid = request.bid msg = '\t'.join([uid, dcm, dcs, str(referer), ip, bid]) rsyslog.send(msg, tag='register_logger')
def mark_as_exited(self, response): assert self.status is self.Status.exiting remote_status = YixinPaymentStatus(int(response.state)) if remote_status is not YixinPaymentStatus.SUCCESS: raise YixinPaymentError(self, remote_status) rsyslog.send('transaction_id=%s\tcomplete_time=%s' % (response.tx_id, response.complete_time), tag='savings_placebo_exited') self.transfer_status(self.Status.exited)
def freeze_updated_bankcard(sender, changed_fields): if 'mobile_phone' not in changed_fields: return for provider in ServiceProvider.get_all(): binding = WalletBankcardBinding.get_by_bankcard(sender, provider) if not binding: continue binding.freeze() rsyslog.send('%r freezed' % binding, tag='wallet_unbind_bankcard')
def log_binding(uid, request, mobile): dcm = request.args.get('dcm', request.cookies.get('dcm', '0')) dcs = request.args.get('dcs', request.cookies.get('dcs', '0')) referer = request.cookies.get('next', request.environ.get('HTTP_REFERER')) ip = request.remote_addr bid = request.bid msg = '\t'.join([uid, dcm, dcs, str(referer), ip, mobile, bid]) rsyslog.send(msg, tag='mobile_binding_success')
def delete(self, reason=None): reason = reason or 'deleted by system' reason = '%s - %s' % (datetime.now(), reason) sql = ('update {.table_name} set is_deleted = %s, ' 'reason = %s where id=%s').format(self) params = (DELETED, reason, self.id) db.execute(sql, params) db.commit() rsyslog.send('rebate delete\t%s\t%s' % (self.id, reason), tag='hoard_rebate') self.clear_cache(self.user_id, self.id)
def remove(self, card_number, silent=False): try: BankCard.delete_by_card_number(card_number, user_id=self.user_id) except CardDeletingError as deleting_error: if silent: rsyslog.send('%s\t%s' % (card_number, deleting_error), 'bankcard_removing_denied') else: raise else: rsyslog.send(card_number, 'bankcare_removed')
def main(): """Downloads the product data of Xinmi.""" with app.app_context(): response = xinmi.get_products(ProductType.dingqi, remark=None) products = [ XMFixedDuedayProduct.add(info) for info in response.products if info.get('product_id') != '2015122217504424733' ] rsyslog.send(','.join([str(p.product_id) for p in products]), tag='xm_updating_products') # (暂时取消)增加新米产品到hoarder系统进行管理 """
def compute_net_worth(group, day, client): """ 计算某个基金组合某一天的净值 """ funds = group.get_funds_m2m() # 只能按当前组合方式计算净值,不能回溯历史 net_worth = 0.0 for fund in funds: fund_day_data = get_save_fundata(fund.fund_code, day, client) if not fund_day_data: rsyslog.send('%s day %s fundata not found' % (fund.fund_code, day), tag='fund') return net_worth += fund.rate * float(fund_day_data.net_worth) return net_worth
def migrate_bankcard(cls, old_bankcard_id, new_bankcard_id): order_ids = cls.get_id_list_by_bankcard_id(old_bankcard_id) sql = ('update {.table_name} set bankcard_id = %s ' 'where id = %s').format(cls) for order_id in order_ids: db.execute(sql, (new_bankcard_id, order_id)) db.commit() for order_id in order_ids: order = cls.get(order_id) order.clear_cache() rsyslog.send('%s to %s\t%r' % (old_bankcard_id, new_bankcard_id, order_ids), tag='hoard_migrate_bankcard')