def index(self, page=1, *args, **kw): pains = DBSession.query(PAINS3) dsc = True tmpl = '' pname = 'pains' userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=userid).first() threshold = float(user.threshold)/100.0 items = user.items_per_page order = "id" if kw: for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': order = v if dsc: pains = pains.order_by(desc(order).nullslast()) else: pains = pains.order_by((order)) page_url = paginate.PageURL_WebOb(request) currentPage = paginate.Page(pains, page, url=page_url, items_per_page=items) pains = pains.all() return dict(length=len(pains), pains=currentPage.items, currentPage=currentPage, tmpl=tmpl, page='pains3', pname=pname)
def edit(self, id): pname = request.environ['PATH_INFO'].split('/')[1] id = int(id) scompound = DBSession.query(SCompound).get(id) alltags = [tag for tag in DBSession.query(Tags).order_by('name').all()] etap_max = scompound.effort[-1].etap_max etap = scompound.effort[-1].etap principals = DBSession.query(Group).get(3) owners = DBSession.query(Group).get(2) come_from = request.headers['Referer'] try: tags = [tag for tag in scompound.mol.tags] except Exception: tags = [scompound.mol.tags] pass try: files = scompound.filename except Exception: files = None pass return dict(scompound=scompound, tags=tags, alltags=alltags, files=files, etap=etap, etap_max=etap_max, users=principals.users, owners=owners.users, come_from=come_from, page='kierownik', pname=pname)
def editlist(self, *args, **kw): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter(User.user_name == userid).first() users = DBSession.query(User).order_by(User.display_name).all() id = args[0] mylist = DBSession.query(UserLists).get(id) assert mylist.tg_user_id == user.user_id, u"Brak uprawnien edycji" if kw: if not (kw.has_key('name') and kw['name'] != u''): flash(l_(u'Name is required'), 'error') else: if kw.has_key('name') and kw['name'] != mylist.name: mylist.name=kw['name'] # if kw.has_key('table') and kw['table'] != mylist.table: # mylist.table=kw['table'] if kw.has_key('notes') and kw['notes'] != mylist.notes: mylist.notes = kw['notes'] if kw.has_key('permitusers') and kw['permitusers'] != u'': if isinstance(kw['permitusers'], (list, tuple)): permitusers = [usr for usr in users if usr.user_name in kw['permitusers']] else: permitusers = [usr for usr in users if usr.user_name == kw['permitusers']] if permitusers != mylist.permitusers: mylist.permitusers = permitusers DBSession.flush() flash(l_(u'Task completed successfully')) redirect(request.headers['Referer']) return dict(mylist=mylist, user=user, users=users, page='index', pname=None)
def index(self): """Main site for project.""" userid = request.identity['repoze.who.userid'] projects = DBSession.query(Projects).all() user = DBSession.query(User).filter_by(user_name=userid).first() perms = [p.permission_name for p in list(user.permissions)] return dict(page='index', userid=userid, projects=projects, perms=perms, pname=project_name)
def check(self): compounds = DBSession.query(Compound).all() pains1 = DBSession.query(PAINS1).all() pains2 = DBSession.query(PAINS2).all() pains3 = DBSession.query(PAINS3).all() ID = '' for compound in compounds: m = Chem.MolFromSmiles(str(compound.structure)) mol = Chem.AddHs(m) for p1 in pains1: patt = Chem.MolFromSmarts(str(p1.structure)) if patt: if mol.HasSubstructMatch(patt): compound.pains1 = p1 else: flash(l_(u'Pattern error'), 'error') redirect(request.headers['Referer']) for p2 in pains2: patt = Chem.MolFromSmarts(str(p2.structure)) if patt: if mol.HasSubstructMatch(patt): compound.pains2 = p2 else: flash(l_(u'Pattern error'), 'error') redirect(request.headers['Referer']) for p3 in pains3: patt = Chem.MolFromSmarts(str(p3.structure)) if patt: if mol.HasSubstructMatch(patt): compound.pains3 = p3 else: flash(l_(u'Pattern error'), 'error') redirect(request.headers['Referer']) flash(l_(u'Task completed successfully')) redirect(request.headers['Referer'])
def index2(self, page=1, *args, **kw): pname = request.environ['PATH_INFO'].split('/')[1] from datetime import timedelta now = datetime.now() one_day = timedelta(days=1) history = DBSession.query(History).order_by( desc('History.id')).limit(20).all() phistory = DBSession.query(PHistory).order_by( desc('PHistory.id')).limit(20).all() shistory = DBSession.query(SHistory).order_by( desc('SHistory.id')).limit(20).all() lhistory = DBSession.query(LHistory).order_by( desc('LHistory.id')).limit(20).all() rhistory = DBSession.query(RHistory).order_by( desc('RHistory.id')).limit(20).all() hist = history + phistory + shistory + lhistory + rhistory hist = sorted(hist, key=lambda hist: hist.date, reverse=True)[0:30] tmpl = '' return dict(history=hist, tmpl=tmpl, one_day=one_day, now=now, page='kierownik', pname=pname)
def addlist(self, *args, **kw): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter(User.user_name == userid).first() users = DBSession.query(User).order_by(User.display_name).all() allproj = DBSession.query(Projects).order_by('id').all() if args and len(args) >= 2: ntable = args[0] get_args = args[1:] else: ntable, get_args = [None, ()] if kw: if not (kw.has_key('name') and kw['name'] != u''): flash(l_(u'Name is required'), 'error') redirect(request.headers['Referer']) elif not (kw.has_key('table') and kw['table'] != u''): flash(l_(u'Table is required'), 'error') redirect(request.headers['Referer']) elif not (kw.has_key('project') and kw['project'] != u''): flash(l_(u'Project is required'), 'error') redirect(request.headers['Referer']) else: lista = UserLists() lista.name = kw['name'] lista.table = kw['table'] lista.pname = kw['project'] if kw.has_key('notes') and kw['notes'] != u'': lista.notes = kw['notes'] if kw.has_key('permitusers') and kw['permitusers'] != u'': if isinstance(kw['permitusers'], (list, tuple)): permitusers = [ usr for usr in users if usr.user_name in kw['permitusers'] ] else: permitusers = [ usr for usr in users if usr.user_name == kw['permitusers'] ] lista.permitusers = permitusers if kw.has_key('argv') and kw['argv'] != u'': elements = [] for arg in kw['argv']: elements.append(arg) import pickle lista.elements = pickle.dumps(elements) user.lists.append(lista) DBSession.add(lista) DBSession.flush() flash(l_(u'Task completed successfully')) redirect(request.headers['Referer']) return dict(user=user, allproj=allproj, users=users, page='index', ntable=ntable, get_args=get_args, pname=None)
def index(self, page=1, *args, **kw): from sqlalchemy import or_ tmpl = '' userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=userid).first() items = user.items_per_page pname = 'pains' pains = DBSession.query(Compound).filter(or_(Compound.pains1.has(), Compound.pains2.has(), Compound.pains3.has())).order_by(desc('gid')) page_url = paginate.PageURL_WebOb(request) currentPage = paginate.Page(pains, page, url=page_url, items_per_page=items) return dict(page='pains', pname=pname, pains=currentPage.items, currentPage=currentPage, tmpl=tmpl)
def index(self, page=1, *args, **kw): pname = request.environ['PATH_INFO'].split('/')[1] from datetime import timedelta now=datetime.now() one_day=timedelta(days=1) history = DBSession.query( History).filter(History.project.any(Projects.name==pname)).order_by(desc('History.id')).limit(20).all() phistory = DBSession.query( PHistory).filter(PHistory.project.any(Projects.name==pname)).order_by(desc('PHistory.id')).limit(20).all() shistory= DBSession.query( SHistory).filter(SHistory.project.any(Projects.name==pname)).order_by(desc('SHistory.id')).limit(20).all() lhistory= DBSession.query( LHistory).filter(LHistory.project.any(Projects.name==pname)).order_by(desc('LHistory.id')).limit(20).all() hist = history +phistory + shistory + lhistory hist = sorted(hist, key=lambda hist: hist.date, reverse=True)[0:30] tmpl = '' return dict(history=hist, tmpl=tmpl, one_day=one_day, now=now, page='kierownik', pname=pname)
def test_query_obj(self): """Model objects can be queried""" obj = DBSession.query(self.klass).one() print str(obj.__class__.__name__) if obj.__class__.__name__ != "Compound": for key, value in self.attrs.items(): eq_(getattr(obj, key), value)
def start(self): """ Home page for authorized users. """ from tg.predicates import not_anonymous if not not_anonymous(): flash(l_(u'Permission is not sufficient for this user'), 'error') redirect('/') userid = request.identity['repoze.who.userid'] projects = DBSession.query(Projects).order_by('id').all() user = DBSession.query(User).filter_by(user_name=userid).first() perms = list(user.permissions) perms_names = [p.permission_name for p in perms] user_projects = [project for project in projects if project.name in perms_names] # flash(l_(u'Alpha version. Please send error reporting to: [email protected]. \t\t :)'), 'warning') return dict(page='start', projects=user_projects, pname=None)
def users(self, page=1, *args, **kw): """ Users Managment. """ users = DBSession.query(User) page_url = paginate.PageURL_WebOb(request) tmpl = '' dsc = True order = 'user_id' if kw: if 'desc' in kw and kw['desc'] != u'': if kw['desc'] != u'1': dsc = False if 'order_by' in kw and kw['order_by'] != u'': order = kw['order_by'] if dsc: users = users.order_by(desc(order).nullslast()) else: users = users.order_by((order)) currentPage = paginate.Page(users, page, url=page_url, items_per_page=30) return dict(page='index', currentPage=currentPage, tmpl=tmpl, pname=None)
def addlist(self, *args, **kw): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter(User.user_name == userid).first() users = DBSession.query(User).order_by(User.display_name).all() allproj = DBSession.query(Projects).order_by('id').all() if args and len(args) >= 2: ntable = args[0] get_args = args[1:] else: ntable, get_args = [None, ()] if kw: if not (kw.has_key('name') and kw['name'] != u''): flash(l_(u'Name is required'), 'error') redirect(request.headers['Referer']) elif not (kw.has_key('table') and kw['table'] != u''): flash(l_(u'Table is required'), 'error') redirect(request.headers['Referer']) elif not (kw.has_key('project') and kw['project'] != u''): flash(l_(u'Project is required'), 'error') redirect(request.headers['Referer']) else: lista = UserLists() lista.name = kw['name'] lista.table = kw['table'] lista.pname = kw['project'] if kw.has_key('notes') and kw['notes'] != u'': lista.notes = kw['notes'] if kw.has_key('permitusers') and kw['permitusers'] != u'': if isinstance(kw['permitusers'], (list, tuple)): permitusers = [usr for usr in users if usr.user_name in kw['permitusers']] else: permitusers = [usr for usr in users if usr.user_name == kw['permitusers']] lista.permitusers = permitusers if kw.has_key('argv') and kw['argv'] != u'': elements = [] for arg in kw['argv']: elements.append(arg) import pickle lista.elements = pickle.dumps(elements) user.lists.append(lista) DBSession.add(lista) DBSession.flush() flash(l_(u'Task completed successfully')) redirect(request.headers['Referer']) return dict(user=user, allproj=allproj, users=users, page='index', ntable=ntable, get_args=get_args, pname=None)
def mylists(self, page=1, *args, **kw): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter(User.user_name == userid).first() mylists = user.lists import pickle as pcl dsc = True tmpl = '' selection = None order = "id" try: if kw['search'] != u'': search_clicked = kw['search'] else: search_clicked = None except Exception: search_clicked = None if kw: delkw = [] for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': order = v if str(k) != 'select' and str(k) != 'remove' and str(v) != u'': tmpl += str(k) + '=' + str(v) + '&' elif str(k) == 'select': try: if isinstance(kw['select'], basestring): selection = [kw['select']] else: selection = [id for id in kw['select']] except Exception: selection = None elif str(v) == u'': delkw.append(k) for k in delkw: del kw[k] mylists = sorted(mylists, key=lambda list: list.__getattribute__(order)) if dsc: mylists.reverse() if selection and not search_clicked: argv ='' for arg in selection: argv += '/' + arg if kw['akcja'] == u'edit': if len(selection) == 1: redirect('/myaccount/editlist%s' %argv) else: flash(l_(u'Editing only one by one'), 'warning') redirect(request.headers['Referer']) elif kw['akcja'] == u'delete': redirect('/myaccount/removelist%s' % argv) else: flash(l_(u'Action error'), 'error') redirect(request.headers['Referer']) return dict(mylists=mylists, pcl=pcl, page='index', tmpl=tmpl, pname=None)
def removelist(self, *args, **kw): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter(User.user_name == userid).first() id = args[0] mylist = DBSession.query(UserLists).get(id) if mylist.tg_user_id != user.user_id: flash(l_(u'Permission denied'), 'error') redirect(request.headers['Referer']) assert mylist.tg_user_id == user.user_id, u"Brak uprawnien usuwania" if mylist: DBSession.delete(mylist) DBSession.flush() flash(l_(u'Task completed successfully')) redirect(request.headers['Referer']) else: flash(l_(u'List is required'), 'warning') redirect(request.headers['Referer'])
def edit(self, id): pname = request.environ['PATH_INFO'].split('/')[1] id = int(id) scompound = DBSession.query( SCompound ).get(id) alltags =[tag for tag in DBSession.query(Tags).order_by('name').all() ] etap_max = scompound.effort[-1].etap_max etap = scompound.effort[-1].etap principals = DBSession.query (Group).get(3) owners = DBSession.query (Group).get(2) come_from = request.headers['Referer'] try: tags = [tag for tag in scompound.mol.tags] except Exception: tags = [scompound.mol.tags] pass try: files = scompound.filename except Exception: files = None pass return dict(scompound=scompound, tags=tags, alltags=alltags, files=files, etap=etap, etap_max=etap_max, users=principals.users, owners=owners.users, come_from=come_from, page='kierownik', pname=pname)
def deletefromlist(self, ulist_id, *args): """ Delete compound from User List. """ ulist = DBSession.query(UserLists).get(ulist_id) # pname = request.environ['PATH_INFO'].split('/')[1] userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=userid).first() # ulists = [l for l in user.lists if l.table == 'Results'] if (ulist in user.lists) or (user in ulist.permitusers): if ulist.elements: import pickle elements = [int(el) for el in pickle.loads(ulist.elements)] for arg in args: if int(arg) in elements: elements.remove(int(arg)) ulist.elements = pickle.dumps(elements) flash(l_(u'Task completed successfully')) else: flash(l_(u'Permission denied'), 'error') redirect(request.headers['Referer'])
def editlist(self, *args, **kw): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter(User.user_name == userid).first() users = DBSession.query(User).order_by(User.display_name).all() id = args[0] mylist = DBSession.query(UserLists).get(id) assert mylist.tg_user_id == user.user_id, u"Brak uprawnien edycji" if kw: if not (kw.has_key('name') and kw['name'] != u''): flash(l_(u'Name is required'), 'error') else: if kw.has_key('name') and kw['name'] != mylist.name: mylist.name = kw['name'] # if kw.has_key('table') and kw['table'] != mylist.table: # mylist.table=kw['table'] if kw.has_key('notes') and kw['notes'] != mylist.notes: mylist.notes = kw['notes'] if kw.has_key('permitusers') and kw['permitusers'] != u'': if isinstance(kw['permitusers'], (list, tuple)): permitusers = [ usr for usr in users if usr.user_name in kw['permitusers'] ] else: permitusers = [ usr for usr in users if usr.user_name == kw['permitusers'] ] if permitusers != mylist.permitusers: mylist.permitusers = permitusers DBSession.flush() flash(l_(u'Task completed successfully')) redirect(request.headers['Referer']) return dict(mylist=mylist, user=user, users=users, page='index', pname=None)
def tags(self, **kw): pname = request.environ['PATH_INFO'].split('/')[1] userid = request.identity['repoze.who.userid'] alltags = [tag for tag in DBSession.query(Tags).order_by('name').all()] if kw: try: usun = kw['button1'] except Exception: usun = None if usun: try: if isinstance(kw['deltags'], basestring): tagi = [DBSession.query(Tags).get(int(kw['deltags']))] else: tagi = [ DBSession.query(Tags).get(int(id)) for id in kw['deltags'] ] except Exception: tagi = None if tagi: for tag in tagi: for compound in DBSession.query(Compound).all(): if tag in compound.tags: compound.tags.remove(tag) history = History() history.user = userid history.status = u'Usuwanie tagu' history.changes = u'Usunieto tag %s ' % tag.name compound.history += [history] DBSession.add(history) DBSession.delete(tag) DBSession.flush() flash(l_(u'Task completed successfully')) alltags = [ tag for tag in DBSession.query(Tags).order_by( 'name').all() ] else: try: if kw['addtag'] != '': tagname = kw['addtag'] else: tagname = None except Exception: tagname = None if tagname: tag = Tags() tag.name = tagname flash(l_(u'Task completed successfully')) DBSession.add(tag) DBSession.flush() alltags = [ tg for tg in DBSession.query(Tags).order_by('name').all() ] else: flash(l_(u'Name required'), 'warning') return dict(alltags=alltags, page='kierownik', pname=pname)
def remove_from_list(self, *args, **kw): ulistid = args[0] ulist = DBSession.query(UserLists).get(ulistid) userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter(User.user_name == userid).first() if (ulist in user.lists): if ulist.elements: import pickle elements = pickle.loads(ulist.elements) if args[1:]: for arg in args[1:]: elements.remove(arg) ulist.elements = pickle.dumps(elements) flash(l_(u'Task completed successfully')) redirect(request.headers['Referer']) else: flash(l_(u'Args error'), 'error') redirect(request.headers['Referer']) else: flash(l_(u'List error'), 'error') redirect(request.headers['Referer']) else: flash(l_(u'Permission denied'), 'error') redirect(request.headers['Referer'])
def _lookup(self, project_name, *remainder): """ Project instance lookup. """ from tg.predicates import not_anonymous try: came_from = request.headers['Referer'] except Exception: came_from = request.path_url if not not_anonymous(): flash(l_('Permission is not sufficient for this user.'), 'error') redirect('/login?came_from=%s' % came_from) if DBSession.query(Projects).filter( Projects.name == project_name).first(): class UsersController(BaseController): """Subcontrollers for lookup. MAIN SITE FOR PROJECT INSTANCE. Parmission allowed only for logged user with added permision named as a project. """ # The predicate that must be met for all the actions in this controller: allow_only = has_permission( project_name, msg=l_('Permission is not sufficient for this user.')) molecules = MoleculesController() select = SelectController() synthesis = SynthesisController() library = LibraryController() results = ResultsController() @expose('molgears.templates.users.index') def index(self): """Main site for project.""" userid = request.identity['repoze.who.userid'] projects = DBSession.query(Projects).all() user = DBSession.query(User).filter_by( user_name=userid).first() perms = [p.permission_name for p in list(user.permissions)] return dict(page='index', userid=userid, projects=projects, perms=perms, pname=project_name) users = UsersController() else: users = ErrorController() return users, remainder
def delete_project(self, *args, **kw): try: project_id = args[0] except Exception: redirect("/error") try: come_from = request.headers['Referer'] except Exception: come_from = request.path_url project = DBSession.query(Projects).get(project_id) if project: DBSession.delete(project) else: flash(l_(u'Project error'), 'error') redirect(come_from) flash(l_(u'Task completed successfully')) redirect(come_from)
def tags(self, **kw): pname = request.environ['PATH_INFO'].split('/')[1] userid = request.identity['repoze.who.userid'] alltags =[tag for tag in DBSession.query(Tags).order_by('name').all() ] if kw: try: usun = kw['button1'] except Exception: usun = None if usun: try: if isinstance(kw['deltags'], basestring): tagi = [DBSession.query( Tags ).get(int(kw['deltags']))] else: tagi = [DBSession.query( Tags ).get(int(id)) for id in kw['deltags']] except Exception: tagi = None if tagi: for tag in tagi: for compound in DBSession.query(Compound).all(): if tag in compound.tags: compound.tags.remove(tag) history = History() history.user = userid history.status = u'Usuwanie tagu' history.changes = u'Usunieto tag %s ' % tag.name compound.history += [history] DBSession.add(history) DBSession.delete(tag) DBSession.flush() flash(l_(u'Task completed successfully')) alltags =[tag for tag in DBSession.query(Tags).order_by('name').all() ] else: try: if kw['addtag'] != '': tagname = kw['addtag'] else: tagname = None except Exception: tagname = None if tagname: tag = Tags() tag.name = tagname flash(l_(u'Task completed successfully')) DBSession.add(tag) DBSession.flush() alltags =[tg for tg in DBSession.query(Tags).order_by('name').all() ] else: flash(l_(u'Name required'), 'warning') return dict(alltags=alltags, page='kierownik', pname=pname)
def _do_get_provider_count_and_objs(self, name=None, **kw): userid = request.identity['repoze.who.userid'] lcompound = DBSession.query(LCompound) dsc = True order = 'id' if kw: for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': order = v # else: # scompound = scompound.filter(str(k)==str(v)) if dsc: lcompound = lcompound.order_by(desc(order)) else: lcompound = lcompound.order_by((order)) lcompound = lcompound.all() return len(lcompound), lcompound
def delete_user(self, *args, **kw): try: user_id = args[0] except Exception: redirect("/error") try: come_from = request.headers['Referer'] except Exception: come_from = request.path_url user = DBSession.query(User).get(user_id) if user: for group in user.groups: group.users.remove(user) DBSession.delete(user) else: flash(l_(u'User error'), 'error') redirect(come_from) flash(l_(u'Task completed successfully')) redirect(come_from)
def add_to_list(self, *args, **kw): if args: listid = args[0] # table = args[1] ulist = DBSession.query(UserLists).get(listid) values = [] if args[2:]: for arg in args[2:]: values.append(arg) import pickle if ulist and ulist.elements and ulist.elements != u"": elements = pickle.loads(ulist.elements) else: elements = [] new_elements = set(elements + values) ulist.elements = pickle.dumps(list(new_elements)) flash(l_(u'Task completed successfully')) redirect(request.headers['Referer']) else: flash(l_(u'Args error'), 'error') redirect("/")
def _lookup(self, project_name, *remainder): """ Project instance lookup. """ from tg.predicates import not_anonymous try: came_from = request.headers['Referer'] except Exception: came_from = request.path_url if not not_anonymous(): flash(l_('Permission is not sufficient for this user.'), 'error') redirect('/login?came_from=%s' % came_from) if DBSession.query(Projects).filter(Projects.name==project_name).first(): class UsersController(BaseController): """Subcontrollers for lookup. MAIN SITE FOR PROJECT INSTANCE. Parmission allowed only for logged user with added permision named as a project. """ # The predicate that must be met for all the actions in this controller: allow_only = has_permission(project_name, msg=l_('Permission is not sufficient for this user.')) molecules = MoleculesController() select = SelectController() synthesis = SynthesisController() library = LibraryController() results = ResultsController() @expose('molgears.templates.users.index') def index(self): """Main site for project.""" userid = request.identity['repoze.who.userid'] projects = DBSession.query(Projects).all() user = DBSession.query(User).filter_by(user_name=userid).first() perms = [p.permission_name for p in list(user.permissions)] return dict(page='index', userid=userid, projects=projects, perms=perms, pname=project_name) users = UsersController() else: users = ErrorController() return users, remainder
def save(self, *args, **kw): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter(User.user_name == userid).first() try: old = kw['old_password'] except Exception: old = None try: new = kw['password'] if not (new == kw['veryfie']): flash(l_(u'Password error'), 'error') redirect('/myaccount') except Exception: new = None flash(l_(u'Password error'), 'error') redirect('/myaccount') try: email = kw['email'] except Exception: email = None try: items_per_page = int(kw['items_per_page']) limit_sim = int(kw['limit_sim']) threshold = int(kw['threshold']) except Exception: items_per_page = None limit_sim = None threshold = None if old: if user.validate_password(old): if items_per_page and items_per_page != user.items_per_page: if items_per_page > 10 and items_per_page < 150: user.items_per_page = items_per_page else: flash( l_(u'Number of Compound per page should be between 10 and 150' ), 'error') redirect('/myaccount') if limit_sim and limit_sim != user.limit_sim: if limit_sim > 10 and limit_sim < 50: user.limit_sim = limit_sim else: flash( l_(u'Number of Compound per page should be between 10 and 150' ), 'error') redirect('/myaccount') if threshold and threshold != user.threshold: if threshold > 10 and threshold < 50: user.threshold = threshold else: flash( l_(u'Similarity value should be between 10 and 50' ), 'error') redirect('/myaccount') if email and user.email_address != email: import re if len(email) > 7: if re.match( "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None: user.email_address = email else: flash(l_(u'Email error'), 'warning') redirect('/myaccount') else: flash(l_(u'Email error'), 'warning') redirect('/myaccount') else: flash(l_(u'Email not changed'), 'warning') if new: if len(new) > 6: user._set_password(new) else: flash(l_(u'Password error'), 'error') redirect('/myaccount') else: flash(l_(u'Password verification error'), 'error') redirect('/myaccount') else: flash(l_(u'Current password required'), 'warning') redirect('/myaccount') flash(l_(u'Task completed successfully')) redirect('/myaccount')
def reagents(self, page=1, *args, **kw): pname = request.environ['PATH_INFO'].split('/')[1] history = DBSession.query( RHistory ).filter(RHistory.project.any(Projects.name==pname)) order='RHistory.id' userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=userid).first() items = user.items_per_page tmpl = '' dsc = True from datetime import timedelta now=datetime.now() one_day=timedelta(days=1) try: if kw['search'] != u'': search_clicked = kw['search'] else: search_clicked = None except Exception: search_clicked = None if kw: for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': if v == 'gid': order = RHistory.reagents_id elif v == 'user': order = RHistory.user elif v == 'date': order = RHistory.date else: order = v if str(k) != 'remove': tmpl += str(k) + '=' + str(v) + '&' if search_clicked: if kw.has_key('text_GID') and kw['text_GID'] !=u'': try: gid = int(kw['text_gid']) history = history.filter(Reagents.rid == gid ) except Exception as msg: flash(l_(u'ID should be a number: %s' % msg), 'error') redirect(request.headers['Referer']) if kw.has_key('text_user') and kw['text_user'] !=u'': history = history.filter(RHistory.user.like(kw['text_user'].replace('*', '%'))) if kw.has_key('text_status') and kw['text_status'] !=u'': history = history.filter(RHistory.status.like(kw['text_status'].replace('*', '%'))) if kw.has_key('text_changes') and kw['text_changes'] !=u'': history = history.filter(RHistory.changes.like(kw['text_changes'].replace('*', '%'))) if kw.has_key('date_from') and kw['date_from'] !=u'': date_from = datetime.strptime(str(kw['date_from']), '%Y-%m-%d') history = history.filter(RHistory.date > date_from) else: date_from = None if kw.has_key('date_to') and kw['date_to'] !=u'': date_to = datetime.strptime(str(kw['date_to']), '%Y-%m-%d') if date_from: if date_to>date_from: history = history.filter(RHistory.date < date_to) else: flash(l_(u'The End date must be later than the initial'), 'error') redirect(request.headers['Referer']) else: history = history.filter(RHistory.date < date_to) if dsc: history = history.order_by(desc(order).nullslast()) else: history = history.order_by((order)) page_url = paginate.PageURL_WebOb(request) currentPage = paginate.Page(history, page, url=page_url, items_per_page=items) return dict(history=currentPage.items, currentPage=currentPage, tmpl=tmpl, one_day=one_day, now=now, page='kierownik', pname=pname)
def save(self, *args, **kw): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] # if not(userid == kw['name']): # flash(u'Zła nazwa użytkownika', 'error') # redirect(request.headers['Referer']) user = DBSession.query(User).filter(User.user_name == userid).first() # flash(kw) try: old = kw['old_password'] except Exception: old = None try: new = kw['password'] if not(new == kw['veryfie']): flash(l_(u'Password error'), 'error') redirect(request.headers['Referer']) except Exception: new = None flash(l_(u'Password error'), 'error') redirect(request.headers['Referer']) try: email = kw['email'] except Exception: email = None try: items_per_page = int(kw['items_per_page']) limit_sim = int(kw['limit_sim']) threshold = int(kw['threshold']) except Exception: items_per_page = None limit_sim = None threshold = None if old: if user.validate_password(old): if items_per_page and items_per_page != user.items_per_page: if items_per_page > 10 and items_per_page < 150: user.items_per_page = items_per_page else: flash(l_(u'Number of Compound per page should be between 10 and 150'), 'error') redirect(request.headers['Referer']) if limit_sim and limit_sim != user.limit_sim: if limit_sim >10 and limit_sim <50: user.limit_sim = limit_sim else: flash(l_(u'Number of Compound per page should be between 10 and 150'), 'error') redirect(request.headers['Referer']) if threshold and threshold != user.threshold: if threshold >10 and threshold <50: user.threshold = threshold else: flash(l_(u'Similarity value should be between 10 and 50'), 'error') redirect(request.headers['Referer']) if email and user.email_address != email: import re if len(email) > 7: if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None: user.email_address = email else: flash(l_(u'Email error'), 'warning') redirect(request.headers['Referer']) else: flash(l_(u'Email error'), 'warning') redirect(request.headers['Referer']) else: flash(l_(u'Email not changed'), 'warning') if new: if len(new)>6: user._set_password(new) else: flash(l_(u'Password error'), 'error') redirect(request.headers['Referer']) else: flash(l_(u'Password verification error'), 'error') redirect(request.headers['Referer']) else: flash(l_(u'Current password required'), 'warning') redirect(request.headers['Referer']) flash(l_(u'Task completed successfully')) redirect(request.headers['Referer'])
def edit(self): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter(User.user_name == userid).first() return dict(user=user, page='index', pname=None)
def sharedlists(self, page=1, *args, **kw): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] SharedLists = DBSession.query(UserLists).filter( UserLists.permitusers.any(User.user_name == userid)).all() import pickle as pcl dsc = True tmpl = '' selection = None order = "id" try: if kw['search'] != u'': search_clicked = kw['search'] else: search_clicked = None except Exception: search_clicked = None if kw: delkw = [] for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': order = v if str(k) != 'select' and str(k) != 'remove' and str(v) != u'': tmpl += str(k) + '=' + str(v) + '&' elif str(k) == 'select': try: if isinstance(kw['select'], basestring): selection = [kw['select']] else: selection = [id for id in kw['select']] except Exception: selection = None elif str(v) == u'': delkw.append(k) for k in delkw: del kw[k] SharedLists = sorted(SharedLists, key=lambda list: list.__getattribute__(order)) if dsc: SharedLists.reverse() if selection and not search_clicked: argv = '' for arg in selection: argv += '/' + arg if kw['akcja'] == u'edit': if len(selection) == 1: redirect('/myaccount/editlist%s' % argv) else: flash(l_(u'Editing only one by one'), 'warning') redirect(request.headers['Referer']) elif kw['akcja'] == u'delete': redirect('/myaccount/removelist%s' % argv) else: flash(l_(u'Action error'), 'error') redirect(request.headers['Referer']) return dict(SharedLists=SharedLists, tmpl=tmpl, pcl=pcl, page='index', pname=None)
def index(self, page=1, *args, **kw): pname = request.environ['PATH_INFO'].split('/')[1] project = DBSession.query(Projects).filter_by(name=pname).first() page_url = paginate.PageURL_WebOb(request) import pickle try: cells = pickle.loads([test.cell_line for test in project.tests if test.name == 'CT'][0]) except: cells = None lcompound = DBSession.query(LCompound).join(LCompound.mol).filter(Compound.project.any(Projects.name==pname)).filter(LCompound.showme==True) dsc = True order = LCompound.id tmpl = '' alltags =[tag for tag in DBSession.query(Tags).order_by('name').all() ] selection = None similarity = None userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=userid).first() ulist = None ulists = set([l for l in user.lists if l.table == 'Results'] + [l for l in user.tg_user_lists if l.table == 'Results']) items = user.items_per_page try: if kw['search'] != u'': search_clicked = kw['search'] else: search_clicked = None except Exception: search_clicked = None if kw: if kw.has_key('mylist'): try: ulist_id = int(kw['mylist']) ulist = DBSession.query(UserLists).get(ulist_id) except Exception: flash(l_(u'List error'), 'error') redirect(request.headers['Referer']) if (ulist in user.lists) or (user in ulist.permitusers): if ulist.elements: import pickle elements = [int(el) for el in pickle.loads(ulist.elements)] if ulist.table == 'Results': lcompound = DBSession.query(LCompound).join(LCompound.mol).filter(Compound.project.any(Projects.name==pname)).filter(LCompound.id.in_(elements)) else: flash(l_(u'Table error'), 'error') redirect(request.headers['Referer']) else: flash(l_(u'Permission denied'), 'error') redirect(request.headers['Referer']) for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': if v in ('gid', 'create_date', 'box', 'form', 'state', 'entry', 'source', 'MDM2', 'MDM4', 'lcode'): if v=='lcode': order = LCompound.lcode else: order = LCompound.__getattribute__(LCompound, v) else: if v=='last_point': lcompound=lcompound.join(LCompound.solubility) order = v elif hasattr(LCompound, v): order = LCompound.__getattribute__(LCompound, v) elif 'CTOX_' in v: v = v.replace('CTOX_', '') all_lcompounds = DBSession.query(LCompound).join(LCompound.mol).filter(Compound.project.any(Projects.name==pname)).all() for l in all_lcompounds: l.avg_ct = v.replace('pp', '+') order = '_avg_ct' else: order = v if str(k) != 'select' and str(k) != 'remove' and str(v) != u'': tmpl += str(k) + '=' + str(v) + '&' elif str(k) == 'select': try: if isinstance(kw['select'], basestring): selection = [kw['select']] else: selection = [id for id in kw['select']] except Exception: selection = None if search_clicked: try: smiles = str(kw['smiles']) if 'pp' in smiles: smiles = smiles.replace('pp', '+') method = str(kw['method']) except Exception: smiles = None method = None if smiles: if checksmi(smiles): from razi.functions import functions from razi.expression import TxtMoleculeElement if method == 'similarity': # from razi.postgresql_rdkit import tanimoto_threshold query_bfp = functions.morgan_b(TxtMoleculeElement(smiles), 2) constraint = Compound.morgan.tanimoto_similar(query_bfp) tanimoto_sml = Compound.morgan.tanimoto_similarity(query_bfp).label('tanimoto') search = DBSession.query(LCompound, tanimoto_sml).join(LCompound.mol).join(LCompound.purity).filter(Compound.project.any(Projects.name==pname)).filter(constraint) if order != LCompound.id: if order == 'purity': order = LPurity.value if dsc: search = search.order_by(desc(order).nullslast()) else: search = search.order_by(order) else: search = search.order_by(desc(tanimoto_sml)).all() lcompound = () similarity = () for row in search: lcompound += (row[0], ) similarity += (row[1], ) currentPage = paginate.Page(lcompound, page, url=page_url, items_per_page=items) return dict(currentPage=currentPage,tmpl=tmpl, page='results', pname=pname, alltags=alltags, similarity=similarity,htmlRgb=htmlRgb, htmlRgb100=htmlRgb100, Num2Rgb=Num2Rgb, cells=cells, ulists=ulists, ulist=ulist) elif method == 'substructure': constraint = Compound.structure.contains(smiles) lcompound = DBSession.query(LCompound).join(LCompound.mol).filter(Compound.project.any(Projects.name==pname)).filter(constraint) elif method == 'identity': lcompound = DBSession.query(LCompound).filter(Compound.project.any(Projects.name==pname)).join(LCompound.mol).filter(Compound.structure.equals(smiles)) else: if method == 'smarts': if dsc: lcompound = lcompound.order_by(desc(order).nullslast()) else: lcompound = lcompound.order_by(order) search = lcompound.all() sub_lcompounds = () patt = Chem.MolFromSmarts(smiles) if not patt: flash(l_(u'SMARTS error'), 'warning') redirect(request.headers['Referer']) for row in search: m = Chem.MolFromSmiles(str(row.mol.structure)) mol = Chem.AddHs(m) if mol.HasSubstructMatch(patt): sub_lcompounds += (row, ) currentPage = paginate.Page(sub_lcompounds, page, url=page_url, items_per_page=items) return dict(currentPage=currentPage,tmpl=tmpl, page='results', pname=pname, alltags=alltags, similarity=similarity,htmlRgb=htmlRgb, htmlRgb100=htmlRgb100, Num2Rgb=Num2Rgb, cells=cells, ulists=ulists, ulist=ulist) else: flash(l_(u'SMILES error'), 'warning') redirect(request.headers['Referer']) if kw.has_key('text_GID') and kw['text_GID'] !=u'': try: gid = int(kw['text_GID']) lcompound = lcompound.filter(LCompound.gid == gid) except Exception as msg: flash(l_(u'GID should be a number: %s' % msg), 'error') redirect(request.headers['Referer']) if kw.has_key('text_ID') and kw['text_ID'] !=u'': try: id = int(kw['text_ID']) lcompound = lcompound.filter(LCompound.id == id) except Exception as msg: flash(l_(u'ID should be a number: %s' % msg), 'error') redirect(request.headers['Referer']) if kw.has_key('text_name') and kw['text_name'] !=u'': lcompound = lcompound.filter(Compound.names.any(Names.name.like(kw['text_name'].strip().replace('*', '%')))) if kw.has_key('text_notes') and kw['text_notes'] !=u'': lcompound = lcompound.filter(LCompound.notes.like(kw['text_notes'].replace('*', '%'))) if kw.has_key('text_lso') and kw['text_lso'] !=u'': lcompound = lcompound.filter(LCompound.lso.like(kw['text_lso'].replace('*', '%'))) if kw.has_key('text_entry') and kw['text_entry'] !=u'': lcompound = lcompound.filter(LCompound.entry.like(kw['text_entry'].replace('*', '%'))) if kw.has_key('text_box') and kw['text_box'] !=u'': lcompound = lcompound.filter(LCompound.box.like(kw['text_box'].replace('*', '%'))) if kw.has_key('date_from') and kw['date_from'] !=u'': date_from = datetime.strptime(str(kw['date_from']), '%Y-%m-%d') lcompound = lcompound.filter(LCompound.create_date > date_from) else: date_from = None if kw.has_key('date_to') and kw['date_to'] !=u'': date_to = datetime.strptime(str(kw['date_to']), '%Y-%m-%d') if date_from: if date_to>date_from: lcompound = lcompound.filter(LCompound.create_date < date_to) else: flash(l_(u'The End date must be later than the initial'), 'error') redirect(request.headers['Referer']) else: lcompound = lcompound.filter(LCompound.create_date < date_to) if kw.has_key('text_mdm2_hill_from') and kw['text_mdm2_hill_from'] !=u'': text_mdm2_hill_from = float(kw['text_mdm2_hill_from']) lcompound = lcompound.filter(LCompound.avg_hillslope_mdm2 >= text_mdm2_hill_from) else: text_mdm2_hill_from = None if kw.has_key('text_mdm2_hill_to') and kw['text_mdm2_hill_to'] !=u'': text_mdm2_hill_to = float(kw['text_mdm2_hill_to']) if text_mdm2_hill_from: if text_mdm2_hill_to>=text_mdm2_hill_from: lcompound = lcompound.filter(LCompound.avg_hillslope_mdm2 <= text_mdm2_hill_to) else: flash(l_(u'The final value must be greater than the initial')) redirect(request.headers['Referer']) else: lcompound = lcompound.filter(LCompound.avg_hillslope_mdm2 <= text_mdm2_hill_to) if kw.has_key('text_mdm2_fluor_from') and kw['text_mdm2_fluor_from'] !=u'': text_mdm2_fluor_from = float(kw['text_mdm2_fluor_from']) lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm2 >= text_mdm2_fluor_from) else: text_mdm2_fluor_from = None if kw.has_key('text_mdm2_fluor_to') and kw['text_mdm2_fluor_to'] !=u'': text_mdm2_fluor_to = float(kw['text_mdm2_fluor_to']) if text_mdm2_fluor_from: if text_mdm2_fluor_to>=text_mdm2_fluor_from: lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm2 <= text_mdm2_fluor_to) else: flash(l_(u'The final value must be greater than the initial')) redirect(request.headers['Referer']) else: lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm2 <= text_mdm2_fluor_to) if kw.has_key('text_mdm2_ki_from') and kw['text_mdm2_ki_from'] !=u'': text_mdm2_ki_from = float(kw['text_mdm2_ki_from']) lcompound = lcompound.filter(LCompound.avg_ki_mdm2 >= text_mdm2_ki_from) else: text_mdm2_ki_from = None if kw.has_key('text_mdm2_ki_to') and kw['text_mdm2_ki_to'] !=u'': text_mdm2_ki_to = float(kw['text_mdm2_ki_to']) if text_mdm2_ki_from: if text_mdm2_ki_to>=text_mdm2_ki_from: lcompound = lcompound.filter(LCompound.avg_ki_mdm2 <= text_mdm2_ki_to) else: flash(l_(u'The final value must be greater than the initial')) redirect(request.headers['Referer']) else: lcompound = lcompound.filter(LCompound.avg_ki_mdm2 <= text_mdm2_ki_to) if kw.has_key('text_mdm4_hill_from') and kw['text_mdm4_hill_from'] !=u'': text_mdm4_hill_from = float(kw['text_mdm4_hill_from']) lcompound = lcompound.filter(LCompound.avg_hillslope_mdm4 >= text_mdm4_hill_from) else: text_mdm4_hill_from = None if kw.has_key('text_mdm4_hill_to') and kw['text_mdm4_hill_to'] !=u'': text_mdm4_hill_to = float(kw['text_mdm4_hill_to']) if text_mdm4_hill_from: if text_mdm4_hill_to>=text_mdm4_hill_from: lcompound = lcompound.filter(LCompound.avg_hillslope_mdm4 <= text_mdm4_hill_to) else: flash(l_(u'The final value must be greater than the initial')) redirect(request.headers['Referer']) else: lcompound = lcompound.filter(LCompound.avg_hillslope_mdm4 <= text_mdm4_hill_to) if kw.has_key('text_mdm4_fluor_from') and kw['text_mdm4_fluor_from'] !=u'': text_mdm4_fluor_from = float(kw['text_mdm4_fluor_from']) lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm4 >= text_mdm4_fluor_from) else: text_mdm4_fluor_from = None if kw.has_key('text_mdm4_fluor_to') and kw['text_mdm4_fluor_to'] !=u'': text_mdm4_fluor_to = float(kw['text_mdm4_fluor_to']) if text_mdm4_fluor_from: if text_mdm4_fluor_to>=text_mdm4_fluor_from: lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm4 <= text_mdm4_fluor_to) else: flash(l_(u'The final value must be greater than the initial')) redirect(request.headers['Referer']) else: lcompound = lcompound.filter(LCompound.avg_fluorescence_mdm4 <= text_mdm4_fluor_to) if kw.has_key('text_mdm4_ki_from') and kw['text_mdm4_ki_from'] !=u'': text_mdm4_ki_from = float(kw['text_mdm4_ki_from']) lcompound = lcompound.filter(LCompound.avg_ki_mdm4 >= text_mdm4_ki_from) else: text_mdm4_ki_from = None if kw.has_key('text_mdm4_ki_to') and kw['text_mdm4_ki_to'] !=u'': text_mdm4_ki_to = float(kw['text_mdm4_ki_to']) if text_mdm4_ki_from: if text_mdm4_ki_to>=text_mdm4_ki_from: lcompound = lcompound.filter(LCompound.avg_ki_mdm4 <= text_mdm4_ki_to) else: flash(l_(u'The final value must be greater than the initial')) redirect(request.headers['Referer']) else: lcompound = lcompound.filter(LCompound.avg_ki_mdm4 <= text_mdm4_ki_to) try: tags = kw['text_tags'] except Exception: tags = None pass if tags: if isinstance(tags, basestring): tagi = eval(tags) if type(tagi) != type([]): tagi = [int(tags)] else: tagi = [int(tid) for tid in tags] lcompound = lcompound.filter(Compound.tags.any(Tags.id.in_(tagi))) if dsc: lcompound = lcompound.order_by(desc(order).nullslast()) else: lcompound = lcompound.order_by(order) if search_clicked and kw['search'] == "Download": if kw['file_type'] and kw['file_type'] != u'' and kw['sell_type'] and kw['sell_type'] != u'': if kw['sell_type'] == u'all': lcompounds = lcompound.all() elif kw['sell_type'] == u'selected': if selection: lcompounds = () for el in selection: lcompounds += (DBSession.query(LCompound).get(el), ) else: flash(l_(u'Lack of selected structures for download'), 'error') redirect(request.headers['Referer']) elif kw['sell_type'] == u'range': lcompounds = lcompound.all() if kw.has_key('select_from') and kw['select_from'] != u'': try: select_from = int(kw['select_from']) -1 if select_from<1 or select_from>len(lcompounds): select_from = 0 except Exception: select_from = 0 else: select_from = 0 if kw.has_key('select_to') and kw['select_to'] != u'': try: select_to = int(kw['select_to']) if select_to<2 or select_to>len(lcompounds): select_to = len(lcompounds) except Exception: select_to = len(lcompounds) else: select_to = len(lcompounds) lcompounds_new = () for el in range(select_from, select_to): lcompounds_new += (lcompounds[el], ) lcompounds = lcompounds_new else: flash(l_(u'Lack of items to download'), 'error') redirect(request.headers['Referer']) try: if isinstance(kw['options'], basestring): options = [kw['options']] else: options = kw['options'] except Exception: flash(l_('Choose download options'), 'error') redirect(request.headers['Referer']) if 'getsize' in kw: size = int(kw['getsize']), int(kw['getsize']) else: size = 100, 100 if kw['file_type'] == 'pdf': filename = userid + '_selected.pdf' from xhtml2pdf.pisa import CreatePDF from tg.render import render as render_template import cStringIO html = render_template({"length":len(lcompounds), "lcompound":lcompounds, "cells":cells, "options":options, "size":size}, "genshi", "molgears.templates.users.results.print2", doctype=None) dest = './molgears/files/pdf/' + filename result = file(dest, "wb") CreatePDF(cStringIO.StringIO(html.encode("UTF-8")), result, encoding="utf-8") result.close() import paste.fileapp f = paste.fileapp.FileApp('./molgears/files/pdf/'+ filename) from tg import use_wsgi_app return use_wsgi_app(f) elif kw['file_type'] == 'xls': filename = userid + '_selected.xls' filepath = os.path.join('./molgears/files/download/', filename) from PIL import Image import xlwt wbk = xlwt.Workbook() sheet = wbk.add_sheet('sheet1') j=0 if 'nr' in options: sheet.write(0,j,u'Nr.') j+=1 if 'gid' in options: sheet.write(0,j,u'GID') j+=1 if 'id' in options: sheet.write(0,j,u'ID') j+=1 if 'name' in options: sheet.write(0,j,u'Name') j+=1 if 'names' in options: sheet.write(0,j,u'Names') j+=1 if 'image' in options: sheet.write(0,j,u'Image') j+=1 if 'smiles' in options: sheet.write(0,j,u'SMILES') j+=1 if 'inchi' in options: sheet.write(0,j,u'InChi') j+=1 if 'lso' in options: sheet.write(0,j,u'LSO') j+=1 if 'num_atoms' in options: sheet.write(0,j,u'Atoms') j+=1 if 'mw' in options: sheet.write(0,j,u'MW') j+=1 if 'hba' in options: sheet.write(0,j,u'hba') j+=1 if 'hbd' in options: sheet.write(0,j,u'hbd') j+=1 if 'tpsa' in options: sheet.write(0,j,u'tpsa') j+=1 if 'logp' in options: sheet.write(0,j,u'logP') j+=1 if 'purity' in options: sheet.write(0,j, u'Purity') j+=1 if 'create_date' in options: sheet.write(0,j,u'Date') j+=1 if 'box' in options: sheet.write(0,j,u'Box') j+=1 if 'entry' in options: sheet.write(0,j,u'Entry') j+=1 if 'source' in options: sheet.write(0,j,u'Source') j+=1 if 'content' in options: sheet.write(0,j,u'Content') j+=1 if 'tags' in options: sheet.write(0,j,u'Tags') j+=1 if 'notes' in options: sheet.write(0,j,u'Notes') j+=1 for cell_line in cells: if '_CT_%s' % cell_line in options: sheet.write(0,j,u'CT %s' % cell_line) j+=1 i = 1 for row in lcompounds: j=0 if 'nr' in options: sheet.write(i,j, str(i)) j+=1 if 'gid' in options: sheet.write(i,j, row.gid) j+=1 if 'id' in options: sheet.write(i,j, row.id) j+=1 if 'name' in options: sheet.write(i,j, row.mol.name) j+=1 if 'names' in options: names = u'' for n in row.mol.names: names += n.name + u', ' sheet.write(i,j, names) j+=1 if 'image' in options: file_in = './molgears/public/img/%s.png' % row.gid img = Image.open(file_in) file_out = './molgears/public/img/bitmap/thumb%s.bmp' %row.gid img.thumbnail(size, Image.ANTIALIAS) img.save(file_out) sheet.insert_bitmap(file_out , i,j, 5, 5) j+=1 if 'smiles' in options: sheet.write(i,j, str(row.mol.structure)) j+=1 if 'inchi' in options: sheet.write(i,j, str(row.mol.inchi)) j+=1 if 'lso' in options: sheet.write(i,j, row.lso) j+=1 if 'num_atoms' in options: sheet.write(i,j,str(row.mol.num_hvy_atoms)+'/'+str(row.mol.num_atoms)) j+=1 if 'mw' in options: sheet.write(i,j, str(row.mol.mw)) j+=1 if 'hba' in options: sheet.write(i,j, str(row.mol.hba)) j+=1 if 'hbd' in options: sheet.write(i,j, str(row.mol.hbd)) j+=1 if 'tpsa' in options: sheet.write(i,j, str(row.mol.tpsa)) j+=1 if 'logp' in options: sheet.write(i,j, str(row.mol.logp)) j+=1 if 'state' in options: sheet.write(i,j, str(row.state)) j+=1 if 'purity' in options: pur = u'' for p in sorted(row.purity, key=lambda p: p.value, reverse=True): pur += u'%s : %s\n' % (p.value, p.type) sheet.write(i,j, pur) j+=1 if 'create_date' in options: sheet.write(i,j, str(row.create_date)) j+=1 if 'owner' in options: sheet.write(i,j, row.owner) j+=1 if 'box' in options: sheet.write(i,j, row.box) j+=1 if 'entry' in options: sheet.write(i,j, row.entry) j+=1 if 'source' in options: sheet.write(i,j, row.source) j+=1 if 'content' in options: if row.content: sheet.write(i,j, str(row.content.value)) else: sheet.write(i,j, 'None') j+=1 if 'tags' in options: tagsy=u'' for tag in row.mol.tags: tagsy += tag.name + u', ' sheet.write(i,j,tagsy) j+=1 if 'notes' in options: sheet.write(i,j, row.notes) j+=1 for cell_line in cells: if '_CT_%s' % cell_line in options: res = [] if row.ctoxicity: for ct in sorted(row.ctoxicity, key=lambda ct: ct.id): if ct.cell_line==cell_line: res.append(ct.ic50) if len(res)>0: sheet.write(i,j, str(round(sum(res)/len(res), 3))) else: sheet.write(i,j, '') j+=1 i += 1 wbk.save(filepath) import paste.fileapp f = paste.fileapp.FileApp(filepath) from tg import use_wsgi_app return use_wsgi_app(f) elif kw['file_type'] == 'sdf': filepath = './molgears/files/download/out.sdf' ww = Chem.SDWriter(filepath) from rdkit.Chem import AllChem for row in lcompounds: m2 = Chem.MolFromSmiles(str(row.mol.structure)) AllChem.Compute2DCoords(m2) AllChem.EmbedMolecule(m2) AllChem.UFFOptimizeMolecule(m2) if 'smiles' in options: m2.SetProp("smiles", str(row.mol.structure)) if 'name' in options: m2.SetProp("_Name", str(row.mol.name.encode('ascii', 'ignore'))) if 'nr' in options: m2.SetProp("Nr", str(lcompounds.index(row)+1)) if 'gid' in options: m2.SetProp("GID", str(row.gid)) if 'names' in options: names = u'' for n in row.mol.names: names += n.name + ', ' m2.SetProp("names", str(names.encode('ascii', 'ignore'))) if 'inchi' in options: m2.SetProp("InChi", str(row.mol.inchi)) if 'lso' in options: m2.SetProp("LSO", str(row.lso)) if 'num_atoms' in options: m2.SetProp("atoms", str(row.mol.num_hvy_atoms)+'/'+str(row.mol.num_atoms)) if 'mw' in options: m2.SetProp("mw", str(row.mol.mw)) if 'hba' in options: m2.SetProp("hba", str(row.mol.hba)) if 'hbd' in options: m2.SetProp("hbd", str(row.mol.hbd)) if 'tpsa' in options: m2.SetProp("TPSA", str(row.mol.tpsa)) if 'logp' in options: m2.SetProp("logP", str(row.mol.tpsa)) if 'create_date' in options: m2.SetProp("create_date", str(row.create_date)) if 'owner' in options: m2.SetProp("owner", str(row.owner)) if 'tags' in options: tagsy=u'' for tag in row.mol.tags: tagsy += tag.name + u', ' m2.SetProp("tagi", str(tagsy.encode('ascii', 'ignore'))) if 'purity' in options: pur = u'' for p in sorted(row.purity, key=lambda p: p.value, reverse=True): pur += u'%s : %s \n' % (p.value, p.type) m2.SetProp("purity", str(pur.encode('ascii', 'ignore'))) if 'content' in options: if row.content: m2.SetProp("content", str(row.content.value)) else: m2.SetProp("content", "None") j+=1 if 'box' in options: m2.SetProp("box", str(row.box)) if 'entry' in options: m2.SetProp("entry", str(row.entry)) if 'notes' in options: if row.notes: m2.SetProp("notes", str(row.notes.encode('ascii', 'ignore'))) else: m2.SetProp("notes", " ") for cell_line in cells: if '_CT_%s' % cell_line in options: res = [] if row.ctoxicity: for ct in sorted(row.ctoxicity, key=lambda ct: ct.id): if ct.cell_line==cell_line: res.append(ct.ic50) if len(res)>0: m2.SetProp('CT_%s' % cell_line, str(round(sum(res)/len(res), 3))) else: m2.SetProp('CT_%s' % cell_line, ' ') ww.write(m2) ww.close() import paste.fileapp f = paste.fileapp.FileApp(filepath) from tg import use_wsgi_app return use_wsgi_app(f) elif kw['file_type'] == 'csv' or 'txt': filename = userid + '_selected.' + kw['file_type'] filepath = os.path.join('./molgears/files/download/', filename) from molgears.widgets.unicodeCSV import UnicodeWriter import csv if kw['file_type'] == u'csv': delimiter = ';' else: delimiter = ' ' with open(filepath, 'wb') as csvfile: spamwriter = UnicodeWriter(csvfile, delimiter=delimiter, quotechar='|', quoting=csv.QUOTE_MINIMAL) for row in lcompounds: line =[] if 'smiles' in options: line.append(str(row.mol.structure)) if 'name' in options: line.append(row.mol.name) if 'nr' in options: line.append(unicode(lcompounds.index(row)+1)) if 'gid' in options: line.append(unicode(row.gid)) if 'names' in options: names = u'' for n in row.mol.names: names += n.name + u', ' line.append(names) if 'inchi' in options: line.append(row.mol.inchi) if 'lso' in options: line.append(row.lso) if 'num_atoms' in options: line.append(unicode(row.mol.num_hvy_atoms)+'/'+unicode(row.mol.num_atoms)) if 'mw' in options: line.append(unicode(row.mol.mw)) if 'hba' in options: line.append(unicode(row.mol.hba)) if 'hbd' in options: line.append(unicode(row.mol.hbd)) if 'tpsa' in options: line.append(unicode(row.mol.tpsa)) if 'logp' in options: line.append(unicode(row.mol.logp)) if 'purity' in options: pur = u'' for p in sorted(row.purity, key=lambda p: p.value, reverse=True): pur += u'%s : %s\n' % (p.value, p.type) line.append(pur) if 'create_date' in options: line.append(unicode(row.create_date)) if 'owner' in options: line.append(row.owner) if 'box' in options: line.append(row.box) if 'entry' in options: line.append(row.entry) if 'source' in options: line.append(row.source) if 'content' in options: if row.content: line.append(unicode(row.content.value)) else: line.append(u'None') if 'tags' in options: tagsy= '' for tag in row.mol.tags: tagsy += tag.name + ', ' line.append(tagsy) if 'notes' in options: line.append(row.notes) spamwriter.writerow(line) import paste.fileapp f = paste.fileapp.FileApp(filepath) from tg import use_wsgi_app return use_wsgi_app(f) if selection and not search_clicked: argv ='' gids = '' for arg in selection: argv += '/' + arg tmp_result = DBSession.query(LCompound).get(arg) gids += '/' + str(tmp_result.gid) if kw['akcja'] == u'edit': redirect('/%s/molecules/multiedit/index%s' % (pname, gids)) elif kw['akcja'] == u'results': if len(selection) == 1: redirect('/%s/results/new_result%s' % (pname, argv)) else: redirect('/%s/results/multiresults/index%s' % (pname, argv)) elif kw['akcja'] == u'htrf': if len(selection) == 1: redirect('/%s/results/htrf/add_result2%s' % (pname, argv)) currentPage = paginate.Page(lcompound, page, url=page_url, items_per_page=items) return dict(currentPage=currentPage,tmpl=tmpl, page='results', htmlRgb=htmlRgb, htmlRgb100=htmlRgb100, Num2Rgb=Num2Rgb, pname=pname, alltags=alltags, similarity=similarity, cells=cells, ulists=ulists, ulist=ulist)
def put(self, *args, **kw): pname = request.environ['PATH_INFO'].split('/')[1] sid = int(args[0]) userid = request.identity['repoze.who.userid'] scompound = DBSession.query(SCompound).get(sid) shistory = SHistory() shistory.gid = scompound.mol.gid shistory.user = userid shistory.status = u'Edycja' schanges = u'' try: reason = kw['reason'] except Exception: reason = None pass if reason and reason != u'': schanges += u'UWAGA! niestandardowa zmiana z powodu:' + reason etap = int(kw['etap']) etap_max = int(kw['etap_max']) if etap < etap_max: scompound.effort[-1].etap = etap scompound.effort[-1].etap_max = etap_max scompound.status = DBSession.query( SStatus ).get(2) schanges += u'; Bieżący etap: ' + str(etap) schanges += u'; Liczba etapow: ' + str(etap_max) else: flash(l_(u'Completed step must be smaller by 2 than the number of stages'), 'error') redirect(request.headers['Referer']) # scompound.status_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if kw.has_key('lso') and kw['lso'] != scompound.lso: scompound.lso = kw['lso'] schanges += u'; LSO: ' + kw['lso'] if kw.has_key('notes') and kw['notes'] != scompound.notes: scompound.notes = kw['notes'] schanges += u';Notes: ' + kw['notes'] try: filename = kw['loadfile'].filename import os filename = os.path.basename(filename) except Exception as msg: filename = None pass try: reaction_file = kw['reaction'].filename import os reaction_file = os.path.basename(reaction_file) except Exception as msg: reaction_file = None pass if kw['owner'] != scompound.owner: scompound.owner = kw['owner'] schanges += u'; Wlasciciel:' + kw['owner'] if kw['principal'] != scompound.principal: scompound.principal = kw['principal'] schanges += u'; Odbiorca:' + kw['principal'] if kw.has_key('priority') and kw['priority'] != u'': scompound.priority = int(kw['priority']) schanges += u'; Priorytet:' + kw['priority'] pcompound = DBSession.query(PCompound).get(scompound.pid) if pcompound: pcompound.priority = int(kw['priority']) phistory = PHistory() phistory.project = pname phistory.date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") phistory.user = userid phistory.status = 'Priorytet' phistory.changes = u'Priority: ' + kw['priority'] pcompound.history += [phistory] DBSession.add(phistory) if filename or reaction_file: if filename: number = DBSession.query(SFiles).count() + 1 newfilename = str(number) + '_' + userid + '_' + str(sid) + '_' + filename newfilename.replace(' ', '_') f_path = os.path.join(files_dir, newfilename) try: f = file(f_path, "w") f.write(kw['loadfile'].value) f.close() except Exception as msg: flash(l_(msg), 'error') redirect(request.headers['Referer']) sfile = SFiles() sfile.name = filename sfile.filename = newfilename if kw['opis']: sfile.description = kw['opis'] schanges += u'; Plik: ' + filename + u' ( ' + newfilename + u' )' DBSession.add(sfile) if reaction_file: number2 = DBSession.query(SFiles).count() + 1 newfilename2 = str(number2) + '_' + userid + '_' + str(sid) + '_' + reaction_file newfilename2.replace(' ', '_') f_path2 = os.path.join(files_dir, newfilename2) try: f2 = file(f_path2, "w") f2.write(kw['reaction'].value) f2.close() except Exception as msg: flash(l_(msg), 'error') redirect(request.headers['Referer']) reaction_sfile = SFiles() reaction_sfile.name = reaction_file reaction_sfile.filename = newfilename2 schanges += u'; Sciezka reakcji: ' + reaction_file + u' ( ' + newfilename2 + u' )' DBSession.add(reaction_sfile) shistory.changes = schanges scompound.history += [shistory] DBSession.add(shistory) DBSession.flush() #transaction.commit() scompound2 = DBSession.query(SCompound).get(sid) if filename: sfile2 = [sfile] sfile2 += scompound2.filename scompound2.filename = sfile2 if reaction_file: reaction_sfile = [reaction_sfile] # reaction_sfile += scompound2.reaction scompound2.reaction = reaction_sfile else: shistory.changes = schanges scompound.history += [shistory] DBSession.add(shistory) DBSession.flush() flash(l_(u'Task completed successfully')) if kw and kw.has_key('come_from'): come_from = kw['come_from'] else: come_from = request.headers['Referer'] redirect(come_from)
def edit_project(self, *args, **kw): """ Edit Project. If you wish to allow users acces to the project- add them to group named as a project. """ try: project_id = args[0] except: redirect("error") userid = request.identity['repoze.who.userid'] # user = DBSession.query(User).filter_by(user_name=userid).first() try: come_from = request.headers['Referer'] except Exception: come_from = request.path_url try: project = DBSession.query(Projects).get(project_id) except: flash("Project not exist", "error") redirect(come_from) if kw: if 'come_from' in kw and kw['come_from'] != u'': come_from = kw['come_from'] if 'name' in kw and kw['name'] != u'': fp_lines = [] ct_lines = [] htrf_lines = [] for k, v in kw.iteritems(): if 'FP_Line_' in str(k) and v != u'': fp_lines.append(v) if 'CT_Line_' in str(k) and v != u'': ct_lines.append(v) if 'HTRF_Line_' in str(k) and v != u'': htrf_lines.append(v) if 'CT_Old_Line' in kw and kw['CT_Old_Line'] != u'': if isinstance(kw['CT_Old_Line'], basestring): if kw['CT_Old_Line'] != u'': ct_lines.append(kw['CT_Old_Line']) else: ct_lines += [ cell for cell in kw['CT_Old_Line'] if cell != u'' ] if 'FP_Old_Line' in kw and kw['FP_Old_Line'] != u'': if isinstance(kw['FP_Old_Line'], basestring): if kw['FP_Old_Line'] != u'': fp_lines.append(kw['FP_Old_Line']) else: fp_lines += [ cell for cell in kw['FP_Old_Line'] if cell != u'' ] if 'HTRF_Old_Line' in kw and kw['HTRF_Old_Line'] != u'': if isinstance(kw['HTRF_Old_Line'], basestring): if kw['HTRF_Old_Line'] != u'': htrf_lines.append(kw['HTRF_Old_Line']) else: htrf_lines += [ cell for cell in kw['HTRF_Old_Line'] if cell != u'' ] if not ct_lines: flash(l_(u'At least 1 CT_Line is required'), 'error') redirect(come_from) if not fp_lines: flash(l_(u'At least 1 FP_Line is required'), 'error') redirect(come_from) if not htrf_lines: flash(l_(u'At least 1 HTRF_Line is required'), 'error') redirect(come_from) #edit project name: if project.name != kw['name']: #change group name: gr = DBSession.query(Group).filter_by( group_name=project.name).first() gr.group_name = kw['name'] gr.display_name = kw['name'] #change permission name: perm = DBSession.query(Permission).filter( Permission.permission_name == project.name).first() perm.permission_name = kw['name'] project.name = kw['name'] #add description: if 'description' in kw and kw['description'] != u'' and kw[ 'description'] != project.description: project.description = kw['description'] #add cell lines import pickle if ct_lines: pickle_dump1 = pickle.dumps(ct_lines) ct_test = [ test for test in project.tests if test.name == 'CT' ][0] ct_test.cell_line = pickle_dump1 if fp_lines: pickle_dump2 = pickle.dumps(fp_lines) fp_test = [ test for test in project.tests if test.name == 'FP' ][0] fp_test.cell_line = pickle_dump2 if htrf_lines: pickle_dump3 = pickle.dumps(htrf_lines) htrf_test = [ test for test in project.tests if test.name == 'HTRF' ][0] htrf_test.cell_line = pickle_dump3 DBSession.flush() flash(l_(u'Task completed successfully')) redirect(come_from) else: flash(l_(u'Name is required'), 'error') redirect(come_from) return dict(page='index', userid=userid, project=project, come_from=come_from)
def index(self, page=1, *args, **kw): """ Index controller for molecules """ pname = request.environ['PATH_INFO'].split('/')[1] project = DBSession.query(Projects).filter(Projects.name==pname).first() alltags =[tag for tag in DBSession.query(Tags).order_by('name').all() ] from sqlalchemy import or_ compound = DBSession.query(Compound).filter(Compound.project.any(Projects.name==pname)).filter(or_(Compound.pcompounds != None, Compound.lcompounds != None)) dsc = True tmpl = '' selection = None similarity = None userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=userid).first() threshold = float(user.threshold)/100.0 items = user.items_per_page order = "gid" try: if kw['search'] != u'': search_clicked = kw['search'] else: search_clicked = None except Exception: search_clicked = None if kw: delkw = [] for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': order = v if str(k) != 'select' and str(k) != 'remove' and str(v) != u'': tmpl += str(k) + '=' + str(v) + '&' elif str(k) == 'select': try: if isinstance(kw['select'], basestring): selection = [kw['select']] else: selection = [id for id in kw['select']] except Exception: selection = None elif str(v) == u'': delkw.append(k) for k in delkw: del kw[k] if search_clicked: try: smiles = str(kw['smiles']) except Exception: smiles = None pass try: method = str(kw['method']) except Exception: method = None pass if smiles: if checksmi(smiles): from razi.functions import functions from razi.expression import TxtMoleculeElement if method == 'similarity': from razi.postgresql_rdkit import tanimoto_threshold DBSession.execute(tanimoto_threshold.set(threshold)) query_bfp = functions.morgan_b(TxtMoleculeElement(smiles), 2) constraint = Compound.morgan.tanimoto_similar(query_bfp) tanimoto_sml = Compound.morgan.tanimoto_similarity(query_bfp).label('tanimoto') limit = user.limit_sim search = DBSession.query(Compound, tanimoto_sml).filter(constraint).filter(Compound.project.any(Projects.name==pname)).order_by(desc(tanimoto_sml)).limit(limit).all() compound = () similarity = () for row in search: compound += (row[0], ) similarity += (row[1], ) page_url = paginate.PageURL_WebOb(request) currentPage = paginate.Page(compound, page, url=page_url, items_per_page=items) return dict(length=len(compound), compound=currentPage.items, currentPage=currentPage, tmpl=tmpl, page='samples', pname=pname, alltags=alltags, similarity=similarity) elif method == 'substructure': constraint = Compound.structure.contains(smiles) compound = DBSession.query(Compound).filter(constraint).filter(Compound.project.any(Projects.name==pname)) elif method == 'identity': compound = DBSession.query(Compound).filter(Compound.structure.equals(smiles)).filter(Compound.project.any(Projects.name==pname)) else: flash(l_(u'Smiles error'), 'warning') redirect(request.headers['Referer']) if kw.has_key('text_GID') and kw['text_GID'] !=u'': try: gid = int(kw['text_GID']) compound = compound.filter_by(gid = gid ) except Exception as msg: flash(l_(u'GID should be a number: %s' % msg), 'error') redirect(request.headers['Referer']) if kw.has_key('text_name') and kw['text_name'] !=u'': compound = compound.filter(Compound.names.any(Names.name.like(kw['text_name'].strip().replace('*', '%')))) if kw.has_key('text_creator') and kw['text_creator'] !=u'': compound = compound.filter(Compound.creator.like(kw['text_creator'].replace('*', '%'))) if kw.has_key('text_notes') and kw['text_notes'] !=u'': compound = compound.filter(Compound.notes.like(kw['text_notes'].replace('*', '%'))) if kw.has_key('date_from') and kw['date_from'] !=u'': date_from = datetime.strptime(str(kw['date_from']), '%Y-%m-%d') compound = compound.filter(Compound.create_date > date_from) else: date_from = None if kw.has_key('date_to') and kw['date_to'] !=u'': date_to = datetime.strptime(str(kw['date_to']), '%Y-%m-%d') if date_from: if date_to>date_from: compound = compound.filter(Compound.create_date < date_to) else: flash(l_(u'The End date must be later than the initial'), 'error') redirect(request.headers['Referer']) else: compound = compound.filter(Compound.create_date < date_to) try: tags = kw['text_tags'] except Exception: tags = None pass if tags: if isinstance(tags, basestring): tagi = eval(tags) if type(tagi) != type([]): tagi = [int(tags)] else: tagi = [int(id) for id in tags] # import sqlalchemy compound = compound.filter(Compound.tags.any(Tags.id.in_(tagi))) if selection and not search_clicked: argv ='' for arg in selection: argv += '/' + arg if kw['akcja'] == u'edit': if len(selection) == 1: redirect('/%s/samples/edit%s' % (pname, argv)) else: redirect('/%s/samples/multiedit/index%s' % (pname, argv)) elif kw['akcja'] == u'accept': if len(selection) == 1: redirect('/%s/samples/accept%s' % (pname, argv)) else: redirect('/%s/samples/multiaccept/index%s' % (pname, argv)) elif kw['akcja'] == u'library': if len(selection) == 1: redirect('/%s/samples/library%s' % (pname, argv)) else: redirect('/%s/samples/multilibrary/index%s' % (pname, argv)) elif kw['akcja'] == u'pdf': redirect('/%s/samples/index/download%s/pdf/samples_selected.pdf' % (pname, argv)) elif kw['akcja'] == u'xls': redirect('/%s/samples/download%s/xls/samples_selected.xls' % (pname, argv)) elif kw['akcja'] == u'txt': redirect('/%s/samples/download%s/txt/samples_selected.txt' % (pname, argv)) elif kw['akcja'] == u'delete': redirect('/%s/samples/remove%s' % (pname, argv)) else: flash(l_(u'Action error'), 'error') redirect(request.headers['Referer']) else: try: akcja = kw['akcja'] except Exception: akcja = None if akcja: if akcja == u'pdf': redirect('/%s/samples/index/download/pdf/samples_all.pdf' % pname) elif akcja == u'xls': redirect('/%s/samples/download/xls/samples_all.xls' % pname) elif akcja == u'txt': redirect('/%s/samples/download/txt/samples_all.txt' % pname) if dsc: compound = compound.order_by(desc(order).nullslast()) else: compound = compound.order_by((order)) page_url = paginate.PageURL_WebOb(request) currentPage = paginate.Page(compound, page, url=page_url, items_per_page=items) return dict(compound=currentPage.items, currentPage=currentPage, tmpl=tmpl, page='samples', pname=pname, alltags=alltags, similarity=similarity)
def new_project(self, *args, **kw): """ Create new project & group with correct permissions asigned. If you wish to allow users acces to the project- add them to group named as a project. """ userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=userid).first() try: come_from = request.headers['Referer'] except Exception: come_from = request.path_url if kw: if 'come_from' in kw and kw['come_from'] != u'': come_from = kw['come_from'] if 'name' in kw and kw['name'] != u'': cell_lines = [] fp_lines = [] htrf_lines = [] for k, v in kw.iteritems(): if 'Cell_Line_' in str(k) and v != u'': cell_lines.append(v.strip().replace(' ', '_')) if 'FP_Line_' in str(k) and v != u'': fp_lines.append(v.strip().replace(' ', '_')) if 'HTRF_Line_' in str(k) and v != u'': htrf_lines.append(v.strip().replace(' ', '_')) if not cell_lines: flash(l_(u'At least 1 Cell_Line is required'), 'error') redirect(come_from) if not fp_lines: flash(l_(u'At least 1 FP_Line is required'), 'error') redirect(come_from) if not htrf_lines: flash(l_(u'At least 1 HTRF_Line is required'), 'error') redirect(come_from) #create new project: project = Projects() project.name = kw['name'].strip().replace(' ', '_') #add group named as a project: gr = Group() gr.group_name = kw['name'].strip().replace(' ', '_') gr.display_name = kw['name'] gr.users.append(user) #add permission named as a project and assign it to group: from molgears.model import Permission perm = Permission() perm.permission_name = kw['name'].strip().replace(' ', '_') perm.groups += [gr] #add description: if 'description' in kw and kw['description'] != u'': project.description = kw['description'] #add test and cell lines ptest = ProjectTests() ptest.name = 'CT' fp_ptest = ProjectTests() fp_ptest.name = 'FP' htrf_ptest = ProjectTests() htrf_ptest.name = 'HTRF' project.tests = [fp_ptest, ptest, htrf_ptest] import pickle if cell_lines: pickle_dump1 = pickle.dumps(cell_lines) ptest.cell_line = pickle_dump1 if fp_lines: pickle_dump2 = pickle.dumps(fp_lines) fp_ptest.cell_line = pickle_dump2 if htrf_lines: pickle_dump3 = pickle.dumps(htrf_lines) htrf_ptest.cell_line = pickle_dump3 DBSession.add(perm) DBSession.add(gr) DBSession.add(ptest) DBSession.add(fp_ptest) DBSession.add(project) DBSession.flush() flash(l_(u'Task completed successfully')) redirect(come_from) else: flash(l_(u'Name is required'), 'error') redirect(come_from) return dict(page='index', userid=userid, come_from=come_from)
def put(self, *args, **kw): pname = request.environ['PATH_INFO'].split('/')[1] sid = int(args[0]) userid = request.identity['repoze.who.userid'] scompound = DBSession.query(SCompound).get(sid) shistory = SHistory() shistory.gid = scompound.mol.gid shistory.user = userid shistory.status = u'Edycja' schanges = u'' try: reason = kw['reason'] except Exception: reason = None pass if reason and reason != u'': schanges += u'UWAGA! niestandardowa zmiana z powodu:' + reason etap = int(kw['etap']) etap_max = int(kw['etap_max']) if etap < etap_max: scompound.effort[-1].etap = etap scompound.effort[-1].etap_max = etap_max scompound.status = DBSession.query(SStatus).get(2) schanges += u'; Bieżący etap: ' + str(etap) schanges += u'; Liczba etapow: ' + str(etap_max) else: flash( l_(u'Completed step must be smaller by 2 than the number of stages' ), 'error') redirect(request.headers['Referer']) # scompound.status_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if kw.has_key('lso') and kw['lso'] != scompound.lso: scompound.lso = kw['lso'] schanges += u'; LSO: ' + kw['lso'] if kw.has_key('notes') and kw['notes'] != scompound.notes: scompound.notes = kw['notes'] schanges += u';Notes: ' + kw['notes'] try: filename = kw['loadfile'].filename import os filename = os.path.basename(filename) except Exception as msg: filename = None pass try: reaction_file = kw['reaction'].filename import os reaction_file = os.path.basename(reaction_file) except Exception as msg: reaction_file = None pass if kw['owner'] != scompound.owner: scompound.owner = kw['owner'] schanges += u'; Wlasciciel:' + kw['owner'] if kw['principal'] != scompound.principal: scompound.principal = kw['principal'] schanges += u'; Odbiorca:' + kw['principal'] if kw.has_key('priority') and kw['priority'] != u'': scompound.priority = int(kw['priority']) schanges += u'; Priorytet:' + kw['priority'] pcompound = DBSession.query(PCompound).get(scompound.pid) if pcompound: pcompound.priority = int(kw['priority']) phistory = PHistory() phistory.project = pname phistory.date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") phistory.user = userid phistory.status = 'Priorytet' phistory.changes = u'Priority: ' + kw['priority'] pcompound.history += [phistory] DBSession.add(phistory) if filename or reaction_file: if filename: number = DBSession.query(SFiles).count() + 1 newfilename = str(number) + '_' + userid + '_' + str( sid) + '_' + filename newfilename.replace(' ', '_') f_path = os.path.join(files_dir, newfilename) try: f = file(f_path, "w") f.write(kw['loadfile'].value) f.close() except Exception as msg: flash(l_(msg), 'error') redirect(request.headers['Referer']) sfile = SFiles() sfile.name = filename sfile.filename = newfilename if kw['opis']: sfile.description = kw['opis'] schanges += u'; Plik: ' + filename + u' ( ' + newfilename + u' )' DBSession.add(sfile) if reaction_file: number2 = DBSession.query(SFiles).count() + 1 newfilename2 = str(number2) + '_' + userid + '_' + str( sid) + '_' + reaction_file newfilename2.replace(' ', '_') f_path2 = os.path.join(files_dir, newfilename2) try: f2 = file(f_path2, "w") f2.write(kw['reaction'].value) f2.close() except Exception as msg: flash(l_(msg), 'error') redirect(request.headers['Referer']) reaction_sfile = SFiles() reaction_sfile.name = reaction_file reaction_sfile.filename = newfilename2 schanges += u'; Sciezka reakcji: ' + reaction_file + u' ( ' + newfilename2 + u' )' DBSession.add(reaction_sfile) shistory.changes = schanges scompound.history += [shistory] DBSession.add(shistory) DBSession.flush() #transaction.commit() scompound2 = DBSession.query(SCompound).get(sid) if filename: sfile2 = [sfile] sfile2 += scompound2.filename scompound2.filename = sfile2 if reaction_file: reaction_sfile = [reaction_sfile] # reaction_sfile += scompound2.reaction scompound2.reaction = reaction_sfile else: shistory.changes = schanges scompound.history += [shistory] DBSession.add(shistory) DBSession.flush() flash(l_(u'Task completed successfully')) if kw and kw.has_key('come_from'): come_from = kw['come_from'] else: come_from = request.headers['Referer'] redirect(come_from)
def index(self, page=1, *args, **kw): """ Index controller for molecules """ pname = request.environ['PATH_INFO'].split('/')[1] project = DBSession.query(Projects).filter( Projects.name == pname).first() alltags = [tag for tag in DBSession.query(Tags).order_by('name').all()] from sqlalchemy import or_ compound = DBSession.query(Compound).filter( Compound.project.any(Projects.name == pname)).filter( or_(Compound.pcompounds != None, Compound.lcompounds != None)) dsc = True tmpl = '' selection = None similarity = None userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=userid).first() threshold = float(user.threshold) / 100.0 items = user.items_per_page order = "gid" try: if kw['search'] != u'': search_clicked = kw['search'] else: search_clicked = None except Exception: search_clicked = None if kw: delkw = [] for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': order = v if str(k) != 'select' and str(k) != 'remove' and str(v) != u'': tmpl += str(k) + '=' + str(v) + '&' elif str(k) == 'select': try: if isinstance(kw['select'], basestring): selection = [kw['select']] else: selection = [id for id in kw['select']] except Exception: selection = None elif str(v) == u'': delkw.append(k) for k in delkw: del kw[k] if search_clicked: try: smiles = str(kw['smiles']) except Exception: smiles = None pass try: method = str(kw['method']) except Exception: method = None pass if smiles: if checksmi(smiles): from razi.functions import functions from razi.expression import TxtMoleculeElement if method == 'similarity': from razi.postgresql_rdkit import tanimoto_threshold DBSession.execute( tanimoto_threshold.set(threshold)) query_bfp = functions.morgan_b( TxtMoleculeElement(smiles), 2) constraint = Compound.morgan.tanimoto_similar( query_bfp) tanimoto_sml = Compound.morgan.tanimoto_similarity( query_bfp).label('tanimoto') limit = user.limit_sim search = DBSession.query( Compound, tanimoto_sml).filter(constraint).filter( Compound.project. any(Projects.name == pname)).order_by( desc(tanimoto_sml)).limit(limit).all() compound = () similarity = () for row in search: compound += (row[0], ) similarity += (row[1], ) page_url = paginate.PageURL_WebOb(request) currentPage = paginate.Page(compound, page, url=page_url, items_per_page=items) return dict(length=len(compound), compound=currentPage.items, currentPage=currentPage, tmpl=tmpl, page='samples', pname=pname, alltags=alltags, similarity=similarity) elif method == 'substructure': constraint = Compound.structure.contains(smiles) compound = DBSession.query(Compound).filter( constraint).filter( Compound.project.any( Projects.name == pname)) elif method == 'identity': compound = DBSession.query(Compound).filter( Compound.structure.equals(smiles)).filter( Compound.project.any( Projects.name == pname)) else: flash(l_(u'Smiles error'), 'warning') redirect(request.headers['Referer']) if kw.has_key('text_GID') and kw['text_GID'] != u'': try: gid = int(kw['text_GID']) compound = compound.filter_by(gid=gid) except Exception as msg: flash(l_(u'GID should be a number: %s' % msg), 'error') redirect(request.headers['Referer']) if kw.has_key('text_name') and kw['text_name'] != u'': compound = compound.filter( Compound.names.any( Names.name.like(kw['text_name'].strip().replace( '*', '%')))) if kw.has_key('text_creator') and kw['text_creator'] != u'': compound = compound.filter( Compound.creator.like(kw['text_creator'].replace( '*', '%'))) if kw.has_key('text_notes') and kw['text_notes'] != u'': compound = compound.filter( Compound.notes.like(kw['text_notes'].replace('*', '%'))) if kw.has_key('date_from') and kw['date_from'] != u'': date_from = datetime.strptime(str(kw['date_from']), '%Y-%m-%d') compound = compound.filter( Compound.create_date > date_from) else: date_from = None if kw.has_key('date_to') and kw['date_to'] != u'': date_to = datetime.strptime(str(kw['date_to']), '%Y-%m-%d') if date_from: if date_to > date_from: compound = compound.filter( Compound.create_date < date_to) else: flash( l_(u'The End date must be later than the initial' ), 'error') redirect(request.headers['Referer']) else: compound = compound.filter( Compound.create_date < date_to) try: tags = kw['text_tags'] except Exception: tags = None pass if tags: if isinstance(tags, basestring): tagi = eval(tags) if type(tagi) != type([]): tagi = [int(tags)] else: tagi = [int(id) for id in tags] # import sqlalchemy compound = compound.filter( Compound.tags.any(Tags.id.in_(tagi))) if selection and not search_clicked: argv = '' for arg in selection: argv += '/' + arg if kw['akcja'] == u'edit': if len(selection) == 1: redirect('/%s/samples/edit%s' % (pname, argv)) else: redirect('/%s/samples/multiedit/index%s' % (pname, argv)) elif kw['akcja'] == u'accept': if len(selection) == 1: redirect('/%s/samples/accept%s' % (pname, argv)) else: redirect('/%s/samples/multiaccept/index%s' % (pname, argv)) elif kw['akcja'] == u'library': if len(selection) == 1: redirect('/%s/samples/library%s' % (pname, argv)) else: redirect('/%s/samples/multilibrary/index%s' % (pname, argv)) elif kw['akcja'] == u'pdf': redirect( '/%s/samples/index/download%s/pdf/samples_selected.pdf' % (pname, argv)) elif kw['akcja'] == u'xls': redirect('/%s/samples/download%s/xls/samples_selected.xls' % (pname, argv)) elif kw['akcja'] == u'txt': redirect('/%s/samples/download%s/txt/samples_selected.txt' % (pname, argv)) elif kw['akcja'] == u'delete': redirect('/%s/samples/remove%s' % (pname, argv)) else: flash(l_(u'Action error'), 'error') redirect(request.headers['Referer']) else: try: akcja = kw['akcja'] except Exception: akcja = None if akcja: if akcja == u'pdf': redirect('/%s/samples/index/download/pdf/samples_all.pdf' % pname) elif akcja == u'xls': redirect('/%s/samples/download/xls/samples_all.xls' % pname) elif akcja == u'txt': redirect('/%s/samples/download/txt/samples_all.txt' % pname) if dsc: compound = compound.order_by(desc(order).nullslast()) else: compound = compound.order_by((order)) page_url = paginate.PageURL_WebOb(request) currentPage = paginate.Page(compound, page, url=page_url, items_per_page=items) return dict(compound=currentPage.items, currentPage=currentPage, tmpl=tmpl, page='samples', pname=pname, alltags=alltags, similarity=similarity)
def myaccount(self): """Let the user know that's visiting a protected controller.""" userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter(User.user_name == userid).first() # flash(u'Zapisanie zmian wymaga podania obecnego hasła.', 'warning') return dict(user=user, page='index')
def multiedit(self, *args, **kw): pname = request.environ['PATH_INFO'].split('/')[1] alltags =[tag for tag in DBSession.query(Tags).order_by('name').all() ] principals = DBSession.query (Group).get(3) owners = DBSession.query (Group).get(2) come_from = request.headers['Referer'] if kw: try: if isinstance(kw['argv'], basestring): argv = [kw['argv']] else: argv = [id for id in kw['argv']] except Exception: argv = None try: if kw.has_key('notes') != u'': notes = kw['notes'] else: notes = None except Exception: notes = None try: priority = int(kw['priority']) except Exception: priority = None if argv: userid = request.identity['repoze.who.userid'] for arg in argv: try: if isinstance(kw['text_tags'], basestring): tagi = [DBSession.query( Tags ).get(int(kw['text_tags']))] else: tagi = [DBSession.query( Tags ).get(int(id)) for id in kw['text_tags']] except Exception: tagi = None scompound = DBSession.query(SCompound).get(int(arg)) shistory = SHistory() shistory.gid = scompound.mol.gid shistory.user = userid shistory.status = u'Multi - edit' shistory.changes = u'' if kw.has_key('owner') and kw['owner'] != u'None' and kw['owner'] != scompound.owner: scompound.owner = kw['owner'] shistory.changes += u' Właściciel: ' + kw['owner'] + ';' if kw.has_key('principal') and kw['principal'] != u'None' and kw['principal'] != scompound.principal: scompound.principal = kw['principal'] shistory.changes += u' Odbiorca: ' + kw['principal'] + ';' if priority and priority != scompound.priority: scompound.priority = int(kw['priority']) shistory.changes += u'; Priorytet: ' + kw['priority'] + ';' pcompound = DBSession.query(PCompound).get(scompound.pid) if pcompound: pcompound.priority = int(kw['priority']) phistory = PHistory() phistory.project = pname phistory.date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") phistory.user = userid phistory.status = 'Priorytet' phistory.changes = u'Priority: ' + kw['priority'] pcompound.history += [phistory] DBSession.add(phistory) if tagi and scompound.mol.tags != tagi: scompound.mol.tags = tagi shistory.changes += u' Tags: ' for tag in tagi: shistory.changes += str(tag.name) + ';' if notes and notes != scompound.notes: scompound.notes = notes shistory.changes += u' Notes: ' + notes scompound.history += [shistory] DBSession.add(shistory) DBSession.flush() #transaction.commit() if kw.has_key('come_from'): come_from = kw['come_from'] else: come_from = request.headers['Referer'] flash(l_(u'Task completed successfully')) redirect(come_from) return dict(alltags=alltags, args=args, users=principals.users, owners=owners.users, come_from=come_from, page='kierownik', pname=pname)
def test_query_obj(self): """Model objects can be queried""" obj = DBSession.query(self.klass).one() for key, value in self.attrs.items(): eq_(getattr(obj, key), value)
def multiedit(self, *args, **kw): pname = request.environ['PATH_INFO'].split('/')[1] alltags = [tag for tag in DBSession.query(Tags).order_by('name').all()] principals = DBSession.query(Group).get(3) owners = DBSession.query(Group).get(2) come_from = request.headers['Referer'] if kw: try: if isinstance(kw['argv'], basestring): argv = [kw['argv']] else: argv = [id for id in kw['argv']] except Exception: argv = None try: if kw.has_key('notes') != u'': notes = kw['notes'] else: notes = None except Exception: notes = None try: priority = int(kw['priority']) except Exception: priority = None if argv: userid = request.identity['repoze.who.userid'] for arg in argv: try: if isinstance(kw['text_tags'], basestring): tagi = [ DBSession.query(Tags).get(int(kw['text_tags'])) ] else: tagi = [ DBSession.query(Tags).get(int(id)) for id in kw['text_tags'] ] except Exception: tagi = None scompound = DBSession.query(SCompound).get(int(arg)) shistory = SHistory() shistory.gid = scompound.mol.gid shistory.user = userid shistory.status = u'Multi - edit' shistory.changes = u'' if kw.has_key('owner') and kw['owner'] != u'None' and kw[ 'owner'] != scompound.owner: scompound.owner = kw['owner'] shistory.changes += u' Właściciel: ' + kw['owner'] + ';' if kw.has_key( 'principal') and kw['principal'] != u'None' and kw[ 'principal'] != scompound.principal: scompound.principal = kw['principal'] shistory.changes += u' Odbiorca: ' + kw[ 'principal'] + ';' if priority and priority != scompound.priority: scompound.priority = int(kw['priority']) shistory.changes += u'; Priorytet: ' + kw[ 'priority'] + ';' pcompound = DBSession.query(PCompound).get( scompound.pid) if pcompound: pcompound.priority = int(kw['priority']) phistory = PHistory() phistory.project = pname phistory.date = datetime.now().strftime( "%Y-%m-%d %H:%M:%S") phistory.user = userid phistory.status = 'Priorytet' phistory.changes = u'Priority: ' + kw['priority'] pcompound.history += [phistory] DBSession.add(phistory) if tagi and scompound.mol.tags != tagi: scompound.mol.tags = tagi shistory.changes += u' Tags: ' for tag in tagi: shistory.changes += str(tag.name) + ';' if notes and notes != scompound.notes: scompound.notes = notes shistory.changes += u' Notes: ' + notes scompound.history += [shistory] DBSession.add(shistory) DBSession.flush() #transaction.commit() if kw.has_key('come_from'): come_from = kw['come_from'] else: come_from = request.headers['Referer'] flash(l_(u'Task completed successfully')) redirect(come_from) return dict(alltags=alltags, args=args, users=principals.users, owners=owners.users, come_from=come_from, page='kierownik', pname=pname)
def new_user(self, *args, **kw): """ Add new User. """ try: come_from = request.headers['Referer'] except Exception: come_from = request.path_url groups = DBSession.query(Group).all() if kw: if 'come_from' in kw and kw['come_from'] != u'': come_from = kw['come_from'] if 'password' in kw and kw['password'] != u'': new = kw['password'] if 'verification' in kw and kw[ 'verification'] != u'' and new != kw['verification']: flash(l_(u'Password not match'), 'error') redirect(come_from) else: flash(l_('Verification error'), 'error') else: flash(l_(u'Password is required'), 'error') redirect(come_from) if 'email' in kw and kw['email'] != u'': email = kw['email'] else: flash(l_('Email is required'), 'error') redirect(come_from) if 'items_per_page' in kw and kw['items_per_page'] != u'': try: items_per_page = int(kw['items_per_page']) except Exception: flash(l_('Compounds per page should be a number'), 'error') else: flash(l_('Compounds per page required'), 'error') redirect(come_from) if 'user_name' in kw and kw['user_name'] != u'': user = User() user.user_name = kw['user_name'].strip().replace(' ', '.') else: flash(l_('User name is required'), 'error') redirect(come_from) if 'display_name' in kw and kw['display_name'] != u'': user.display_name = kw['display_name'] if 'groups' in kw and kw['groups'] != u'': if isinstance(kw['groups'], basestring): groups = [DBSession.query(Group).get(kw['groups'])] else: groups = [ DBSession.query(Group).get(group_id) for group_id in kw['groups'] ] else: flash(l_('Group is required'), 'error') redirect(come_from) if items_per_page: if items_per_page > 10 and items_per_page < 150: user.items_per_page = items_per_page else: flash( l_(u'Number of Compound per page should be between 10 and 150' ), 'error') redirect(come_from) if email: import re if len(email) >= 6: if re.match( "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None: user.email_address = email else: flash(l_(u'Email error'), 'warning') redirect(come_from) else: flash(l_(u'Email error'), 'warning') redirect(come_from) else: flash(l_(u'Email not changed'), 'warning') if new: if len(new) >= 6: user._set_password(new) else: flash(l_(u'Password error'), 'error') redirect(come_from) else: flash(l_('Password is required'), 'error') redirect(come_from) if groups: for group in groups: group.users.append(user) else: flash(l_('Gropus error'), 'error') redirect(come_from) DBSession.add(user) DBSession.flush() flash(l_(u'Task completed successfully')) redirect(come_from) return dict(page='index', come_from=come_from, groups=groups, pname=None)
def by_email_address(cls, email): """Return the user object whose email address is ``email``.""" return DBSession.query(cls).filter_by(email_address=email).first()
def by_user_name(cls, username): """Return the user object whose user name is ``username``.""" return DBSession.query(cls).filter_by(user_name=username).first()
def details(self, id, **kw): id = int(id) pains = DBSession.query(PAINS2).get(id) return dict(pains=pains, page='pains2', pname = 'pains')
def _do_get_provider_count_and_objs(self, name=None, **kw): userid = request.identity['repoze.who.userid'] scompound = () dsc = True order = 'id' if kw: try: smiles = kw['smi'] method = kw['method'] except Exception: smiles = None method = None pass try: ogranicz_tekst = kw['ogranicz_tekst'] except Exception: ogranicz_tekst = None pass if smiles: if checksmi(smiles): from razi.functions import functions from razi.expression import TxtMoleculeElement if method == 'similarity': query_bfp = functions.morgan_b(TxtMoleculeElement(smiles), 2) constraint = SCompound.morgan.dice_similar(query_bfp) dice_sml = SCompound.morgan.dice_similarity(query_bfp).label('dice') # scompound = DBSession.query(SCompound, dice_sml).filter(constraint).filter(SCompound.owner.contains(userid)) scompound = DBSession.query(SCompound).filter(constraint).filter(SCompound.owner.contains(userid)) elif method == 'substructure': constraint = SCompound.structure.contains(smiles) scompound = DBSession.query(SCompound).filter(constraint).filter(SCompound.owner.contains(userid)) elif method == 'identity': scompound = DBSession.query(SCompound).filter(SCompound.structure.equals(smiles)).filter(SCompound.owner.contains(userid)) # if ogranicz_tekst: # scompound = scompound.filter(SCompound.__getattribute__(SCompound, kw['ogranicz']).like(ogranicz_tekst)) else: flash('SMILES error', 'warning') scompound = () else: scompound = DBSession.query(SCompound).filter(SCompound.owner.contains(userid)) if ogranicz_tekst: if kw['ogranicz'] == 'p_id': try: p_id = int(ogranicz_tekst) scompound = scompound.filter_by(p_id = p_id ) except Exception as msg: flash('P_id should be a number: %s' % msg, 'error') else: scompound = scompound.filter(SCompound.__getattribute__(SCompound, kw['ogranicz']).like(ogranicz_tekst)) try: tagi = kw['tags'] except Exception: tagi = None pass if isinstance(tagi, basestring): tagi_id = [int(tagi)] else: tagi_id = [int(id) for id in tagi] if tagi_id: import sqlalchemy scompound = scompound.filter(SCompound.tags.any(Tags.tags_id.in_(tagi_id))) # scompound = scompound.filter(SCompound.tags.contain(tagi_id)) # scompound = scompound.join(SCompound.tags).filter_by(not_(tags_id = tagi_id[0])) if int(kw['status']) > 0: scompound = scompound.filter(SCompound.status_id == int(kw['status'])) for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': order = v if scompound: if dsc: scompound = scompound.order_by(desc(order)) else: scompound = scompound.order_by((order)) scompound = scompound.all() # scompound = scompound.all() return len(scompound), scompound
def reagents(self, page=1, *args, **kw): pname = request.environ['PATH_INFO'].split('/')[1] history = DBSession.query(RHistory).filter( RHistory.project.any(Projects.name == pname)) order = 'RHistory.id' userid = request.identity['repoze.who.userid'] user = DBSession.query(User).filter_by(user_name=userid).first() items = user.items_per_page tmpl = '' dsc = True from datetime import timedelta now = datetime.now() one_day = timedelta(days=1) try: if kw['search'] != u'': search_clicked = kw['search'] else: search_clicked = None except Exception: search_clicked = None if kw: for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': if v == 'gid': order = RHistory.reagents_id elif v == 'user': order = RHistory.user elif v == 'date': order = RHistory.date else: order = v if str(k) != 'remove': tmpl += str(k) + '=' + str(v) + '&' if search_clicked: if kw.has_key('text_GID') and kw['text_GID'] != u'': try: gid = int(kw['text_gid']) history = history.filter(Reagents.rid == gid) except Exception as msg: flash(l_(u'ID should be a number: %s' % msg), 'error') redirect(request.headers['Referer']) if kw.has_key('text_user') and kw['text_user'] != u'': history = history.filter( RHistory.user.like(kw['text_user'].replace('*', '%'))) if kw.has_key('text_status') and kw['text_status'] != u'': history = history.filter( RHistory.status.like(kw['text_status'].replace( '*', '%'))) if kw.has_key('text_changes') and kw['text_changes'] != u'': history = history.filter( RHistory.changes.like(kw['text_changes'].replace( '*', '%'))) if kw.has_key('date_from') and kw['date_from'] != u'': date_from = datetime.strptime(str(kw['date_from']), '%Y-%m-%d') history = history.filter(RHistory.date > date_from) else: date_from = None if kw.has_key('date_to') and kw['date_to'] != u'': date_to = datetime.strptime(str(kw['date_to']), '%Y-%m-%d') if date_from: if date_to > date_from: history = history.filter(RHistory.date < date_to) else: flash( l_(u'The End date must be later than the initial' ), 'error') redirect(request.headers['Referer']) else: history = history.filter(RHistory.date < date_to) if dsc: history = history.order_by(desc(order).nullslast()) else: history = history.order_by((order)) page_url = paginate.PageURL_WebOb(request) currentPage = paginate.Page(history, page, url=page_url, items_per_page=items) return dict(history=currentPage.items, currentPage=currentPage, tmpl=tmpl, one_day=one_day, now=now, page='kierownik', pname=pname)
def _do_get_provider_count_and_objs(self, name=None, **kw): userid = request.identity['repoze.who.userid'] scompound = () dsc = True order = 'id' if kw: try: smiles = kw['smi'] method = kw['method'] except Exception: smiles = None method = None pass try: ogranicz_tekst = kw['ogranicz_tekst'] except Exception: ogranicz_tekst = None pass if smiles: if checksmi(smiles): from razi.functions import functions from razi.expression import TxtMoleculeElement if method == 'similarity': query_bfp = functions.morgan_b( TxtMoleculeElement(smiles), 2) constraint = SCompound.morgan.dice_similar(query_bfp) dice_sml = SCompound.morgan.dice_similarity( query_bfp).label('dice') # scompound = DBSession.query(SCompound, dice_sml).filter(constraint).filter(SCompound.owner.contains(userid)) scompound = DBSession.query( SCompound).filter(constraint).filter( SCompound.owner.contains(userid)) elif method == 'substructure': constraint = SCompound.structure.contains(smiles) scompound = DBSession.query( SCompound).filter(constraint).filter( SCompound.owner.contains(userid)) elif method == 'identity': scompound = DBSession.query(SCompound).filter( SCompound.structure.equals(smiles)).filter( SCompound.owner.contains(userid)) # if ogranicz_tekst: # scompound = scompound.filter(SCompound.__getattribute__(SCompound, kw['ogranicz']).like(ogranicz_tekst)) else: flash('SMILES error', 'warning') scompound = () else: scompound = DBSession.query(SCompound).filter( SCompound.owner.contains(userid)) if ogranicz_tekst: if kw['ogranicz'] == 'p_id': try: p_id = int(ogranicz_tekst) scompound = scompound.filter_by(p_id=p_id) except Exception as msg: flash('P_id should be a number: %s' % msg, 'error') else: scompound = scompound.filter( SCompound.__getattribute__( SCompound, kw['ogranicz']).like(ogranicz_tekst)) try: tagi = kw['tags'] except Exception: tagi = None pass if isinstance(tagi, basestring): tagi_id = [int(tagi)] else: tagi_id = [int(id) for id in tagi] if tagi_id: import sqlalchemy scompound = scompound.filter( SCompound.tags.any(Tags.tags_id.in_(tagi_id))) # scompound = scompound.filter(SCompound.tags.contain(tagi_id)) # scompound = scompound.join(SCompound.tags).filter_by(not_(tags_id = tagi_id[0])) if int(kw['status']) > 0: scompound = scompound.filter( SCompound.status_id == int(kw['status'])) for k, v in kw.iteritems(): if str(k) == 'desc' and str(v) != '1': dsc = None elif str(k) == 'order_by': order = v if scompound: if dsc: scompound = scompound.order_by(desc(order)) else: scompound = scompound.order_by((order)) scompound = scompound.all() # scompound = scompound.all() return len(scompound), scompound