예제 #1
0
def post_delete(id):
    post = db_session.query(Post).get(id)
    if post is None:
        abort(404)
    db_session.delete(post)
    db_session.commit()
    return redirect(url_for('index'))
예제 #2
0
    def test_source_is_deleted_while_logged_in(self, logger):
        """If a source is deleted by a journalist when they are logged in,
        a NoResultFound will occur. The source should be redirected to the
        index when this happens, and a warning logged."""

        with self.client as client:
            codename = new_codename(client, session)
            resp = client.post('login', data=dict(codename=codename),
                               follow_redirects=True)

            # Now the journalist deletes the source
            filesystem_id = crypto_util.hash_codename(codename)
            crypto_util.delete_reply_keypair(filesystem_id)
            source = Source.query.filter_by(filesystem_id=filesystem_id).one()
            db_session.delete(source)
            db_session.commit()

            # Source attempts to continue to navigate
            resp = client.post('/lookup', follow_redirects=True)
            self.assertEqual(resp.status_code, 200)
            self.assertIn('Submit documents for the first time', resp.data)
            self.assertNotIn('logged_in', session.keys())
            self.assertNotIn('codename', session.keys())

        logger.assert_called_once_with(
            "Found no Sources when one was expected: "
            "No row was found for one()")
예제 #3
0
def delete_user(args):
    """Deletes a journalist or administrator from the application."""
    username = _get_username_to_delete()
    try:
        selected_user = Journalist.query.filter_by(username=username).one()
    except NoResultFound:
        print('ERROR: That user was not found!')
        return 0

    # Confirm deletion if user is found
    if not _get_delete_confirmation(selected_user.username):
        return 0

    # Try to delete user from the database
    try:
        db_session.delete(selected_user)
        db_session.commit()
    except Exception as e:
        # If the user was deleted between the user selection and confirmation,
        # (e.g., through the web app), we don't report any errors. If the user
        # is still there, but there was a error deleting them from the
        # database, we do report it.
        try:
            Journalist.query.filter_by(username=username).one()
        except NoResultFound:
            pass
        else:
            raise e

    print('User "{}" successfully deleted'.format(username))
    return 0
예제 #4
0
def categories_list():

    #if errors detected
    errors = []

    #saved?
    saved = False

    if request.method == 'POST':
        categories = []

        saved = True

        for field in request.form:
            if field.startswith('title'):
                not_needed, category_id = field.split('-')
                categories.append(category_id)

        for category_id in categories:
            category = Category.query.get(int(category_id))
            category.title = escape(request.form['title-' + category_id])
            category.description = escape(request.form['description-' + category_id])

            try:
                db_session.add(category)
                db_session.commit()
            except exc.SQLAlchemyError:
                db_session.rollback()
                errors += ['Error saving category #{0}\n'.format(category.id)]
                saved = False

        if request.form['new-title']:
            category = Category(escape(request.form['new-title']), escape(request.form['new-description']))
            try:
                db_session.add(category)
                db_session.commit()
            except exc.SQLAlchemyError:
                db_session.rollback()
                errors += ['Error with new category']
                saved = False

    category_to_delete = request.values.get('delete', False)
    if category_to_delete:
        category = Category.query.get(int(category_to_delete))

        db_session.delete(category)
        db_session.commit()

        return redirect(url_for('categories_list'))

    categories = Category.query.all()

    prop = dict()
    prop.update(default)
    prop['categories'] = categories
    prop['saved'] = saved
    prop['errors'] = errors

    return render_template('admin/categories_list.html', **prop)
예제 #5
0
def bulk_delete(sid, items_selected):
    for item in items_selected:
        item_path = store.path(sid, item.filename)
        worker.enqueue(store.secure_unlink, item_path)
        db_session.delete(item)
    db_session.commit()

    flash("Submission{} deleted.".format("s" if len(items_selected) > 1 else ""), "notification")
    return redirect(url_for("col", sid=sid))
예제 #6
0
def delete_task(task_id, group_id):
    print "taskid = " + task_id
    print "group_id = " + group_id
    query_result = db_session.query(models.Task).filter(models.Task.id==int(task_id)).first()
    if query_result:
        db_session.delete(query_result)
        db_session.commit()
        updated_query = db_session.query(models.Task).filter(models.Task.group_id==int(group_id)).order_by(models.Task.date).all()
        return utils.list_to_json('tasks', updated_query)
    return utils.error_json_message("invalid task id")
