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')
Beispiel #2
0
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 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')
Beispiel #4
0
    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)
Beispiel #5
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'}
Beispiel #6
0
    def test_user(self):
        db = DBSession()
        user = db.query(User) \
            .filter(User.password == User.encryptPassword('root'), User.email == r'*****@*****.**') \
            .one()

        self.assertIsNotNone(user)
Beispiel #7
0
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
Beispiel #8
0
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}
Beispiel #9
0
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
Beispiel #10
0
 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,
Beispiel #11
0
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()
Beispiel #12
0
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()
Beispiel #13
0
 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
Beispiel #14
0
 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)
Beispiel #15
0
 def loadFeedDict(cls, feeds):
     for feed in feeds:
         guid = feed["id"]
         try:
             message = DBSession.query(Message).filter(Message.guid == guid).one()
             if _compareTime(message.updated.timetuple(),feed["updated_parsed"]) < 0:
                 message.update(title=feed["title"],
                                link=feed["link"],
                                updated=feed["updated"],
                                text=feed["summary"])
                 userMessages = DBSession.query(UserMessage).filter(UserMessage.message == message.message_id).all()
                 for userMessage in userMessages:
                     userMessage.new = True
         except NoResultFound:
             message = Message(text=feed["summary"], guid=feed["id"], **feed)
             DBSession.add(message)
             DBSession.flush()
             cls.sendMessageToAllUsers(message)
Beispiel #16
0
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()
Beispiel #17
0
    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]}))
Beispiel #18
0
    def test_some(self):
        # fields = exclude_fields(Transaction, [Transaction.user, Transaction._user_id, Transaction.expenseTagGroup_id, Transaction.incomeTagGroup_id, Transaction.expenseTagGroup, Transaction.incomeTagGroup])
        transactions = DBSession.query(Transaction).options(
            subqueryload(Transaction.incomeTagGroup).subqueryload(TagGroup.tags),
            subqueryload(Transaction.expenseTagGroup).subqueryload(TagGroup.tags)
        ).all()

        transaction_json = jsonify.encode(dict(transactions=transactions))
        parsed = json.loads(transaction_json)
        print(json.dumps(parsed, indent=2, sort_keys=True), len(transactions))
Beispiel #19
0
 def _setMol(self,molId,mol,smiles,chirality='A'):
         molDb=DBSession.query(self.ModelClass).get(int(molId)) 
         try:
             molDb.mol_struct = mol.encode('utf-8')
             molDb.chirality=chirality 
             transaction.commit()
         except IntegrityError,e:
             transaction.abort()
             log.exception(e)
             raise Exception("Unique field has been violated")
Beispiel #20
0
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'}
Beispiel #21
0
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'}
Beispiel #22
0
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()
Beispiel #23
0
 def toDict(self):
     mainMessage = DBSession.query(Message).filter(Message.message_id == self.message).one()
     author = mainMessage.author
     return dict(isNew=self.new,
                 id=self.id,
                 title=mainMessage.title, 
                 text=mainMessage.text, 
                 link=mainMessage.link,
                 updated=mainMessage.updated,
                 priority=mainMessage.priority,
                 author=dict(display_name=author.display_name,
                             email_address=author.email_address,
                             user_id=author.user_id))
Beispiel #24
0
    def test_tag(self):
        db = DBSession()

        res = db.query(func.sum(Transaction.amount).label("balance"))
        print(res.one().balance)
        print(res.filter(Transaction.amount < 0).one().balance)
        print(res.filter(Transaction.amount > 0).one().balance)

        res = db.query(Transaction) \
            .filter(Transaction.expenseTagGroup.has(TagGroup.tags.any(Tag.name.in_(["traveling", "grocery"])))) \
            .filter(Transaction.incomeTagGroup.has(TagGroup.tags.any(Tag.name.in_(["cash"]))))

        print("\n\nAll transactions with expense tags [traveling or grocery] and income tag [cash]\n")
        for r in res.all():
            print(r)

        print("\n\nAll expenses per tag\n")
        for tag in db.query(Tag).filter(Tag.type == Tag.TYPE_EXPENSE):
            print(tag.name)
            for transactions in [group.expenses.all() for group in tag.groups]:
                for transaction in transactions:
                    print(transaction)
Beispiel #25
0
    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()
Beispiel #26
0
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}
Beispiel #27
0
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}
Beispiel #28
0
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}
Beispiel #29
0
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}
Beispiel #30
0
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
Beispiel #31
0
 def markOld(cls, id):
     userMessages = DBSession.query(UserMessage).get(id)
     userMessages.new = False
Beispiel #32
0
 def test_query_obj(self):
     obj = DBSession.query(self.klass).filter_by(**self.attrs).one()
     for key, value in self.attrs.iteritems():
         assert_equals(getattr(obj, key), value)
Beispiel #33
0
 def sendMessageToAllUsers(cls, message):
     users = DBSession.query(User).all()
     for user in users:
         userMessage = cls(user, message)
         DBSession.add(userMessage)
Beispiel #34
0
 def parent(self):
     if self.parent_id is not None:
         return DBSession.query(Message).get(self.parent_id)
     else:
         return None
Beispiel #35
0
 def by_pid(cls, petition_id):
     return DBSession.query(cls).filter_by(petition_id=petition_id).first()
Beispiel #36
0
 def author(self):
     if self.author_id is not None:
         return DBSession.query(User).filter(User.user_id==self.author_id).one()
     else:
         return _InnectusUser