def update_asset_balances(self, assets): with create_session() as session: account_model = session.query(ExchangeAccount).filter_by( id=self.account_model_id).first() if not type(assets) == list: logger.error(f"assets must be a list") return for asset in assets: asset_name = asset['name'] asset_model = session.query(Asset).filter_by( exchange=self._exchange).filter_by( exchange_account_id=self.account_model_id).filter_by( name=asset_name).first() if asset_model: asset_model.name = asset_name asset_model.free = asset['free'] asset_model.locked = asset['locked'] asset_model.timestamp = datetime.utcnow() else: asset_model = Asset(exchange=self._exchange, name=asset['name'], free=asset['free'], locked=asset['locked']) account_model.assets.append(asset_model) asset_names = [asset['name'] for asset in assets] for asset in account_model.assets: if asset.name not in asset_names: logger.info(f'Removing {asset.name}') session.delete(asset) session.commit()
def _get_or_create_asset(session, category_id): asset = session.query(Asset).filter_by(category_id=category_id).first() if asset is not None: return asset asset = Asset(category_id=category_id, amount=0) session.add(asset) return asset
def addzc(): flag = request.args.get('flag') if flag == '1': tasks = Task.query.filter_by(state='State.FINISH_SCAN', is_add=1).all() number = 0 db_url_list = [] to_url_list = [] assets = Asset.query.all() for asset in assets: db_url_list.append(asset.url) for task in tasks: cms = task.cms_result web = task.result host = task.host_result if task.result or task.host_result or task.cms_result: result = field.result_parse(cms,web,host) if result: try: if task.url not in db_url_list and task.url not in to_url_list: import pymysql asert = Asset(url=task.url, ip=result.get('ip'), title=result.get('title'), cms=result.get('cms'),operating_systems=str(result.get('os')) , web_servers=str(result.get('web_server')), programming_languages=str(result.get('programming_languages')),web_frameworks=str(result.get('web_frameworks')),javascript_frameworks=str(result.get('js')), ports=str(result.get( 'port')) , upgrade_time=datetime.datetime.now(), header=pymysql.escape_string(str(result.get('header'))), body=pymysql.escape_string(str(result.get('body')))) db.session.add(asert) db.session.commit() number += 1 to_url_list.append(task.url) except Exception as e: pass return field.success(message='成功更新{}条资产!'.format(number)) else: return field.params_error(message='没有接受到参数!')
def destroy(id=1): try: assets = Asset() asset = assets.query.get_or_404(id) target_dir = os.path.abspath(app.config['UPLOAD_FOLDER']) target = target_dir + '/' + asset.data_file_name # remove thumbnail first infilename, ext = os.path.splitext(target) os.remove(infilename + '.thumbnail' + ext) if os.path.isfile(infilename + '.thumbnail' + ext) else None # remove file last os.remove(target) if os.path.isfile(target) else None assets.destroy_data(asset.id) # html or Json response if request_wants_json(): return jsonify(data={ message: "Record deleted successfully.", asset: m_asset }) else: flash("Record deleted successfully.", category="success") return redirect(url_for('assets_page.index')) except Exception, ex: print("------------ ERROR ------------\n" + str(ex.message)) flash(str(ex.message), category="warning") abort(404)
def update_crypto(crypto): """Add crypto data to database""" btc = Asset.query.get(crypto) if btc: btc.price = btc_price btc.daily_price_change = float(btc_price - btc_daily_price) btc.daily_perc_change = percent_change(btc_price, btc_daily_price) btc.weekly_perc_change = percent_change(btc_price, btc_weekly_price) btc.monthly_perc_change = percent_change(btc_price, btc_monthly_price) btc.annual_perc_change = percent_change(btc_price, btc_annual_price) else: new_btc = Asset( id=crypto, asset="crypto", price=btc_price, daily_price_change=btc_price - btc_daily_price, daily_perc_change=percent_change(btc_price, btc_daily_price), weekly_perc_change=percent_change(btc_price, btc_weekly_price), monthly_perc_change=percent_change(btc_price, btc_monthly_price), annual_perc_change=percent_change(btc_price, btc_annual_price)) db.session.add(new_btc) db.session.commit() print(f'{crypto} updated!')
def update_prices(ticker): """Updates DB of price and price changes of ticker symbol.""" today_price = float(get_data(ticker, TODAY, TODAY)) daily_price = float(get_data(ticker, DAILY, TODAY)) weekly_price = float(get_data(ticker, WEEKLY, TODAY)) monthly_price = float(get_data(ticker, MONTHLY, TODAY)) annual_price = float(get_data(ticker, ANNUAL, TODAY)) stock = Asset.query.get(ticker) if stock: stock.price = today_price stock.daily_price_change = today_price - daily_price stock.daily_perc_change = percent_change(today_price, daily_price) stock.weekly_perc_change = percent_change(today_price, weekly_price) stock.monthly_perc_change = percent_change(today_price, monthly_price) stock.annual_perc_change = percent_change(today_price, annual_price) else: new_stock = Asset( id=ticker, asset="stock", price=today_price, daily_price_change=today_price - daily_price, daily_perc_change=percent_change(today_price, daily_price), weekly_perc_change=percent_change(today_price, weekly_price), monthly_perc_change=percent_change(today_price, monthly_price), annual_perc_change=percent_change(today_price, annual_price)) db.session.add(new_stock) db.session.commit() print(f'{ticker} updated!')
def post_assets(self, balances): with create_session() as session: account = session.query(AccountModel).filter_by( api_key=self.api_key).first() account_assets = account.my_assets account_assets_names = [asset.name for asset in account_assets] for asset_params in balances: if not asset_params[ 'asset'] in account_assets_names: # asset is not yet created asset = Asset(name=asset_params['asset'], free=asset_params['free'], fixed=asset_params['locked'], account=account) session.add(asset) continue for account_asset in account_assets: if asset_params['asset'] == account_asset.name: account_asset.free = asset_params['free'] account_asset.fixed = asset_params['locked'] session.add(account_asset) #do the reverse, check if there is an asset whose balance is zero balances_assets_names = [asset['asset'] for asset in balances] for asset_name in account_assets_names: if asset_name not in balances_assets_names: asset = [ asset for asset in account_assets if asset.name == asset_name ] if asset: asset = asset[0] session.delete(asset) logger.info(f"asset {asset_name} has been deleted") session.commit()
def post(self): ''' ''' args = self.reqparse.parse_args(strict=True) asset = Asset(**args) dbadd(addidc) return my_response(dict(result=True, message='NEW IDC add Success'))
def put(self, asset_id): args = self.put_reqparse.parse_args() asset = Asset.query.filter_by(identifier=asset_id).first() if asset is None: asset = Asset(args['title'], args['description'], args['thumbnail_url']) header = {'location': '/assets/' + str(asset.identifier)} return asset, 201, header asset.update(args['title'], args['description'], args['thumbnail_url']) return asset, 200
def parse(filename): with open(filename, 'rb') as csvfile: reader = csv.DictReader(csvfile, delimiter=',', quotechar='"') assets = [] return map(lambda row: Asset( symbol=row.get('Symbol'), quantity=row.get('Quantity'), price=row.get('Price') ), reader)
def list_data(): f = open("flax.csv") reader = csv.reader(f) for asset_address, asset_id, asset_cpp in reader: asset = Asset(asset_address=asset_address, asset_id=asset_id, asset_cpp=asset_cpp) db.session.add(asset) print( f"Asset_ID = {asset_id} \n Asset location = {asset_address} \n Control plan page = {asset_cpp}" ) db.session.commit()
def test_model_asset(self): "Test asset model" contact_type = ContactType(name='test') contact_type.save() contact = Contact(name='test', contact_type=contact_type) contact.save() obj = Asset(name='test', owner=contact) obj.save() self.assertEquals('test', obj.name) self.assertNotEquals(obj.id, None) obj.delete()
def show(id=1): try: m_assets = Asset() m_asset = m_assets.read_data(id) # html or Json response if request_wants_json(): return jsonify(data=m_asset) else: return render_template("assets/show.html", asset=m_asset, app=app) except Exception, ex: print("------------ ERROR ------------\n" + str(ex.message)) flash(str(ex.message), category="warning") abort(404)
def add_asset_view(request): try: strjson = request.body decjson = json.loads(strjson) if Asset.objects.filter(asset_id=decjson['asset_id']).exists(): return HttpResponse('Conflict', status=409) else: vasset = Asset() vasset.asset_id = decjson['asset_id'] vasset.asset_type = "unknown" vasset.save() message = "Asset Generado Correctamente" return HttpResponse('Asset Generado Correctamente', status=200) except ValueError, e: message = "Error al leer archivo JSON. (" + e.message + ")" return render(request, 'cawas/error.html', {"message": message})
def add_asset(): ''' 新增服务器信息 { "Device_type": "VM", "System_Hostname": "sso.jinu.tech", "System_Ip": "172.16.1.4", "IDC_Id": "QCLOUD" , "Physical_Memory": "2" } ''' if request.method == 'POST': data = request.json #host = Asset.query.filter_by(Host_Id=id).first() #data = {'System_Ip': host.System_Ip, 'System_Hostname': host.System_Hostname, 'idc': host.IDC_Id,'Device_type': host.Device_type} #data = {'System_Ip': 'host.System_Ip', 'System_Hostname': 'host.System_Hostname', 'idc': 'host.IDC_Id','Device_type': 'host.Device_type'} host = Asset(**data) db.session.add(host) db.session.commit() result = {'host_id': host.host_id, 'system_ip': host.system_ip, 'system_hostname': host.system_hostname,'idc': host.idc_id, 'device_type': host.device_type} mes = 'HOST add is success , ID is %s .' % host.host_id return task.json_message_200(data=result,info=mes), 200
def data_list(): f = open("flax.csv") reader = csv.reader(f) for asset_address, asset_id, asset_cpp in reader: asset = Asset(asset_address=asset_address, asset_id=asset_id, asset_cpp=asset_cpp) db.session.add(asset) print( f"Asset_ID = {asset_id} \n Asset location = {asset_address} \n Control plan page = {asset_cpp}" ) db.session.commit() # if __name__ == "__main__": # with app.app_context(): # main()
def batch_asset(): ''' 批量新增服务器信息 [ { "device_type": "VM", "system_hostname": "git.jinu.tech", "system_ip": "172.16.1.5", "idc_id": "QCLOUD" , "physical_memory": "2" } , { "device_type": "VM", "system_hostname": "jk.jinu.tech", "system_ip": "172.16.1.6", "idc_id": "QCLOUD" , "physical_memory": "2" } ] ''' if request.method == 'POST': hostlist = request.json mes = [] for data in hostlist: host = Asset(**data) db.session.add(host) mes.append({ host.system_ip:host.host_id}) db.session.commit() return task.json_message_200('HOST add is success , ID is %s .' % mes), 200
def new_asset(): ''' Create new asset ''' form = AssetForm() if form.validate_on_submit(): my_asset = Asset() form.populate_obj(my_asset) db.session.add(my_asset) try: db.session.commit() # User info flash('Asset created correctly', 'success') return redirect(url_for('assets')) except: db.session.rollback() flash('Error generating asset.', 'danger') return render_template('web/new_asset.html', form=form)
def index(page=1): try: m_assets = Asset() list_assets = m_assets.all_data(page, app.config['LISTINGS_PER_PAGE']) # html or Json response if request_wants_json(): return jsonify([{ 'id': d.id, 'title_en_US': d.title_en_US, 'description_en_US': d.description_en_US, 'title_fr_FR': d.title_fr_FR, 'description_fr_FR': d.description_fr_FR } for d in list_assets.items]) else: return render_template("assets/index.html", list_assets=list_assets, app=app) except Exception, ex: print("------------ ERROR ------------\n" + str(ex.message))
def update_asset_balance(self, msg): with create_session() as session: account_model = session.query(ExchangeAccount).filter_by( id=self.account_model_id).first() asset_name = msg['name'] asset_model = session.query(Asset).filter_by( exchange=self._exchange).filter_by( exchange_account_id=self.account_model_id).filter_by( name=asset_name).first() if asset_model: asset_model.name = asset_name asset_model.free = msg['free'] asset_model.locked = msg['locked'] asset_model.timestamp = datetime.utcnow() else: asset_model = Asset(exchange=self._exchange, name=msg['name'], free=msg['free'], locked=msg['locked']) account_model.assets.append(asset_model) session.commit()
def POST(self, table_name): inp = web.input() state = inp.get('state') if state == 'hapus': asset_id = inp.get('asset_id') delete = Delete('asset', where='id=' + asset_id) query = conn.sqlrepr(delete) conn.query(query) return "ok" elif state == 'tambah': nama = inp.get('nama_asset_add') kategori = inp.get('kategori-asset') merk = inp.get('merk') model = inp.get('model') tgl_perolehan = inp.get('tgl_perolehan') if inp.get('nilai'): n1 = inp.get('nilai').replace('Rp. ', '') n2 = n1.replace('.', '') nilai = n2 bmn = inp.get('bmn') Asset(table_name=table_name, cuser=session.get('username'), kategori=kategori + '_' + nama, nama=nama, merk=merk, model=model, perolehan=tgl_perolehan, nilai_perolehan=int(nilai), bmn=bmn) return web.redirect('asset') else: try: asset = Asset.get(int(inp.get('pk'))) asset.set(**{inp.get('name'): inp.get('value')}) except SQLObjectNotFound: return web.notfound() web.header('Content-Type', 'application/json') return json.dumps({"Ok": "true"})
def initialise_new(): groups = PGroup.objects.filter(gtype=1) asset_all = get_all_asset_info() for group in groups: group_id = group.id #asset_all_old = group.asset_set.all() segments = group.segment.split(',') delete_ip(group_id, segments) for segment in segments: for asset in asset_all:#asset (ip,port,hostname) if asset[0] in IPy.IP(segment): if Asset.objects.filter(ip=asset[0]): asset = Asset.objects.get(ip=asset[0]) asset_groups_obj = PGroup.objects.filter(id=group_id) asset.group = asset_groups_obj asset.save() continue new_asset = Asset(ip=asset[0], port=asset[1],hostname=asset[2]) new_asset.save() asset_groups_obj = PGroup.objects.filter(id=group_id) new_asset.group = asset_groups_obj new_asset.save()
def item_add(self, item_name, item_description, item_quantity, cost_per_item): ''' This method add an item to the database It also makes sure that same item cannot be added twice ''' query = self.session.query(Asset.item_name, Asset.item_description).all() current_item = (item_name, item_description) available_items = [(item.item_name, item.item_description) for item in query] if current_item in available_items: click.secho("\n\t\t\tSuch an item already exist in the database", fg = 'red', bold = True) return date_added = datetime.now().strftime('%Y-%m-%d %H:%M') item_status = True self.session.add(Asset(item_name, item_description, item_quantity, cost_per_item, date_added, item_status)) self.session.commit() click.secho("\n\t\t\tSuccessfully Added", fg = 'green', bold = True)
def save(only_push=False): app = APILogic() assets = [ Asset(2112, quantity=8027, nav=14.35), Asset(1990, quantity=12771, nav=9.02), Asset(2064, quantity=2689, nav=42.84), Asset(1968, quantity=59076, nav=1.95), Asset(1897, quantity=21021, nav=5.48), Asset(1956, quantity=37524, nav=3.07), Asset(2120, quantity=81, nav=1418.0), Asset(1877, quantity=30901, nav=3.728), Asset(1585, quantity=4170, nav=27.62), Asset(1960, quantity=20682, nav=5.57), Asset(2013, quantity=5835, nav=19.74), Asset(1958, quantity=874, nav=131.75), Asset(2000, quantity=12972, nav=8.88), Asset(1912, quantity=13076, nav=8.81), Asset(1872, quantity=4129, nav=27.9), ] new_quantities = [ 4738, 12771, 4327, 95140, 21021, 22155, 81, 30901, 4170, 10989, 9394, 514, 10506, 13076, 2193 ] # 2.512252348115 new_quantities = [ 2516, 9308, 4327, 95140, 15323, 11772, 89, 30901, 4170, 2511, 9394, 114, 6202, 13076, 497 ] # 2.556050614378 new_quantities = [ 2516, 9308, 4327, 95140, 15323, 10594, 89, 30901, 4170, 2511, 9394, 114, 6202, 13076, 497 ] # 2.55606999004 new_quantities = [ 2516, 8842, 4327, 95140, 15323, 10594, 89, 30901, 4170, 2511, 9394, 108, 6202, 12422, 497 ] # 2.556471976733 new_quantities = [ 2516, 8842, 4327, 95140, 15323, 10594, 89, 29355, 3961, 2511, 9394, 102, 6202, 12422, 497 ] # 2.556703403807 for i, quant in enumerate(new_quantities): assets[i].quantity = quant app.update_ptf(assets) app.update_ptf(assets) ratio = app.get_user_ptf_sharpe() print("Dolphin: intial ratio :" + str(ratio)) if not only_push: improve_ptf(app, assets, [], [], ratio)
def post(self): args = self.post_reqparse.parse_args() asset = Asset(args['title'], args['description'], args['thumbnail_url']) header = {'location': '/assets/' + str(asset.identifier)} return asset, 201, header
def initialise(): # 从zeus数据库获取所有asset列表 asset_all # 读config 匹配对应的每个部门分组的网段进行更新 # error = check_conf() if not error: print 'good' else: print error print 'start initialise' cf = ConfigParser.ConfigParser() config = os.path.join(BASE_DIR, 'group.conf') cf.read(config) groups = cf.sections() pgroups = PGroup.objects.filter(gtype=1) for pg in pgroups: if pg.name not in groups: pg.delete() asset_all = get_all_asset_info() delete_user_department() for group in groups: ip_group = [] segments = cf.get(group,"segment").split(",") managers = cf.get(group,"manager").split(",") department = cf.get(group,"department") env = cf.get(group,"env") if not Group.objects.filter(name=department): dgroup = Group(name=department) dgroup.save() for manager in managers: if not User.objects.filter(username=manager): user = User(username=manager) user.save() obj_group = Group.objects.filter(name=department) user.groups = obj_group user.save() else: user = User.objects.get(username=manager) obj_group = Group.objects.get(name=department) user.groups.add(obj_group) user.save() if PGroup.objects.filter(name=group): PGS = PGroup.objects.get(name=group) PGS.department = department PGS.env = env old_manager_users = PGS.manager.all() for o in old_manager_users: if o.username not in managers: PGS.manager.remove(o) for manager in managers: m_user = User.objects.get(username=manager) PGS.manager.add(m_user) PGS.save() group_id = PGS.id else: addpgroup = PGroup(name=group,department=department,env=env,gtype=1) addpgroup.save() for manager in managers: m_user = User.objects.get(username=manager) addpgroup.manager.add(m_user) addpgroup.save() group_id = addpgroup.id ###删除多余ip delete_ip(group_id, segments) ###1.在Zeus中不存在的;2.在网段中不存在的 for segment in segments: for asset in asset_all:#asset (ip,port,hostname) if asset[0] in IPy.IP(segment): if Asset.objects.filter(ip=asset[0]): asset = Asset.objects.get(ip=asset[0]) asset_groups_obj = PGroup.objects.filter(id=group_id) asset.group = asset_groups_obj asset.save() continue new_asset = Asset(ip=asset[0], port=asset[1],hostname=asset[2]) new_asset.save() asset_groups_obj = PGroup.objects.filter(id=group_id) new_asset.group = asset_groups_obj new_asset.save() ip_group.append(asset[0]) print 'initialise finished' return True
processor = random.choice(choice_list['processor']) ram = random.choice(choice_list['ram']) hdd = random.choice(choice_list['hdd']) asset_no = random_alphanumeric() allocation_date = random_date() project_name = random.choice(choice_list['project_name']) won_no = random.randint(1000, 2000) end_date = random_date(start_date=allocation_date, end_date='+1y') # Save in database row_data = Asset(name=name, emp_no=emp_no, location=location, seat_no=seat_no, sl_no_1=sl_no_1, model=model, make=make, tel_tvm=tel_tvm, test_pc=test_pc, processor=processor, ram=ram, hdd=hdd, asset_no=asset_no, allocation_date=allocation_date, project_name=project_name, won_no=won_no, end_date=end_date) db.session.add(row_data) db.session.commit()
def make_asset(type_id, name, **kw): asset_id = make_random_string(16) asset = Asset(id=asset_id, type_id=type_id, name=name, **kw) db.add(asset) db.commit() return asset
from models import Asset from transform import usaa date = '2019-03-13' folder = 'data/' + date assets = [Asset(**row) for row in usaa.normalize(folder)] with open('portfolio.csv', 'w') as folio: for asset in assets: folio.write(asset.to_csv() + "\n") total = sum([asset.price * asset.quantity for asset in assets]) print(total) with open('data/doit.csv', 'a') as out: out.write("{}, {}".format(date, total))
def edit(id=1): try: # check_admin() assets = Asset() asset = assets.query.get_or_404(id) # users = User.query.all() users = User.query.filter(User.is_active == True).all() items = Item.query.filter(Item.is_active == True).all() # request.form only contains form input data. request.files contains file upload data. # You need to pass the combination of both to the form. form = Form_Record_Add(CombinedMultiDict( (request.files, request.form))) if request.method == 'POST': if form.validate(): # file = request.files['data_file_name'] file = form.data_file_name.data # if user does not select file, browser also submit a empty part without filename # value not required in edit mode if file and allowed_file(file.filename): filename = secure_filename(file.filename) filename = filename.encode('utf-8') target_dir = os.path.abspath(app.config['UPLOAD_FOLDER']) target = target_dir + '/' + filename # Remove previous image prev_target = target_dir + '/' + asset.data_file_name print("------------ PREV FILE ------------\n" + str(prev_target)) # remove previous thumbnail first prev_infilename, prev_ext = os.path.splitext(prev_target) os.remove(prev_infilename + '.thumbnail' + prev_ext) if os.path.isfile(prev_infilename + '.thumbnail' + prev_ext) else None # remove previous file last os.remove(prev_target) if os.path.isfile( prev_target) else None print("------------ FILE ------------\n" + str(target)) # if target not exist if not os.path.isdir(target_dir): os.mkdir(target_dir) file.save(target) filetype = file.content_type # guess asset type asset_type = get_asset_type(filetype) if asset_type == "image": # resize if too high resize_image_to_max(target, app.config['MAX_SIZE']) filesize = os.stat(target).st_size # image processing thumbnail infilename, ext = os.path.splitext(target) filewidth = 0 fileheight = 0 if asset_type == "image": im = Image.open(target) filewidth, fileheight = im.size im.thumbnail(app.config['THUMBNAIL_SIZE']) im.save(infilename + ".thumbnail" + ext) if not file: filename = asset.data_file_name filetype = asset.data_content_type filesize = asset.data_file_size filewidth = asset.width fileheight = asset.height asset_type = asset.asset_type sanitize_form = { 'data_file_name': filename, 'data_content_type': filetype, 'data_file_size': filesize, 'asset_type': asset_type, 'width': filewidth, 'height': fileheight, 'description_en_US': form.description_en_US.data, 'description_fr_FR': form.description_fr_FR.data, 'user': form.user.data, 'items': form.items.data, 'is_active': form.is_active.data } assets.update_data(asset.id, sanitize_form) logger.info("Editing a new record.") if request_wants_json(): return jsonify(data={ message: "Record updated successfully.", form: form }), 200, { 'Content-Type': 'application/json' } else: flash("Record updated successfully.", category="success") return redirect("/assets") form.action = url_for('assets_page.edit', id=asset.id) form.data_file_name.data = asset.data_file_name form.data_content_type.data = asset.data_content_type form.data_file_size.data = asset.data_file_size form.asset_type.data = asset.asset_type form.width.data = asset.width form.height.data = asset.height form.description_en_US.data = asset.description_en_US form.description_fr_FR.data = asset.description_fr_FR if asset.user: form.user.data = asset.user.id if asset.items: form.items.data = asset.items form.is_active.data = asset.is_active # html or Json response if request_wants_json(): return jsonify(data=form), 200, { 'Content-Type': 'application/json' } else: return render_template("assets/edit.html", form=form, users=users, items=items, title_en_US='Edit', app=app) except Exception, ex: print("------------ ERROR ------------\n" + str(ex.message)) flash(str(ex.message), category="warning") abort(404)