예제 #7
0
def delete_collection(source_id):
    # Delete the source's collection of submissions
    worker.enqueue(store.delete_source_directory, source_id)

    # Delete the source's reply keypair
    crypto_util.delete_reply_keypair(source_id)

    # Delete their entry in the db
    source = get_source(source_id)
    db_session.delete(source)
    db_session.commit()
예제 #8
0
def bulk_delete(filesystem_id, items_selected):
    for item in items_selected:
        item_path = store.path(filesystem_id, item.filename)
        worker.enqueue(srm, item_path)
        db_session.delete(item)
    db_session.commit()

    flash(ngettext("Submission deleted.",
                   "{num} submissions deleted.".format(
                       num=len(items_selected)),
                   len(items_selected)), "notification")
    return redirect(url_for('col.col', filesystem_id=filesystem_id))
예제 #9
0
def delete_collection(filesystem_id):
    # Delete the source's collection of submissions
    job = worker.enqueue(srm, store.path(filesystem_id))

    # Delete the source's reply keypair
    crypto_util.delete_reply_keypair(filesystem_id)

    # Delete their entry in the db
    source = get_source(filesystem_id)
    db_session.delete(source)
    db_session.commit()
    return job
예제 #10
0
def del_entry(view,id): 
	if view=='books':
		entry = db_session.query(Book).filter(Book.id==id).first()
	else:
		entry = db_session.query(Author).filter(Author.id==id).first()
	if entry:
		db_session.delete(entry)
		db_session.commit()		
		flash('%s successfuly removed from database' % entry.name)
	else:
		flash('No entry with id = %d' % id)
	return redirect(url_for('admin_show_entries',pagin = app.config['PAGIN'], page=1, view=view))
예제 #11
0
    def delete_user(user_id):
        user = Journalist.query.get(user_id)
        if user:
            db_session.delete(user)
            db_session.commit()
            flash(gettext("Deleted user '{user}'").format(
                user=user.username), "notification")
        else:
            current_app.logger.error(
                "Admin {} tried to delete nonexistent user with pk={}".format(
                    g.user.username, user_id))
            abort(404)

        return redirect(url_for('admin.index'))
예제 #12
0
def clients_list():
    clients = Client.query.all()

    client_to_delete = request.values.get('delete', False)
    if client_to_delete:
        client = Client.query.get(int(client_to_delete))

        db_session.delete(client)
        db_session.commit()

        return redirect(url_for('clients_list'))

    prop = dict()
    prop.update(default)
    prop['clients'] = clients

    return render_template('admin/clients_list.html', **prop)
예제 #13
0
def projects_list():
    """ Projects list
    """

    project_to_delete = request.values.get('delete', False)
    if project_to_delete:
        project = Project.query.get(int(project_to_delete))
        db_session.delete(project)
        db_session.commit()

        return redirect(url_for('projects_list'))

    projects = Project.query.all()

    prop = dict()
    prop.update(default)
    prop['projects'] = projects

    return render_template('admin/projects_list.html', **prop)
예제 #14
0
    def mutate(self, info, orgCode):

        import utils
        if utils.isAllowAccess():
            result = OrgDelete()

            from db_models.orgSelection import isOrgByOrgCodeExist, selectOrgByOrgCode
            if isOrgByOrgCodeExist(orgCode):
                toDeleteOrg = selectOrgByOrgCode(orgCode)

                db_session.delete(toDeleteOrg)
                db_session.commit()

                result.status = True
                result.msg = "Delete organziation by orgCode '{}' success.".format(
                    orgCode)
            else:
                result.msg = "Org by this orgCode '{}' is not exist.".format(
                    orgCode)

            return result
예제 #15
0
    def mutate(self, info, peopleCode):

        import utils
        if utils.isAllowAccess():

            msg = ''
            status = False

            from mutation_people import isPeopleByPCodeExist, selectPeopleByPCode
            if isPeopleByPCodeExist(peopleCode, info):
                delettingPeople = selectPeopleByPCode(peopleCode, info)

                db_session.delete(delettingPeople)
                db_session.commit()

                status = True
                msg = 'delete pCode\'s {} success.'.format(peopleCode)
            else:
                msg = 'This pCode\'s {} is not exist'.format(peopleCode)

            return DeletePeople(peopleCode=peopleCode, msg=msg, status=status)
예제 #16
0
    def get(self, qty):
        # Firstly, delete old entries
        while EntryModel.query.first():
            entry = EntryModel.query.first()
            db_session.delete(entry)
            db_session.commit()

        # Create some new entries for every method call
        for idx in range(qty):
            header = get_header(idx)
            publisher = get_publisher(idx)
            content = get_content(idx)
            link = get_link(idx)
            n_days_ago = get_num_days_ago(idx)
            img = get_base64_img(idx)
            entry = EntryModel(header, publisher, content, link, n_days_ago,
                               img)
            db_session.add(entry)
            db_session.commit()

        return EntryModel.query.limit(qty).all()
