def put(self): json = request.json['asset'] asset = AssetModel(name=json['name'], description=json['description'], manufacturer_id=json['manufacturer'], min_quantity=json['min_quantity'], image=json['image'], max_quantity=json['max_quantity']) asset.manufacturer = Manufacturer().find(id=json['manufacturer']) asset.save() model = { 'department': { 'id': asset.id, 'name': asset.name, 'description': asset.description, 'manufacturer': asset.manufacturer_id, 'min_quantity': asset.min_quantity, 'max_quantity': asset.max_quantity, 'image': asset.image, 'requires_approval': 'true' if asset.requires_approval else 'false' } } print model return jsonify(model), 201
def put(self): json = request.json['asset'] asset = AssetModel( name=json['name'], description=json['description'], manufacturer_id=json['manufacturer'], min_quantity=json['min_quantity'], image=json['image'], max_quantity=json['max_quantity'] ) asset.manufacturer = Manufacturer().find(id=json['manufacturer']) asset.save() model = { 'department': { 'id': asset.id, 'name': asset.name, 'description': asset.description, 'manufacturer': asset.manufacturer_id, 'min_quantity': asset.min_quantity, 'max_quantity': asset.max_quantity, 'image': asset.image, 'requires_approval': 'true' if asset.requires_approval else 'false' } } print model return jsonify(model), 201
def get(self): assetlist = [] for asset in AssetModel.list(): units = [] for unit in asset.units: units.append({ 'id': unit.id, 'status': unit.status, 'tag': unit.tag, 'purchase_cost': unit.purchase_cost, 'warranty_expiration': unit.warranty_expiration, 'end_of_life': unit.end_of_life, 'asset': unit.asset_id, }) model = { 'id': asset.id, 'description': asset.description, 'name': asset.name, 'max_quantity': asset.max_quantity, 'min_quantity': asset.min_quantity, 'image': asset.image, 'units': units, 'requires_approval': 'true' if asset.requires_approval else 'false' } print model assetlist.append(model) return jsonify({'assets': assetlist})
def init_db(self, engine): if engine.__class__ is not Engine: raise exceptions.DBException('Database engine is not avaliable!') self._engine = engine self._dbSessMaker = sessionmaker(bind=engine, autocommit=True) self._dbSess = self._dbSessMaker() # Add station to DB # TODO: Make name changable, identify by slug q = self._dbSess.query(StationModel).filter_by(name=self._name, slug=self._slug) if q.count() < 1: self._('No DB entry found for this station, creating one...', p='Warning') station = StationModel(name=self._name, slug=self._slug) self._dbSess.add(station) default_asset = Asset( id_by_station = -1, type = 'Live', station = station, title = 'LIVE', artist = self._name, ) self._dbSess.add(default_asset) # self._dbSess.commit() else: station = q.first() self._dbObj = station
def get(self, id): asset = AssetModel.find(id=id) units = [] for unit in asset.units: units.append({ 'id': unit.id, 'status': unit.status, 'tag': unit.tag, 'purchase_cost': unit.purchase_cost, 'warranty_expiration': unit.warranty_expiration, 'end_of_life': unit.end_of_life, 'asset': unit.asset_id, }) model = { 'asset': { 'id': asset.id, 'description': asset.description, 'name': asset.name, 'max_quantity': asset.max_quantity, 'min_quantity': asset.min_quantity, 'image': asset.image, 'manufacturer': asset.manufacturer_id, 'units': units, 'requires_approval': 1 if asset.requires_approval else 0 } } return jsonify(model)
def _edit_form(self, path, asset): user = get_current_user() if config.settings.editors and (not user or user.email() not in config.settings.editors): logging.warning('user %s not found in editors %s', user, config.settings.editors) return self.redirect(create_login_url('/')) create = False if not asset: logging.info('Creating asset %s', path) create = True asset = Asset(fullpath=path) _, ext = os.path.splitext(asset.fullpath or path) if 'upload' in self.request.GET: self.response.write( JINJA_ENVIRONMENT.get_template('asset_upload.html').render({})) else: self.response.write( JINJA_ENVIRONMENT.get_template('asset_edit.html').render({ 'mimes': mimeutil.MIME_DICT, 'content': asset.content or '', 'fullpath': asset.fullpath or '', 'mime': asset.mime or mimeutil.get_mime(path), 'create': create or '' }))
async def get(self): """Get all assets.""" with self.make_session() as session: assets = await as_future(session.query(Asset).all) output = [] for asset in assets: output.append(Asset.serialize(asset)) print('GET assets: ', output) self.write({'assets': output})
def download(self): q = Asset.query() assets = q.fetch(100) output = StringIO.StringIO() with zipfile.ZipFile(output, 'w') as zf: for a in assets: zf.writestr(a.fullpath.lstrip('/'), a.content) self.response.headers['Content-Type'] = 'application/zip' self.response.headers['Content-Disposition'] = 'attachment; filename="%s"' % 'site.zip' self.response.write(output.getvalue())
async def get(self, asset_id): """Get one asset.""" with self.make_session() as session: asset = await as_future( session.query(Asset).filter(Asset.id == asset_id).first) if not asset: self.finish({'message': 'No Asset found!'}) asset_data = Asset.serialize(asset) print('GET asset: ', asset_data) self.write({'assets': asset_data})
def download(self): q = Asset.query() assets = q.fetch(100) output = StringIO.StringIO() with zipfile.ZipFile(output, 'w') as zf: for a in assets: zf.writestr(a.fullpath.lstrip('/'), a.content) self.response.headers['Content-Type'] = 'application/zip' self.response.headers[ 'Content-Disposition'] = 'attachment; filename="%s"' % 'site.zip' self.response.write(output.getvalue())
async def post(self): """Create a new asset.""" with self.make_session() as session: # data = json.loads(self.request.body.decode('utf-8')) asset = Asset(name=self.json_args['name']) session.add(asset) session.commit() asset_data = Asset.serialize(asset) print('POST added asset: ', asset_data) # assets = await as_future(session.query(Asset).all) self.write({'message': 'new item added', 'asset': asset_data})
async def put(self, asset_id): """Update asset.""" with self.make_session() as session: asset = await as_future( session.query(Asset).filter(Asset.id == asset_id).first) if not asset: self.finish({'message': 'No Asset found!'}) asset.name = self.json_args['name'] session.commit() self.write({ 'message': 'The item has been updated', 'asset': Asset.serialize(asset) })
def post_asset(): company = request.json.get('company') asset_tag = request.json.get('asset_tag') if Asset.query.filter( and_(Asset.company == company, Asset.asset_tag == asset_tag)).first() is not None: json_abort( { 'err_msg': '%s is already exist in %s' % (asset_tag, company), 'err_code': 1 }, 422) asset = Asset(**request.json) db.session.add(asset) db.session.flush() _id = asset.id db.session.commit() return '{ "id" : %d }' % _id, 201
async def delete(self, asset_id): """Delete asset.""" with self.make_session() as session: asset = await as_future( session.query(Asset).filter(Asset.id == asset_id).first) if not asset: self.finish({'message': 'No Asset found!'}) session.delete(asset) session.commit() self.write({ 'message': 'The item has been deleted', 'asset': Asset.serialize(asset) })
def download_commit(self): commit_id = self.request.POST['commit_id'] site = self._get_site() owner, repo = site.repo.split('/') git = GitClient(owner, repo, site.github_token) res = git.get_repos('/zipball/%s' % commit_id, binary=True) res = StringIO.StringIO(res) site_zip = zipfile.ZipFile(res, 'r') assets = _extract_zipped_files(site_zip, '') assets = [ Asset(id=a[0], content=a[1], fullpath=a[2], mime=a[3]) for a in assets ] ndb.put_multi(assets) site = self._get_site() site.current_sha = commit_id site.put()
def _save_asset(self, path, content, uploaded=None, mime=None): global _code_cache if uploaded is not None: if uploaded.filename.endswith('zip'): site_zip = zipfile.ZipFile(uploaded.file, 'r') assets = _extract_zipped_files(site_zip, path if path != '/' else '') else: mime = mimeutil.get_mime(uploaded.filename) fullpath, mime = _get_fullpath(path, mime) assets = [(path, self.request.get('asset'), fullpath, mime)] else: fullpath, mime = _get_fullpath(path, mime) assets = [(path, content, fullpath, mime)] assets = [ Asset(id=a[0], content=a[1], fullpath=a[2], mime=a[3]) for a in assets ] ndb.put_multi(assets) _code_cache = {}
def post_asset(db): assettypeid = request.forms.getunicode('assettypeid') asiden = request.forms.getunicode('asiden') asorgan = request.forms.getunicode('asorgan') bill_dt = request.forms.getunicode('bill_dt') repayment_dt = request.forms.getunicode('repayment_dt') credit_limit = request.forms.getunicode('credit_limit') year_rate = request.forms.getunicode('year_rate') comment = request.forms.getunicode('comment') print(assettypeid, asiden, asorgan) if assettypeid == '' or asiden == '' or asorgan == '': redirect('/asset') asset = Asset(asiden=asiden, asorgan=asorgan, bill_dt=bill_dt, repayment_dt=repayment_dt, credit_limit=credit_limit, year_rate=year_rate, comment=comment) db.add(asset) redirect("/asset")
def load_asset_content(fullpath): asset = Asset.query(Asset.fullpath == fullpath).fetch(1) if asset: return asset[0].content
def setUp(self): app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://%s:%s@%s/%s' % (\ TEST_DB_CONFIG['username'],\ TEST_DB_CONFIG['password'],\ TEST_DB_CONFIG['server'],\ TEST_DB_CONFIG['db']) db.init_app(app) with app.app_context(): db.create_all() asset_a = Asset(model='Mac Book Pro', company='NCCC', asset_tag='a', asset_state='已报废', sn='sn1', user='******', location='sh', type='pc') asset_b = Asset(model='Mac Book Pro', company='NCCC', asset_tag='b', asset_state='已报废', sn='sn2', user='******', location='sh', type='laptop') asset_c = Asset(model='Mac Book Pro', company='NCCC', asset_tag='c', asset_state='已报废', sn='sn3', user='******', location='sh', type='laptop') asset_d = Asset(model='Mac Book Pro', company='NCCC', asset_tag='d', asset_state='', sn='sn4', user='******', location='bj', type='pc') asset_e = Asset(model='Mac Book Pro', company='NCCC', asset_tag='e', asset_state='在用', sn='sn5', user='******', location='bj', type='ipad') asset_f = Asset(model='Mac Book Pro', company='NCCC', asset_tag='f', asset_state='在用', sn='sn6', user='******', location='bj', type='ipad') db.session.add_all( [asset_a, asset_b, asset_c, asset_d, asset_e, asset_f]) db.session.commit() self.app = app.test_client()
def process_data(self, parsed): """ parsed = { id: int type: str<SONG, LINK, SPOT, DEFAULT_METADATA> title: str artist: str album: str optional extra_data: Dict nullable, Extra play data extra_asset_data: Dict nullable, Extra asset data } """ assetType = 'Unknown' if parsed['type'] == 'SONG': assetType = 'Song' elif parsed['type'] == 'LINK': assetType = 'Link' elif parsed['type'] == 'SPOT': assetType = 'Spot' elif parsed['type'] == 'DEFAULT_METADATA': assetType = 'Live' new_record = False if parsed['type'] == 'DEFAULT_METADATA': asset = self._dbObj.assets.filter_by(id_by_station=-1).first() else: if 'id' in parsed: # check if asset exists q = self._dbObj.assets.filter_by(id_by_station=parsed['id']) if q.count() < 1: # if not exists then create one asset = Asset( station = self._dbObj, id_by_station = parsed['id'], type = assetType, title = parsed['title'], artist = parsed['artist'], album = parsed['album'] if 'album' in parsed else None, extra_data = json.dumps(parsed['extra_asset_data'], sort_keys=True) if 'extra_asset_data' in parsed and parsed['extra_asset_data'] != {} else None, ) new_record = True else: asset = q.first() else: # check if asset exists q = self._dbObj.assets.filter_by(title=parsed['title'], artist=parsed['artist']) if q.count() < 1: # if not exists then create one asset = Asset( station = self._dbObj, id_by_station = None, type = assetType, title = parsed['title'], artist = parsed['artist'], album = parsed['album'] if 'album' in parsed else None, extra_data = json.dumps(parsed['extra_asset_data'], sort_keys=True) if 'extra_asset_data' in parsed and parsed['extra_asset_data'] != {} else None, ) new_record = True else: asset = q.first() if new_record: self._dbSess.add(asset) # self._dbSess.commit() # TODO: Update outdated assets # check if duplicate play playq = self._dbSess.query(Play).filter(Play.asset.has(station=self._dbObj)).order_by(desc(Play.id)).limit(1) last_play = playq.first() play = Play( asset = asset, extra_data = json.dumps(parsed['extra_data'], sort_keys=True) if 'extra_data' in parsed and parsed['extra_data'] != {} else None, ) dupe = True if last_play is None: dupe = False else: if 'id' in parsed: if play.asset.id_by_station != last_play.asset.id_by_station: dupe = False else: if play.asset.title != last_play.asset.title and play.asset.artist != last_play.asset.artist: dupe = False if not dupe: # add asset to plays self._dbSess.add(play) # self._dbSess.commit() print('not last') else: print('is last') return (asset, play)