def testClone(self): r=DBSession().query(Rxn).first() ok_(r) newr=r.clone() ok_(newr) DBSession().add(newr) transaction.commit()
def test_user(self): db = DBSession() user = db.query(User) \ .filter(User.password == User.encryptPassword('root'), User.email == r'*****@*****.**') \ .one() self.assertIsNotNone(user)
def gridInsert(self, modelObjects,row): rack = modelObjects[Rack] dbRack = None vial = modelObjects[Vial] if rack.rack_barcode: dbRack = Rack.byBarcode(rack.rack_barcode) if dbRack is None: dbRack = Rack() dbRack.rack_barcode = rack.rack_barcode if vial.well: dbRack.rack_type_id = vial.well.rack_type_id DBSession().add(dbRack) DBSession().flush() mol=modelObjects[Mol] mol=mergeMol(mol) lot=modelObjects[Lot] if lot.lot_id is None: mol.addLot(lot, 0) else: lot=DBSession().merge(lot) lot.vials.append(vial) if dbRack: vial.vial_rack_id = dbRack.rack_id vial.vial_lot_aliquot_no = len(lot.vials) if lot.lot_submitter_id == None: lot.lot_submitter_id = request.identity['user'].user_id if hasattr(mol,'mol_reg_id') and not row.has_key('verify'): if mol.mol_reg_id is None: mol.setAltId(row['prefix']) DBSession().flush() return mol, lot, vial, dbRack
def testReagentRegistration(self): """Authenticated users can register reagents""" numBeforeDbLots = len(DBSession.query(ReagentLot).all()) self.doRegistration('reagents', 'app/tests/data/molregtest.sdf') self.checkGridPostReg('reagents') numAfterDbLots = len(DBSession.query(ReagentLot).all()) ok_(numAfterDbLots == numBeforeDbLots + 2, 'Failed to register 2 new lots')
def gridData(self): columns=self.rptCfg.uicolumns idName=self.rptCfg.getId() results = [] reqs = DBSession().query(Request).select_from(outerjoin(Request,RequestItem)) childrenDisp = [] dispense = reqs.filter(RequestItem.request_item_dispense_date == None).order_by(Request.request_id).all() for row in dispense: # if row.hasOpenItems() or len(row.items)==0: rowData = [] for col in columns: val = getattr(row,col.id,None) if isinstance(val,datetime): val = val.strftime('%m/%d/%Y') rowData.append(val) childrenDisp.append({'id':row.__dict__[idName], 'data':rowData}) childrenComplete = [] complete = reqs.filter(RequestItem.request_item_dispense_date > (datetime.now()-timedelta(days=1))).order_by(Request.request_id).all() for row in complete: if not row.hasOpenItems(): rowData = [] for col in columns: val = getattr(row,col.id,None) if isinstance(val,datetime): val = val.strftime('%m/%d/%Y') rowData.append(val) childrenComplete.append({'id':row.__dict__[idName], 'data':rowData}) results.append(dict(id='open',data=['Open Requests'],children=childrenDisp)) results.append(dict(id='closed',data=['Recently Closed'],children=childrenComplete)) results.append(dict(id='search',data=['Search'])) return results
def setAltId(self,value): try: regConfig = DBSession().query(MolRegConfig).get(value) self.mol_reg_id = regConfig.getRegId() except Exception,e: log.exception(e) raise Exception("Configure your registry id prefix first using the 'Configure' link.")
def gridUpdate(self, modelObjects,row): rpt=Report(self.rptCfg) pkCol=rpt._rptCfg._columns[rpt.getIdName()] modelClass=pkCol.modelClass id=getattr(modelObjects[modelClass], rpt.getIdName()) fileRow=DBSession().query(FileRow).get(id) fileRow.pickle(rpt.convertToUI(*modelObjects.values())) return None
def get_books(): db_session = DBSession() books = db_session.query(Books).order_by(desc(Books.id)).all() for b in books: yield {'id': b.id, 'name': b.name} db_session.close()
def get_types(): db_session = DBSession() types = db_session.query(Types).order_by(desc(Types.id)).all() for i in types: yield {'id': i.id, 'name': i.name} db_session.close()
def gridInsert(self, modelObjects,row): lot = DBSession().query(Lot).get(modelObjects[Vial].vial_lot_id) mol = lot.mol vial = modelObjects[Vial] vial.vial_lot_aliquot_no = lot.getVialCount() + 1 DBSession().add(modelObjects[Vial]) DBSession().flush() return mol,lot,vial
def clear(self,parentId): retVal={} try: parent = DBSession().query(ReagentLotLocation).get(parentId) parent.lots=[] except Exception,e: log.exception(e) retVal={'error':'Parent not found'}
def checkOutLot(self,barcode,userId,pbarId=None): retVal = {} try: lot = DBSession().query(ReagentLot).filter(ReagentLot.lot_barcode==barcode.strip()).one() #@UndefinedVariable : lot_barcode comes from SQLAlchemy reflection lot.lot_current_user_id = int(userId) retVal = {'success': "Successfully checked out " + lot.lot_barcode} except Exception,e: log.debug(e) retVal = {'error': 'barcode ' + barcode + ' not found in inventory'}
def get_authors(): db_session = DBSession() authors = db_session.query(Authors).order_by(desc(Authors.id)).all() for i in authors: yield {'id': i.id, 'fullname': i.fullname} db_session.close()
def sendMessageToUser(cls, message, userId): if str(userId) == "#": user = _InnectusUser _sendMessageViaMail(message, user) else: user = DBSession.query(User).filter(User.user_id == userId).one() #_sendMessageViaMail(message, user) userMessage = cls(user, message) DBSession.add(userMessage)
def gridDelete(self,modelObjects): req = DBSession().query(Request).get(modelObjects[Request].request_id) if len(req.items) == 0: DBSession().delete(req) elif req.hasOpenItems() and not req.hasClosedItems(): for i in req.items: DBSession().delete(i) DBSession().delete(req) else: raise ClientException("Can't delete a request with completed items")
def disposeLot(self,barcode,userId,pbarId=None): retVal = {} try: lot = DBSession().query(ReagentLot).filter(ReagentLot.lot_barcode==barcode.strip()).one() #@UndefinedVariable : lot_barcode comes from SQLAlchemy reflection lot.lot_is_disposed = 'Y' lot.lot_current_user_id = None retVal = {'success': 'Marked as disposed ' + lot.lot_barcode} except Exception,e: log.debug(e) retVal = {'error': 'barcode ' + barcode + ' not found in inventory'}
def link(self,parentId,childBarcode): retVal={'success': 'Successfully linked reagent'} try: child = DBSession().query(ReagentLot).filter(ReagentLot.lot_barcode==childBarcode).one() child.loc = DBSession().query(ReagentLotLocation).get(parentId) child.aud_modified_date = datetime.datetime.now() child.lot_current_user_id = None except Exception,e: log.exception(e) retVal={'error':"Could not find barcode " + childBarcode}
def setUp(self): ''' Need a row of data in the login audit table ''' super(TestUserAdministration, self).setUp() aud = AuditLogin(dict(REMOTE_ADDR='127.0.0.1'), dict(user_name='chemadmin')) result = AuditLoginResult.get('LOGIN_SUCCESS') aud.login_result = result log.debug(aud in DBSession()) DBSession.add(aud) transaction.commit()
def gridUpdate(self, modelObjects,row): request = modelObjects[Request] requestItem = modelObjects[RequestItem] mol = modelObjects[Mol] mols = DBSession().query(Mol).filter(Mol.mol_reg_id==mol.mol_reg_id).all() if len(mols)==0: raise ClientException(mol.mol_reg_id + " was not found in the database") mol = mols[0] item = DBSession().merge(requestItem) item.mol = mol return mol,item,request
def get_users(): db_session = DBSession() users = db_session.query(User).order_by(desc(User.id)).all() for i in users: yield {'id': i.id, 'username': i.username, 'email': i.email, 'is_admin': i.is_admin, 'confirmed_at': str(i.confirmed_at), 'is_active': i.is_active} db_session.close()
def testReagentMolStereoReg(self): """Different stereoisomers can be registered as individual molecules""" numBeforeDbMols = len(DBSession.query(ReagentMol).all()) self.doRegistration('reagents', 'app/tests/data/stereo_test.sdf') self.checkGridPostReg('reagents') numAfterDbMols = len(DBSession.query(ReagentMol).all()) # We register 11 molecules, but only 10 distinct lots. One of the molecules is present twice # in the sd file. That molecule is drawn as enantiomers but without the chiral flag set, so that # the molecules are treated as being relative stereochemistry and consequently the same. # So: We should only see 10 new lots here. log.debug('num after db mols is ' + str(numAfterDbMols)) ok_(numAfterDbMols == numBeforeDbMols + 10, 'Failed to register 10 new stereo mols')
def sendMessage(title, text, recipients, parentId=None, authorId=None): from tg import request authorId = None if authorId is None: authorId = request.identity['user'].user_id msg = Message(title=title, text=text, author_id=authorId, parent_id=parentId) DBSession.add(msg) DBSession.flush() UserMessage.sendMessageToUsers(msg, recipients)
async def count(petition_id: str): p = Petition.by_pid(petition_id) if not p: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="Petition not Found") if p.status != STATUS.CLOSED: raise HTTPException( status_code=HTTP_424_FAILED_DEPENDENCY, detail="Petition still open" ) p.count = zencode(CONTRACTS.COUNT_PETITION, keys=p.tally, data=p.petition) DBSession.commit() return json.loads(p.count)
def updateNode(self,id,name,parentId): retVal = {} try: folder = DBSession().query(sar.Folder).get(id) # if this is a root folder, we don't allow any changes if folder.parentFolder is None: raise ClientException("You may not rename this folder") folder.name = name folder.parent_folder_id = parentId DBSession().flush() retVal=dict(msg='success') except ClientException, ce: # re-raise it raise ce
def gridInsert(self, modelObjects,row): mol = modelObjects[Mol] mol = Mol.byRegId(mol.mol_reg_id) if mol is None: raise ClientException(row['mol_reg_id'] + " was not found in the database") req = modelObjects[Request] req = DBSession().merge(req) req.requested_by_id = request.identity['user'].user_id item = modelObjects[RequestItem] req.items.append(item) item.request_item_mol_id = mol.mol_id DBSession().add(item) DBSession().flush() return mol,item,req
def setUp(self): super(TestStructureSearch,self).setUp() org=DBSession.query(ReagentVendor).first() for name, smiles in self.smilesToReg.items(): mol = ReagentMol(toMolFromSmiles(smiles)) mol.mol_name = name submitter = User.by_user_name('chemadmin') lot = ReagentLot() lot.lot_submitter_id = submitter.user_id lot.lot_source_org_id = org.vendor_id mol.addLot(lot, 0) DBSession.add(mol) DBSession.flush()
def get_user(user_id): if not user_id: return {'status': 'Error'} else: db_session = DBSession() user = db_session.query(User).filter(User.id == user_id).all() if not user: return {'message': 'user not found'} user = [d.to_dict() for d in user] db_session.close() return {'user': user}
def delete_book(book_id): if not (book_id): return {'status': 'error'} db_session = DBSession() book = db_session.query(Books).get(book_id) db_session.delete(book) db_session.commit() db_session.close() return {'status': 'OK'}
def delete_outhor(author_id): if not (author_id): return {'status': 'error'} print(type(author_id)) db_session = DBSession() outhor = db_session.query(Authors).get(author_id) db_session.delete(outhor) db_session.commit() db_session.close() return {'status': 'OK'}
def get_book(book_id): if not book_id: return {'status': 'Error'} else: db_session = DBSession() book = db_session.query(Books).filter(Books.id == book_id).all() if not book: return {'message': 'book not found'} book = [d.to_dict() for d in book] db_session.close() return {'book': book}
def test_concat(self): user = DBSession.query(User).filter(User.id == "d09b9111-70a0-43c0-9373-aba10f2af592").all()[0] # balanceQuery = DBSession.query(func.sum(Transaction.amount).label("balance")).with_parent(user).\ # filter(Transaction.date > datetime.utcnow()) tags = DBSession.query(Tag).with_parent(user).filter(Tag.type == Tag.TYPE_INCOME) balances = [] # for tag in tags: balance = DBSession.query(Transaction.id, func.sum(Transaction.amount).label("balance")).with_parent(user) balances = DBSession.query(Tag.name, balance.c.balance). \ filter(Transaction.incomeTagGroup.has(TagGroup.tags.any(Tag.id == balance))) balances.append(balances) print(balances)
def get_type(type_id): if not type_id: return {'status': 'Error'} else: db_session = DBSession() book_type = db_session.query(Types).filter(Types.id == type_id).all() if not book_type: return {'message': 'type not found'} book_type = [d.to_dict() for d in book_type] db_session.close() return {'type': book_type}
def updateLeaf(self,id,name,parentId): retVal = {} try: file = DBSession().query(self.LeafClass).get(id) file.name = name if hasattr(file, 'folder_id'): file.folder_id = parentId elif hasattr(file, 'groupId'): file.groupId = parentId else: raise KeyError('') DBSession().flush() retVal=dict(msg='success') except Exception,e: retVal=dict(error = "Move failed")
def create_author(data): db_session = DBSession() new_author = Authors(**data) try: db_session.add(new_author) db_session.commit() result = {'status': 'OK', 'author': data['fullname']} except: db_session.rollback() result = {'status': 'error'} db_session.close() return result
def get_author(author_id): if not author_id: return {'status': 'Error'} else: db_session = DBSession() book_author = db_session.query(Authors).filter( Authors.id == author_id).all() if not book_author: return {'message': 'type not found'} book_author = [d.to_dict() for d in book_author] db_session.close() return {'author': book_author}
def gridUpdate(self, modelObjects, row): o=modelObjects[Group] dbgroup = DBSession.query(Group).get(int(o.group_id)) if dbgroup.group_name =='admin': raise ClientException("You can't change the " + dbgroup.group_name + " group's information.") d=DBSession().merge(o) return d,
def getContacts(): users = DBSession.query(User).all() retVal = [dict(id=_InnectusUser.user_id,value=_InnectusUser.user_name)] for user in users: retVal.append(dict(id=user.user_id,value=user.user_name)) return retVal
def checkInLot(self,barcode,userId,pbarId=None): retVal = {} msg = '' try: lot = DBSession().query(ReagentLot).filter(ReagentLot.lot_barcode==barcode.strip()).one() #@UndefinedVariable : lot_barcode comes from SQLAlchemy reflection msg += ', place in <b>bin</b> ' + str(lot.loc.loc_name) msg += ', <b>shelf</b> ' + str(lot.loc.loc_shelf) msg += ', <b>cabinet</b> ' + str(lot.loc.loc_cabinet) msg += ', <b>room</b> ' + str(lot.loc.loc_room) if lot.lot_current_user_id == None: retVal = {'error': lot.lot_barcode + ' already checked in ' + msg} else: lot.lot_current_user_id = None retVal = {'success': lot.lot_barcode + ' has been checked in ' + msg} except Exception,e: log.debug(e) retVal = {'error': 'barcode ' + barcode + ' not found in inventory'}
def gridUpdate(self, modelObjects,row): mol = modelObjects[Mol] lot = DBSession().merge(modelObjects[Lot]) vial = DBSession().merge(modelObjects[Vial]) rack = modelObjects[Rack] dbRack = None if rack.rack_barcode: dbRack = Rack.byBarcode(rack.rack_barcode) if dbRack is None: dbRack = Rack() dbRack.rack_barcode = rack.rack_barcode if vial.well: dbRack.rack_type_id = vial.well.rack_type_id DBSession().add(dbRack) DBSession().flush() vial.vial_rack_id = dbRack.rack_id return mol,lot,vial,dbRack
def _query(self): """ Generate a SQL query that retrieves data corresponding to the model classes in the XML config. @return: SQLAlchemy query @rtype: sqlalchemy.orm.query.Query """ clist=self._rptCfg.classlist() q=DBSession().query(*clist) for c in clist[1:]: onclause = self._rptCfg._onclause.get(c, None) if self._rptCfg.isouterjoin(c): q=q.outerjoin((c, onclause)) else: q=q.join((c, onclause)) return q
def delete_type(type_id): if not (type_id): return {'status': 'error'} db_session = DBSession() db_session.query(Types).filter(Types.id == type_id).delete() db_session.commit() db_session.close() return {'status': 'OK'}
def update_user(user_id, data): data = {k: data[k] for k in data if k in ['username', 'password', 'new_password', 'email']} db_session = DBSession() user = db_session.query(User).get(user_id) password = sha512(data['password'].encode('utf-8')).hexdigest() if (not user or user.password != password): return {'status': 'error'} if (user.password == password and data['new_password'] != ''): new_password = sha512( data['new_password'].encode('utf-8')).hexdigest() user.username = data['username'] user.email = data['email'] user.password = new_password elif (user.password == data['password'] and data['new_password'] == ''): user.username = data['username'] user.email = data['email'] user.password = data['password'] else: return {'status': 'error'} db_session.commit() db_session.close() return {'status': 'OK', 'user': user_id}
def getUserMessagesById(cls, userId, newOnly = False): messages = [] userMessages = DBSession.query(UserMessage).filter(UserMessage.user == userId) if newOnly: userMessages = userMessages.filter(UserMessage._new == 1) userMessages = userMessages.all() for userMessage in userMessages: messages.append(userMessage.toDict()) return messages
def test_deref(self): trans = DBSession.query(Transaction).options( subqueryload(Transaction.incomeTagGroup).subqueryload(TagGroup.tags), subqueryload(Transaction.expenseTagGroup).subqueryload(TagGroup.tags) ).options(defer('_user_id')) tran = trans.first() print(tran) print(json.dumps({'fsd': tran.incomeTagGroup.tags[0]}))
def delete_user(user_id, data): if not user_id: return{'status': 'error'} db_session = DBSession() user = db_session.query(User).get(user_id) password = sha512(data['password'].encode('utf-8')).hexdigest() if (not user or data['username'] != user.username or password != user.password): return{'status': 'error'} db_session.query(User).filter(User.id == user_id).delete() db_session.commit() db_session.close() return {'status': 'OK'}
def create_book(data): db_session = DBSession() new_book = Books(name=data['name'], type_id=data['type_id'], author_id=data['author_id'], book_translator=data['book_translator']) try: db_session.add(new_book) db_session.commit() result = {'status': 'OK', 'book': data['name']} except: db_session.rollback() result = {'status': 'error'} db_session.close() return result
async def sign(petition_id: str, signature: PetitionSignature, expand: bool = False): p = Petition.by_pid(petition_id) if not p: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="Petition not Found") try: petition = zencode( CONTRACTS.ADD_SIGNATURE, keys=p.petition, data=signature.json() ) except Error as e: debug(e) raise HTTPException( status_code=HTTP_424_FAILED_DEPENDENCY, detail="Petition signature is duplicate or not valid", ) p.petition = petition DBSession.commit() return p.publish(expand)
def create(petition: PetitionIn, expand: bool = False, token: str = Security(security)): if not allowed_to_control_petition(token): raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authorized to control this petition", ) try: petition_object, ci_uid = _generate_petition_object(petition) except FileNotFoundError: raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail="Credential issuer is not validated, missing info/keys/credentials", ) except ConnectionError: raise HTTPException( status_code=HTTP_424_FAILED_DEPENDENCY, detail="Credential issuer server is not available", ) p = Petition( petition=petition_object, petition_id=petition.petition_id, credential_issuer_uid=ci_uid, credential_issuer_url=petition.credential_issuer_url, ) try: DBSession.add(p) DBSession.commit() except IntegrityError: DBSession.rollback() raise HTTPException( status_code=HTTP_409_CONFLICT, detail="Duplicate Petition Id" ) return p.publish(expand)
async def tally( petition_id: str, authorizable_attribute: TallyBody = Body(...), expand: bool = False, token: str = Security(security), ): if not allowed_to_control_petition(token): raise HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authorized to control this petition", ) p = Petition.by_pid(petition_id) if not p: raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="Petition not Found") petition = Bunch( petition_id=petition_id, credential_issuer_url=p.credential_issuer_url, authorizable_attribute_id=authorizable_attribute.authorizable_attribute_id, ) credential = _retrieve_credential(petition) p.tally = zencode(CONTRACTS.TALLY_PETITION, keys=credential, data=p.petition) DBSession.commit() return p.publish(expand)
def remove_session(ex=None): DBSession.expire_all()
# -*- coding: utf-8 -*- import os import re import paramiko from sqlalchemy.orm.exc import NoResultFound from app.tasks import app from celery.schedules import crontab from celery.utils.log import get_task_logger from app.conf.config import CONFIG from app.model import DBSession from app.model.file import File from app.util.dbutil import * session = DBSession() logger = get_task_logger(__name__) ssh = paramiko.SSHClient() @app.on_after_configure.connect def set_up_periodic_tasks(sender, **kwargs): # 每10s执行一次任务 sender.add_periodic_task(10.0, scan.s(), name='scan every 10 seconds') sender.add_periodic_task(10.0, check.s(), name='check every 10 seconds') @app.task(name='app.tasks.scan.scan') def scan(): files = os.listdir(CONFIG['DIR_TO_SCAN']) for filename in files: if not os.path.isdir(CONFIG['DIR_TO_SCAN'] + filename):
def create_type(data): db_session = DBSession() book_type = db_session.query(Types).filter( Types.name == data['name']).first() if book_type: return {'status': 'error', 'message': 'message'} new_type = Types(name=data['name']) try: db_session.add(new_type) db_session.commit() result = {'status': 'OK', 'type': data['name']} except: db_session.rollback() result = {'status': 'error'} db_session.close() return result
def by_pid(cls, petition_id): return DBSession.query(cls).filter_by(petition_id=petition_id).first()
def create_user(data): time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') db_session = DBSession() print(data) user = db_session.query(User).filter( User.email == data['email']).first() if user: return {'status': 'error', 'message': 'message'} password = sha512(data['password'].encode('utf-8')).hexdigest() new_user = User( username=data['username'], password=password, email=data['email'], confirmed_at=time, is_active=True, is_admin=data['is_admin']) try: db_session.add(new_user) db_session.commit() result = {'status': 'OK', 'user': data['username']} except: db_session.rollback() result = {'status': 'error'} db_session.close() return result
from flask_admin.contrib.sqla import ModelView from app.model import (DBSession, User, Types, Authors, Books, Notes) from wtforms.fields import PasswordField # from wtforms import TextAreaField ModelView.page_size = 1000 ModelView.create_modal = True ModelView.edit_modal = True admin_session = DBSession() class UserViewTemplate(ModelView): column_list = [ 'id', 'username', 'email', 'password', 'is_active', 'is_admin' ] column_exclude_list = ['password'] form_overrides = dict(password=PasswordField) column_searchable_list = ['username', 'email'] class TypesViewTemplate(ModelView): column_list = ['id', 'name'] column_searchable_list = ['id', 'name'] class AuthorsViewTemplate(ModelView): column_list = ['id', 'fullname'] column_searchable_list = ['id', 'fullname'] class BooksViewTemplate(ModelView):