예제 #17
0
def delete_user():  # pragma: no cover
    """Deletes a journalist or administrator from the application."""
    # Select user to delete
    username = raw_input('Username to delete: ')
    try:
        selected_user = Journalist.query.filter_by(username=username).one()
    except NoResultFound:
        print('ERROR: That user was not found!')
        return 0

    # Confirm deletion if user is found
    confirmation = raw_input('Are you sure you want to delete user '
                             '{} (y/n)?'.format(selected_user))
    if confirmation.lower() != 'y':
        print('Confirmation not received: user "{}" was NOT '
              'deleted'.format(username))
        return 0

    # Try to delete user from the database
    try:
        db_session.delete(selected_user)
        db_session.commit()
    except:
        # If the user was deleted between the user selection and confirmation,
        # (e.g., through the web app), we don't report any errors. If the user
        # is still there, but there was a error deleting them from the
        # database, we do report it.
        try:
            selected_user = Journalist.query.filter_by(username=username).one()
        except NoResultFound:
            pass
        else:
            raise

    print('User "{}" successfully deleted'.format(username))
    return 0
예제 #18
0
def delete(id):
  item = Items.query.filter(Items.id == id).one()
  db_session.delete(item)
  db_session.commit()
  return redirect(url_for('index'))
예제 #19
0
 def delete(self, order_id):
     order = OrderModel.query.filter_by(id=order_id).first()
     db_session.delete(order)
     db_session.commit()
     return '', 204
예제 #20
0
def delete(id):
    categories = Categories.query.filter(Categories.id == id).one()
    db_session.delete(categories)
    db_session.commit()
    return redirect(url_for('category.new'))
예제 #21
0
def admin_delete_user(user_id):
    user = Journalist.query.get(user_id)
    db_session.delete(user)
    db_session.commit()
    return redirect(url_for('admin_index'))
예제 #22
0
def admin_delete_user(user_id):
    user = Journalist.query.get(user_id)
    db_session.delete(user)
    db_session.commit()
    return redirect(url_for("admin_index"))
예제 #23
0
from db import db_session
from models import User

user = User.query.first()
db_session.delete(user)
db_session.commit()
예제 #24
0
def crawl(pubmed_id_f, cutoff, start_at=0, overwrite=False):
  # collect papers to parse
  pubmed_ids = list()
  with open(pubmed_id_f) as f:
    pubmed_ids = [int(line.strip()) for line in f]

  # download GWC data for each paper
  for pmid in pubmed_ids:
    if pmid < start_at: continue

    # overwrite previous associations:
    if overwrite:
      assocs = db_session.query(Association).join(Association.paper).filter(Paper.pubmed_id==pmid).filter(Association.source=='gwas_central').all()
      if assocs:
        for a in assocs: db_session.delete(a)
        db_session.commit()

    # create/load paper
    paper = db_session.query(Paper).filter(Paper.pubmed_id==pmid).first()
    if not paper:
      paper = Paper(pubmed_id=pmid)
      db_session.add(paper)
      db_session.commit()

    # get study identifier
    gwcid = pmid2gwcid(pmid)
    if not gwcid: continue

    # get list of results
    try:
      results = gwcid2results(gwcid)
    except ValueError:
      print 'ERROR!'
      continue

    phenotypes = dict()
    snps = dict()
    for result in results:
      rsid, resultset_id, resultset_link, pvalue, neglog_pvalue = result

      if neglog_pvalue < cutoff: continue

      # if phenotype is not known, retrieve it
      if resultset_id not in phenotypes:
        phenotype_name = res2phen(resultset_id, resultset_link)
        phenotype = Phenotype(name=phenotype_name, source='gwas_central')
        phenotypes[resultset_id] = phenotype
        db_session.add(phenotype)
        db_session.commit()
      else:
        phenotype = phenotypes[resultset_id]

      # create snp
      if rsid not in snps:
        snp = db_session.query(SNP).filter(SNP.rs_id==rsid).first()
        if not snp:
          snp = SNP(rs_id=rsid)
          db_session.add(snp)
          db_session.commit()
      else:
        snp = snps[rsid]

      # create association
      db_session.add(Association(
        snp=snp,
        phenotype=phenotype,
        paper=paper,
        pvalue=pvalue,
        source='gwas_central'
      ))

      print 'Extracted association:', paper.pubmed_id, phenotype.name, snp.rs_id, pvalue

  db_session.commit()