def main(): user = Account.get_by_alias(EMAIL) ZhiwangAccount.unbind(user.id_) try: register_zhiwang_account(user.id_) zhiwang_account = ZhiwangAccount.get_by_local(user.id_) except (MismatchUserError, RepeatlyRegisterError) as e: bcolors.fail(e.args[0], key='zhiwang_code') return bcolors.run('The new zhiwang code is %s' % zhiwang_account.zhiwang_id, key='zhiwang_code') with open(ADD_ZHIWANG_FILE, 'r') as f: source = RE_ZHIWANG_CODE.sub( "ZHIWANG_TOKEN = u'%s'" % zhiwang_account.zhiwang_id.encode('ascii'), f.read()) with open(ADD_ZHIWANG_FILE, 'w') as f: f.write(source) bcolors.run('%s is changed. PLEASE COMMIT IT AND OPEN A MERGE REQUEST.' % ADD_ZHIWANG_FILE, key='zhiwang_code') if '--commit' in sys.argv: subprocess.check_call( ['git', 'commit', '-m', COMMIT_MSG, '--', ADD_ZHIWANG_FILE])
def token_dump(user_alias, workdir=None): """Dumps API token from database.""" account = Account.get_by_alias(user_alias) if not account: return bcolors.fail('user %r not found' % user_alias) workdir = os.path.expanduser(workdir or '~/.guihua') if not os.path.exists(workdir): os.makedirs(workdir) yixin_account = YixinAccount.get_by_local(account.id_) if not yixin_account: return bcolors.fail('%r need to bind yixin account' % user_alias) jsonfile_location = os.path.join(workdir, 'solar-yixin-token.json') if os.path.exists(jsonfile_location): with open(jsonfile_location) as jsonfile: data = json.load(jsonfile) if not isinstance(data, dict): return bcolors.fail('unexpected data') else: data = {} data[user_alias] = { 'user_alias': user_alias, 'yixin_account': yixin_account.p2p_account, 'yixin_token': yixin_account.p2p_token, } with open(jsonfile_location, 'w') as jsonfile: json.dump(data, jsonfile, indent=4) bcolors.success('success: %s %s' % (user_alias, yixin_account.p2p_account))
def consume(self): broker = self.get_broker() job = broker.reserve() if job is None: return bcolors.success('Get job %s' % job.jid) self._send_log('get job %s' % job.jid) try: self.target(job.body) except KeyboardInterrupt: job.bury() raise except WorkerTaskError: sentry.captureException(level=logging.WARNING) job.bury() except Exception as e: sentry.captureException() bcolors.fail('job %s failed and bury. %s' % (job.jid, unicode(e).encode('utf-8'))) self._send_log('job %s failed and buried because %s' % (job.jid, unicode(e).encode('utf-8'))) job.bury() else: bcolors.success('Job process success.') job.delete() self._send_log('job %s deleted' % job.jid)
def init(): """Downloads the product data of Yixin.""" try: response = yixin.query.p2p_service_list() except RemoteError as e: bcolors.fail('%s : %s : %s' % e.args) else: for service_info in response.data: service = YixinService.add(service_info) bcolors.success('YixinService: %s' % service.p2pservice_name)
def init(): """Downloads the product data of sxb.""" try: rs = sxb.query_products(ProductType.ririying) except ClientError as e: bcolors.fail('Fetching Sxb Product Failed:%s' % e) else: for product_info in rs: product = fillup_local(product_info) product = fillup_local(product_info, is_child_product=True) bcolors.success('SxbProduct: %s' % product.name)
def vacuum_tokens(token_ids='', grace_days=0): """Clean up expired tokens from database.""" grace_time = timedelta(days=int(grace_days)) ids = [id_.strip() for id_ in token_ids.split(',') if id_.strip()] if ids: if all(id_.isdigit() for id_ in ids): OAuthToken.vacuum(ids, grace_time=grace_time) else: bcolors.fail( '"-t" should be comma-splited digits (e.g. "10001,10002")') return else: OAuthToken.vacuum(grace_time=grace_time) # vacuum all tokens
def main(): user = Account.get_by_alias(EMAIL) if not user: bcolors.fail('%s is not found' % EMAIL, key='firewood') flow = FirewoodWorkflow(user.id_) transaction = firewood.create_transaction(flow.account_uid, AMOUNT, TAGS) transaction_uid = uuid.UUID(transaction.json()['uid']) transaction = firewood.confirm_transaction(flow.account_uid, transaction_uid) transaction_uri = transaction.json()['_links']['self'] bcolors.run('%s +100.00' % transaction_uri, key='firewood')
def init(): """Synchronize the annual rates.""" try: rates = WalletAnnualRate.synchronize(zslib.client, provider.fund_code) except BusinessError as e: bcolors.fail('%s : %s : %s' % e.args) return for rate in rates: bcolors.success('{0}\t{1}\t{2}\t¥{3}'.format( rate.date, rate.fund_code, round_half_up(rate.annual_rate, 2), round_half_up(rate.ten_thousand_pieces_income, 2), ))
def main(): bcolors.run('Add redeem code.') effective_time = datetime.now() - timedelta(days=1) expire_time = datetime.now() + timedelta(days=30) try: # 创建100个可被使用一次的兑换码 RedeemCode.create_multi_codes(fanmeeting_gold.id_, RedeemCode.Kind.normal_package.value, u'测试用兑换码', 1, 100, effective_time, expire_time) # 创建一个可使用100次的兑换码 RedeemCode.create(fanmeeting_silver.id_, RedeemCode.Kind.normal_package.value, u'测试用兑换码', 100, None, effective_time, expire_time) bcolors.success('Init redeemcode done.') except Exception as e: bcolors.fail('Init redeemcode fail: %s.' % e)
def orders(user_alias): """Lists all orders of specific user.""" user = Account.get_by_alias(user_alias) if not user: bcolors.fail('user not found') return profile = HoardProfile.get(user.id) if not profile: bcolors.fail('profile not initialized') return for order, _, status in profile.orders(): data = [ order.id_, order.creation_time, round(order.order_amount, 2), order.service.p2pservice_name, status, ] print(u'\t'.join(map(unicode, data)))
def order_status(order_id, new_status): """Edits the status of specific order.""" if new_status in remote_statuses(): new_status = new_status.decode(sys.stdin.encoding) else: status_list = ', '.join(remote_statuses()) bcolors.fail('status must be one of %s' % status_list) return order = HoardOrder.get(order_id) if not order: bcolors.fail('order not found') return profile = HoardProfile.get(order.user_id) matched_index = [ index for index, order_info in enumerate(profile.person_account_info) if order_info['finOrderNo'] == order.fin_order_id ] if not matched_index: bcolors.fail('failed') return account_info = list(profile.person_account_info) account_info[matched_index[0]]['finOrderStatus'] = unicode(new_status) profile.person_account_info = account_info bcolors.success('done')
def init(): """Downloads the product data of Zhiwang.""" try: response = zhiwang.product_list() except RemoteError as e: bcolors.fail('Fetching Zhiwang Product Failed:%s' % e) else: all_products = [] for product_info in response.products: base_product = ZhiwangProduct.add(product_info) bcolors.success('ZhiwangProduct: %s' % base_product.name) wrapped_products = ZhiwangWrappedProduct.get_multi_by_raw(base_product.product_id) for wp in wrapped_products: bcolors.success('ZhiwangWrappedProduct: %s' % wp.name) all_products.append(base_product) all_products.extend(wrapped_products) for p in all_products: # 测试环境默认上架 p.is_taken_down = False
def token_load(workdir=None): """Loads API token from local file.""" workdir = os.path.expanduser(workdir or '~/.guihua') if not os.path.exists(workdir): return bcolors.fail('token not found') jsonfile_location = os.path.join(workdir, 'solar-yixin-token.json') if not os.path.exists(jsonfile_location): return bcolors.fail('token not found') with open(jsonfile_location) as jsonfile: data = json.load(jsonfile) for user_alias, item in data.iteritems(): account = Account.get_by_alias(item['user_alias']) if not account: bcolors.fail('user %s not found' % user_alias) continue p2p_account = item['yixin_account'] p2p_token = item['yixin_token'] YixinAccount.bind(account.id_, p2p_account, p2p_token) bcolors.success('restored %s %s' % (account, p2p_account))
# coding: utf-8 """ 创建测试用礼券 """ from libs.utils.log import bcolors from core.models.user.account import Account from core.models.welfare.package.kind import test_newcomer_center if __name__ == '__main__': bcolors.run('Add coupons.') # in init_user we create test%[email protected] try: emails = ['*****@*****.**' % r for r in range(9)] emails.append('*****@*****.**') for email in emails: user = Account.get_by_alias(email) package = test_newcomer_center.distributor.bestow(user) package.unpack(user) bcolors.success('Init coupon done.') except Exception as e: bcolors.fail('Init coupon fail: %s.' % e)
u = add_user(name, email, reg_type=ACCOUNT_REG_TYPE.EMAIL) if i < 5: p = Plan.add(u.id) p.data.secret_db.set(p.data.props_name, d) p.update_step(6) bcolors.run('email=%s, password=%s, plan=%s' % (email, 'testtest', p.id), key='user') else: bcolors.run('email=%s, password=%s' % (email, 'testtest'), key='user') for i in range(10): name = 'mobiletest%s' % i mobile = '159%s' % (repr(i) * 8) u = add_user(name, mobile, reg_type=ACCOUNT_REG_TYPE.MOBILE) if i < 5: p = Plan.add(u.id) p.data.secret_db.set(p.data.props_name, d) p.update_step(6) bcolors.run('mobile=%s, password=%s, plan=%s' % (mobile, 'testtest', p.id), key='user') else: bcolors.run('mobile=%s, password=%s' % (mobile, 'testtest'), key='user') bcolors.success('Init user done.') except Exception as e: bcolors.fail('Init user fail: %s.' % e)
(652200, '哈密地区', 650000), (652300, '昌吉回族自治州', 650000), (652700, '博尔塔拉蒙古自治州', 650000), (652800, '巴音郭楞蒙古自治州', 650000), (652900, '阿克苏地区', 650000), (653000, '克孜勒苏柯尔克孜自治州', 650000), (653100, '喀什地区', 650000), (653200, '和田地区', 650000), (654000, '伊犁哈萨克自治州', 650000), (654200, '塔城地区', 650000), (654300, '阿勒泰地区', 650000), (710000, '台湾省', 100000), (710100, '台湾地区', 710000), (810000, '香港特别行政区', 100000), (810100, '香港地区', 810000), (820000, '澳门特别行政区', 100000), (820100, '澳门地区', 820000), ] bcolors.run('Add Location.') try: for r in CITIES: db.execute( 'insert into location ' '(id, name_cn, parent_id) ' 'values (%s, %s, %s)', r) db.commit() bcolors.success('Add Location Done.') except Exception as e: bcolors.fail('Init data fail: %r' % e)