예제 #1
0
    def addEdit(self, _thread_id, _content, _submitted=False):
        existingList = (
            session.query(bot_comments_anetpool)
            .filter_by(thread_id=_thread_id)
            .order_by(desc(bot_comments_anetpool.edit_id))
            .first()
        )

        if existingList is None:
            row = bot_comments_anetpool()
            row.thread_id = _thread_id
            _from_template = self.anetpool_template.split("	", 1)
            row.content = _from_template[0] + _content + "	" + _from_template[1]
            row.submitted = _submitted
            session.add(row)
        else:
            if len(existingList.content) + len(_content) >= 10000:
                row = bot_comments_anetpool()
                row.thread_id = _thread_id
                _from_template = self.anetpool_template.split("	", 1)
                row.content = _from_template[0] + _content + "	" + _from_template[1]
                row.submitted_id = "e" + str(existingList.edit_id)
                row.submitted = _submitted
                session.add(row)
            else:
                _from_save = existingList.content.split("	", 1)
                session.query(bot_comments_anetpool).filter_by(edit_id=existingList.edit_id).update(
                    {"content": _from_save[0] + _content + "	" + _from_save[1], "submitted": False}
                )
        session.commit()
예제 #2
0
    def _get_loops(self, pdb):
        """Get all loops in the given pdb file.
        """

        loops = []
        unit_ids = self._get_id_correspondence(pdb)
        query = session.query(AllLoops.id, AllLoops.pdb, AllLoops.type,
                              AllLoops.nt_ids).filter_by(pdb=pdb)

        releases = {}
        for loop_type in ['IL', 'HL']:
            releases[loop_type] = session.query(Release).\
                filter(Release.type == loop_type).\
                order_by(desc(Release.date)).first().id

        for loop in query:
            data = {'id': loop.id, 'pdb': loop.pdb, 'motif_id': ''}
            nts = loop.nt_ids.split(',')

            if loop.type in releases:
                query = session.query(Loop.motif_id).\
                    filter(Loop.id == loop.id).\
                    filter(Loop.release_id == releases[loop.type])

                if query.count() != 0:
                    data['motif_id'] = query.scalar()

            try:
                data['nts'] = ','.join([unit_ids[nt] for nt in nts])
                loops.append(data)
            except:
                logging.warning("Missing new style id for: %s" % loop.id)

        return loops
예제 #3
0
파일: serv.py 프로젝트: NSkelsey/pcomment
def list_responses(account_name):
    a = session.query(Account).filter_by(name=account_name).first()
    responses = session.query(Response).filter_by(from_email=a.email).all()
    if len(responses) == 0:
        message = "This User has made no public statements."
        return render_template('list_posts.html', responses=responses, account=a, message=message)
    return render_template('list_posts.html', responses=responses, account=a)
예제 #4
0
    def project_change(self, name, index, mode):
        project = session.query(Project).filter(Project.name == self.early_p_id.get())[0]
        # What tasks does this project have?
        tasks = session.query(Task).filter(Task.project == project.id)

        if tasks.count() > 0:
            self._fill_tasks(tasks)
예제 #5
0
 def __delete_distances(self, pdb_list):
     """recalculate=True, so delete what's already in the database"""
     logging.info('Deleting existing records %s', ','.join(pdb_list))
     for pdb_file in pdb_list:
         session.query(Distances). \
                 filter(Distances.id1.like(pdb_file+'%')). \
                 delete(synchronize_session=False)
예제 #6
0
파일: app.py 프로젝트: NSkelsey/verdant
def mod():
    global __HEXDIGEST__
    if request.method == "GET":
        mess = session.query(EmailMessage).get(__HEXDIGEST__)
        if mess is None or mess.approved == True:
            flash('No new messages to edit')
            return render_template('edit.html')
        dct = json.loads(mess.everything)
        form = EditForm()
        form.subject.data = dct.get('subject')
        form.text.data = dct.get('body-plain')
        form.approved.data = mess.approved
        return render_template('edit.html', form=form) 
    else:
        form = EditForm(request.form)
        mess = session.query(EmailMessage).get(__HEXDIGEST__)
        if form.approved.data == True:
            send_message(form.data)
            mess.approved = True
            session.add(mess)
            session.commit()
            flash('message sent')
            return render_template('edit.html')
        flash("bad form")
        return "bad form"
예제 #7
0
def wemo(request, command=None, device=None):
    if not command:
        raise NoCommandSpecified()
    if device:
        device = urllib.unquote(device)

    if command == 'ls':
        devices = session.query(distinct(WemoTimeSeries.device_name)).all()
        response = '<p>'
        for d in devices:
            response += "'" + d[0] + "'</br>"
        response += '</p>'
    
    elif command == 'on':
        wemo = WemoCC().on(device)
        response = '<p>' + device + ' turned on.</p>'
    
    elif command == 'off':
        wemo = WemoCC().off(device)
        response = '<p>' + device + ' turned off.</p>'

    elif command == 'completion':
        completion = []
        devices = session.query(distinct(WemoTimeSeries.device_name)).all()
        for d in devices:
            completion.append(d.lower().replace(' ', '_'))
        response = json.dumps(completion)

    return HttpResponse(response)
예제 #8
0
def terminal_visual():
    print_line_count = 0
    print colored('TIMELORD v.0.0.1', 'white', attrs=['bold'])
    print_line_count += 1

    # work
    todays_work = session.query(func.sum(WorkTime.work)).filter(WorkTime.datetime >= datetime.date.today()).one()
    if todays_work:
        todays_work = todays_work[0]
    if not todays_work:
        todays_work = 0

    print colored('work: ', 'cyan') + \
            colored(str(todays_work / 60.), 'green') + \
            colored(' hrs', 'cyan')
    print_line_count += 1

    # tasks
    print colored('task progress:', 'cyan')
    print_line_count += 1
    todays_progress = session.query(Milestone).filter(Milestone.datetime >= datetime.date.today()).all()
    if todays_progress:
        for tp in todays_progress:
            print colored('    ' + str(tp), 'yellow')
            print_line_count += 1
    else:
        print colored('    none', 'red')
        print_line_count += 1

    for i in range(print_line_count):
        print '\033[1A' + '\r',
        sys.stdout.flush()
예제 #9
0
 def get_latest_release(self):
     if session.query(NR_release).first() is None:
         logging.info('No previous releases found')
         return
     release = session.query(NR_release).order_by(desc(NR_release.date)).first()
     self.release = release.id
     self.get_release()
예제 #10
0
def item_edit(item_title):
    categories = session.query(Category).all()
    item = session.query(Item).filter_by(
        title=item_title).one()
    user = session.query(User).filter_by(
        id=login_session.get('user_id')).one()
    if item.user is not None and item.user.id != user.id:
        return redirect(url_for('home'))
    if request.method == 'POST':
        form = vh.ItemForm(request.form, item)
        file_storage_err = vh.store_item_pic(
            item, request.files['picture'])
        if (not form.validate() or file_storage_err is not None):
            return render_template('item_edit.html',
                                   form=form,
                                   file_err=file_storage_err)
        form.populate_obj(item)
        try:
            session.add(item)
            session.commit()
        except ValueError as e:
            return "Database validation error: " + str(e)
        except SQLAlchemyError as e:
            # todo: log error, but don't display detailed message
            # for security reasons
            return "Database error: " + str(e)
        return redirect(url_for('home'))
    else:
        form = vh.ItemForm(obj=item)
        return render_template('item_edit.html',
                               form=form,
                               file_err=None)
예제 #11
0
 def __delete_interactions(self, pdb_list):
     """recalculate=True, so delete what's already in the database"""
     logging.info('Deleting existing records %s', ','.join(pdb_list))
     for pdb_file in pdb_list:
         session.query(PairwiseInteractions). \
                 filter(PairwiseInteractions.pdb_id.in_(pdb_file+'%')). \
                 delete(synchronize_session=False)
예제 #12
0
def home():
    categories = session.query(Category).all()
    # todo: most recent
    items = session.query(Item).order_by(desc(Item.last_update))
    return render_template('home.html',
                           session=login_session,
                           categories=categories,
                           items=items)
예제 #13
0
파일: tests.py 프로젝트: leplatrem/pyfspot
 def test_add_tag(self):
     p = session.query(Photo).filter_by(filename='bee.jpg').one()
     self.assertEqual(p.tags, [])
     p.add_tag('Family')
     self.assertEqual(p.tags, [session.query(Tag).filter_by(name='Family').one()])
     self.assertEqual(p.tagnames, ['Family'])
     p.add_tag('family')
     self.assertEqual(len(p.tags), 1)
예제 #14
0
파일: test.py 프로젝트: EmuxEvans/py_learn
def delete_test():
    tom = session.query(Teacher).get(1)
    print tom.students
    session.delete(tom)
    # lucy = session.query(Student).get(1)
    # session.delete(lucy)
    session.commit()
    print session.query(Teacher).all()
    print session.query(Student).all()
예제 #15
0
파일: logics.py 프로젝트: Jack1007/clubot
 def get_members(remove = None):
     """ 获取所有成员
     Arguments:
         `remove`    -   排除成员
     """
     remove_email = get_email(remove)
     if remove:
         return session.query(Member).filter(Member.email != remove_email).all()
     return session.query(Member).all()
 def __delete_old_data(self, pdbs):
     """When recalculate=True, delete all data from pdb_best_chains_and_models
     and set pdb_analysis_status to None in the best_chains_and_models column"""
     session.query(PdbBestChainsAndModels).filter(PdbBestChainsAndModels.pdb_id.in_(pdbs)).delete(
         synchronize_session="fetch"
     )
     for statusObj in session.query(PdbAnalysisStatus).filter(PdbAnalysisStatus.id.in_(pdbs)).all():
         statusObj.best_chains_and_models = None
         session.merge(statusObj)
     session.commit()
 def __delete_old_data(self, pdbs):
     """When recalculate=True, delete all data from pdb_redundant_nucleotides
     and set pdb_analysis_status to None in the redundant_nts column"""
     session.query(RedundantNucleotide).filter(RedundantNucleotide.pdb_id.in_(pdbs)).delete(
         synchronize_session="fetch"
     )
     for statusObj in session.query(PdbAnalysisStatus).filter(PdbAnalysisStatus.id.in_(pdbs)).all():
         statusObj.redundant_nts = None
         session.merge(statusObj)
     session.commit()
예제 #18
0
def serialize_catalog():
    categories = session.query(Category).all()
    categories_json = [c.serialize for c in categories]
    for category_json in categories_json:
        items = session.query(Item).filter_by(
            category_id=category_json['id']).all()
        if len(items) > 0:
            category_json['Item'] = [
                i.serialize for i in items]
    return {'Category': categories_json}
예제 #19
0
 def get_previous_release(self):
     if session.query(NR_release).first() is None:
         logging.info('No previous releases found')
         return
     release = session.query(NR_release).order_by(desc(NR_release.date))[0:2]
     if len(release) == 2:
         self.release = release[1].id
         self.get_release()
     else:
         self.get_latest_release()
예제 #20
0
    def list(self):
        address_list = []
        if "limit" in self.data:
            query = session.query(Endereco).limit(self.data["limit"])
        else:
            query = query = session.query(Endereco)

        for q in query:
            address_list.append(to_json(q))

        return address_list
예제 #21
0
def items_list(category_name):
    category = session.query(Category).filter_by(
        name=category_name).one()
    categories = session.query(Category).all()
    items = session.query(Item).filter_by(
        category_id=category.id).all()
    return render_template('items.html',
                           session=login_session,
                           categories=categories,
                           category=category,
                           items=items)
예제 #22
0
 def updateLatestObjectIds(self, _last_comment_id, _last_submission_id):
     lastIds = session.query(subreddit).filter_by(website="reddit").first()
     if lastIds == None:
         row = subreddit()
         row.website = "reddit"
         row.last_comment = _last_comment_id
         row.last_submission = _last_submission_id
         session.add(row)
     else:
         session.query(subreddit).filter_by(website="reddit").update(
             {"last_submission": _last_submission_id, "last_comment": _last_comment_id}
         )
예제 #23
0
 def __release_diff_commit(self):
     """
     """
     try:
         session.add_all(self.release_diff)
         session.query(NR_handle).delete()
         session.commit()
         logging.info("Successful update")
     except sqlalchemy.exc.SQLAlchemyError, e:
         logging.error("Update failed. SQLAlchemy error. Rolling back.")
         logging.error(str(e))
         session.rollback()
         sys.exit()
예제 #24
0
 def __delete_unit_ids(self, pdbs):
     """
     """
     logging.info('Deleting unit id correspondence data')
     session.query(PdbUnitIdCorrespondence). \
             filter(PdbUnitIdCorrespondence.pdb.in_(pdbs)). \
             delete(synchronize_session='fetch')
     logging.info('Resetting unit id analysis status')
     for statusObj in session.query(PdbAnalysisStatus). \
                              filter(PdbAnalysisStatus.id.in_(pdbs)). \
                              all():
         statusObj.unit_ids = None
         session.merge(statusObj)
     session.commit()
예제 #25
0
def get_create_user(name, email):
    """ get or create user record """
    try:
        user = session.query(User).filter_by(
            email=email).one()
    # todo: catch specific sqlalchemy exception
    except:
        new_user = User(name=name,
                        email=email)
        session.add(new_user)
        session.commit()
        user = session.query(User).filter_by(
            email=email).one()
    return user.id
예제 #26
0
def home(request):

    session.rollback()
    session.commit()

    filter_date = datetime.datetime.utcnow() - datetime.timedelta(seconds=60)
    
    wemo_device_count = session.query(func.count(distinct(WemoTimeSeries.device_name))).first()[0]
    wemo = session.query(WemoTimeSeries).order_by(WemoTimeSeries.datetime.desc()).limit(wemo_device_count).all()

    hue_device_count = session.query(func.count(distinct(HueTimeSeries.device_name))).first()[0]
    hue = session.query(HueTimeSeries).order_by(HueTimeSeries.datetime.desc()).limit(hue_device_count).all()

    nest = session.query(NestTimeSeries).order_by(NestTimeSeries.datetime.desc()).limit(1).first()

    apex = session.query(ApexTimeSeries).filter(ApexTimeSeries.value != None).filter(ApexTimeSeries.datetime>filter_date).all()
   
    roomba_device_count = session.query(func.count(distinct(RoombaTimeSeries.device_name))).first()[0]
    roomba = session.query(RoombaTimeSeries).order_by(RoombaTimeSeries.datetime.desc()).limit(roomba_device_count).all()
    
    f = Flower()
    flower = f.get_data(.001)[-1]
    
    return render(request, template_name='home.html', dictionary={'wemo': wemo, 
                                                                  'hue': hue, 
                                                                  'nest': nest,
                                                                  'apex': apex,
                                                                  'roomba': roomba,
                                                                  'flower': flower,
                                                                 })
예제 #27
0
def login():
    if request.method == 'POST':
        if request.form.get('sign-in') is not None:
            try:
                user = session.query(User).filter_by(
                    email=request.form.get('email')).one()
            except NoResultFound:
                return ("no user record found for email '%s'" %
                        request.form.get('email'))
            if user.password is None:
                return ("user account created with third-party service"
                        "<br>"
                        "sign up locally or sign in with third-party")
            if check_password_hash(user.password,
                                   request.form.get('password')):
                login_session['user_id'] = user.id
            else:
                return "bad password"
        else:
            # request.form.get('sign-up') is not None
            if ((request.form.get('password') !=
                 request.form.get('password-confirm'))):
                return "passwords don't match"
            try:
                user = session.query(User).filter_by(
                    email=request.form.get('email')).one()
            except NoResultFound:
                user = User(email=request.form.get('email'))
            if user.password is not None:
                return "user already registered"
            user.password = generate_password_hash(
                request.form.get('password'))
            user.name = request.form.get('name')
            session.add(user)
            session.commit()
            user = session.query(User).filter_by(
                email=request.form.get('email')).one()
            login_session['user_id'] = user.id
        return redirect(url_for('home'))
    else:
        state = ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for _ in range(32)
        )
        login_session['state'] = state
        return render_template(
            'login.html',
            state=state,
            G_CLIENT_ID=G_CLIENT_ID,
            GH_CLIENT_ID=app.config['GITHUB_CLIENT_ID'])
예제 #28
0
def item_detail(category_name, item_title):
    category = session.query(Category).filter_by(
        name=category_name).one()
    item = session.query(Item).filter_by(
        category_id=category.id).filter_by(
            title=item_title).one()
    has_img = vh.get_item_image_info(item.id) is not None
    can_modify = (item.user is None or
                  item.user.id == login_session.get('user_id'))
    return render_template('item.html',
                           session=login_session,
                           item=item,
                           has_img=has_img,
                           can_modify=can_modify,
                           rand_q=time.time())
예제 #29
0
 def _get_loop_id(self, full_id, pdb_id, loop_type):
     """returns a loop id"""
     L = session.query(AllLoops).filter(AllLoops.nt_ids==full_id).first()
     if L:
         logging.info('Full_id %s matched %s', full_id, L.id)
         return L.id
     else:
         "count the loops already in the db"""
         seq_id = session.query(AllLoops). \
                          filter(AllLoops.pdb==pdb_id). \
                          filter(AllLoops.type==loop_type).count()
         """format example: IL_1S72_001"""
         id = '_'.join([loop_type, pdb_id, str(seq_id+1).rjust(3,'0')])
         logging.info('Created new loop id %s', id)
         return id
def inspection_and_delivery(document, rfq):
    document.add_heading("6. Inspection and Delivery", level=BIG_HEADING)

    content_components = session.query(ContentComponent).filter_by(document_id=rfq.id).filter_by(section=6).all()
    cc = make_dict(content_components)

    document.add_heading("Overview", level=SUB_HEADING)
    document.add_paragraph(cc["guidingPrinciples"])

    document.add_heading("Delivery and Timing", level=SUB_HEADING)
    document.add_paragraph(cc["inspectionOverview"])

    document.add_heading("Late Delivery", level=SUB_HEADING)
    document.add_paragraph(cc["lateDelivery"])

    document.add_heading("Collaboration Environment", level=SUB_HEADING)

    if cc["workspaceExists"] == "yes":
        if len(cc["workspaceName"]) > 0:
            document.add_paragraph(rfq.agency + " is currently using " + cc["workspaceName"] + " as their primary collaborative workspace tool. The contractor is required to establish a collaborative workspace using either this tool or another that both the contractor and the CO can agree upon.")

    document.add_paragraph(cc["deliveringDeliverables"])

    document.add_heading("Transition Activities", level=SUB_HEADING)
    document.add_paragraph(cc["transitionActivities"])

    return document
예제 #31
0
def blog_context():
    data = {
        'blog_title': BLOG_TITLE,
        'blog_sub_title': BLOG_SUB_TITLE,
        'title': BLOG_TITLE,
        'ver': STATIC_FILE_VERSION,
        'github_link': GITHUB_LINK
    }

    # TODO cache the tags
    with session_context() as session:
        data['tags'] = session.query(Tag).order_by(Tag.name.asc())

    return data
def check_out(userid: int):
    if not userid:
        return Response.wrong_format({
            'updated': False,
            'message': 'userid missing'
        })

    person = session.query(Person).filter(Person.id == userid).first()
    person.is_present = False
    try:
        session.commit()
    except:
        Response.database_error()
    return Response.ok({"userid": userid, "message": "checked out"})
예제 #33
0
    async def rm(self, ctx, battletag):
        """Remove your battletag.

        Args:
            battletag: Your Battle.Net battletag.
        """
        member = ctx.message.author
        result = session.query(wz_model).filter_by(member_id=member.id).first()
        if result:
            session.delete(result)
            session.commit()
            return await ctx.reply(f"{result.battletag} removed.")

        return await ctx.reply(f"{battletag} not registerd.")
예제 #34
0
    def mutate(root, info, item, task_id, completed, index):
        task = Task(task_id=task_id,
                    item=item,
                    completed=completed,
                    index=index)

        row = session.query(TaskModel).filter(
            TaskModel.task_id == task_id).one()
        row.item = item
        row.completed = completed
        row.index = index

        session.commit()
        return UpdateTodo(task=task)
예제 #35
0
def add_product():
    """Adds product by user input.
    if conflict, user input is saved."""
    name = input('What is the name of the product? ')

    quantity_error = True
    while quantity_error == True:
        quantity = input('How many are there? ')
        try:
            int(quantity)
        except ValueError:
            quit_or_again = input('''
                    \nThe quantity must be an number.
                    \rPress enter to try again.''')
        else:
            quantity_error = False

    price_error = True
    while price_error == True:
        price = input('What is the price of the product?(ex. 3.99) ')
        price = clean_price(price)
        if type(price) == int:
            price_error = False

    date = datetime.datetime.now()

    # Delete conflicting instance.
    session.query(Product).filter(name == Product.product_name).delete()

    new_product = Product(product_name=name,
                          product_quantity=quantity,
                          product_price=price,
                          date_updated=date)
    session.add(new_product)
    session.commit()
    print(f'-- {name} was added. --')
    time.sleep(1)
예제 #36
0
    def post(self, *args, **kwargs):
        resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
        member_info = self.member_info
        order_sn = self.get_argument('order_sn','')
        score = self.get_argument('score',10)
        content = self.get_argument('content','')

        pay_order_info = session.query(PayOrder).filter_by(member_id=member_info.id, order_sn=order_sn).first()
        if not pay_order_info:
            resp['code'] = -1
            resp['msg'] = "系统繁忙,请稍后再试~~"
            self.write(resp)
            return

        if pay_order_info.comment_status:
            resp['code'] = -1
            resp['msg'] = "已经评价过了~~"
            self.write(resp)
            return

        pay_order_items = session.query(PayOrderItem).filter_by(pay_order_id=pay_order_info.id).all()
        food_ids = selectFilterObj(pay_order_items, "food_id")
        tmp_food_ids_str = '_'.join(str(s) for s in food_ids if s not in [None])
        model_comment = MemberComments()
        model_comment.food_ids = "_%s_" % tmp_food_ids_str
        model_comment.member_id = member_info.id
        model_comment.pay_order_id = pay_order_info.id
        model_comment.score = score
        model_comment.content = content
        session.add(model_comment)

        pay_order_info.comment_status = 1
        pay_order_info.updated_time = getCurrentDate()
        session.add(pay_order_info)

        session.commit()
        self.finish(resp)
예제 #37
0
def place_vote(data: dict):
    if not 'choice_id' in data:
        return Response.wrong_format(
            {'message': 'choiceid is required for voting'})
    if not 'election_round_id' in data:
        return Response.wrong_format(
            {'message': 'election_round_id required for voting'})
    if not 'person_id' in data:
        return Response.wrong_format(
            {'message': 'person_id required for voting'})
    try:
        election_round_id = int(data['election_round_id'])
        person_id = int(data['person_id'])
        choice_id = int(data['choice_id'])
    except:
        return Response.wrong_format(
            {"message": "ids have to be an int base 10"})
    elec_round = _get_electionround_by_id(election_round_id)
    if not elec_round:
        return Response.ressource_not_found(
            {"message": "No electionround for this id."})
    person = get_person_by_id(person_id)
    if person in elec_round.persons_voted:
        return Response.server_error({"message": "Person already voted"})
    try:
        choice = session.query(Choice).filter_by(id=choice_id).first()
        session.commit()
        if choice is None:
            return Response.ressource_not_found(
                {"message": "No Choice with this id."})
    except:
        print("no choice")
        return Response.database_error()

    if choice not in elec_round.choices:
        return Response.server_error(
            {"message": "Electionround has no Choice with that ID"})
    try:
        choice.counter = choice.counter + 1
        session.commit()
    except:
        return Response.database_error()
    try:
        elec_round.persons_voted.append(person)
        session.commit()
    except:
        return Response.database_error()

    return Response.ok(model_as_dict(choice))
예제 #38
0
def update_user(id):
    user_obj = session.query(User).get(id)
    username = request.json['username']
    email = request.json['email']
    skills = request.json['skills']
    hobbies = request.json['hobbies']
    #update
    user_obj.username = username
    user_obj.email = email
    user_obj.skills = []
    user_obj.hobbies = []

    for skill in skills:
        skill_obj = session.query(Skill).get(skill['id'])
        user_obj.skills.append(skill_obj)

    for hob in hobbies:
        hob_obj = session.query(Hobbie).get(hob['id'])
        user_obj.hobbies.append(hob_obj)

    session.commit()
    output = user_schema.dump(user_obj)

    return jsonify(output)
예제 #39
0
def check_user_for_obj(kind, id):
    #kind = globals()[kind]
    obj = session.query(kind).filter(kind.id == id).first()

    ## Does it exist
    if not obj: return render_template('404.html'), 404

    ## Check auth
    uid = None
    if flask_session.get('current_user'):
        uid = flask_session['current_user'].get('id')
    if obj.user_id == uid:
        return True
    else:
        return False
예제 #40
0
def get_top():
    if request.method != 'GET':
        abort(BAD_REQUEST)

    count = min(conf['max_count_per_query'], int(request.args.get('count',
                                                                  10)))
    offset = int(request.args.get('offset', 0))

    resp = session.query(Meme)\
        .order_by(Meme.rating.desc(), Meme.id.desc())\
        .limit(count)\
        .offset(offset)\
        .all()

    return jsonify(get_list_memes(resp))
예제 #41
0
def categories_list():
    """ Creates a list of the available categories. """
    if request.method == 'GET':
        page = Page(title="Categories page",
                    description="The full list of the categories available")
        categories = list(session.query(models.Category).all())
        for i in categories:
            i.to_link()
            i.link = flask.render_template('link.html', link=i)
        page.content.title = "Categories"
        page.content.main = flask.render_template('definitionlist.html',
                                                  htmlclass="categories",
                                                  definitions=categories)
        page.content.aside = ""
        return page.render()
예제 #42
0
def find_info(entry):
    soup = BeautifulSoup(entry.description, "html.parser")
    secondtd = soup.findAll("td")[1]
    card = create_card(secondtd.strings)
    card_obj = session.query(Card).filter(
        Card.title == card["title"]).one_or_none()
    if card_obj is None:
        card_obj = Card(title=card["title"])
    record = Record(qty=card["qty"], price=card["price"])
    card_obj.records.append(record)
    print(f"{card_obj}")
    for record in card_obj.records:
        print(f"{record}")

    return card_obj
예제 #43
0
    def post(self, *args, **kwargs):
        resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
        code = self.get_argument('code', '')
        if not code or len(code) < 1:
            resp['code'] = -1
            resp['msg'] = "需要code"
            self.write(resp)
            return

        openid = MemberService.getWeChatOpenId(code)
        if openid is None:
            resp['code'] = -1
            resp['msg'] = "调用微信出错"
            self.write(resp)
            return

        bind_info = session.query(OauthMemberBind).filter_by(openid=openid,
                                                             type=1).first()
        if not bind_info:
            resp['code'] = -1
            resp['msg'] = "未绑定"
            self.write(resp)
            return

        member_info = session.query(Member).filter_by(
            id=bind_info.member_id).first()
        if not member_info:
            resp['code'] = -1
            resp['msg'] = "未查询到绑定信息"
            self.write(resp)
            return

        token = "%s#%s" % (MemberService.geneAuthCode(member_info),
                           member_info.id)
        resp['data'] = {'token': token}
        self.finish(resp)
def delete_item_by_id(category_id, item_id):
    """
    HTML endpoint providing a form to delete an item
    """
    if not UserUtils.is_authenticated():
        UserUtils.set_preauthentication_url()
        flash('sign in to delete an item')
        return redirect('/login')

    item = session.query(Item).filter_by(id=item_id).one()

    # Users may delete only items they created
    if not Permissions.get_user_permissions_for_item(item).delete:
        flash('you may delete only items you created')
        return redirect(url_for(
            'get_category_by_id',
            category_id=category_id))

    if request.method == 'POST':
        session.delete(item)
        session.commit()

        flash('item deleted')

        return redirect(url_for(
            'get_category_by_id',
            category_id=category_id))
    else:
        category = session.query(Category).filter_by(id=category_id).one()

        return UserUtils.render_user_template(
            'item_delete.html',
            category=category,
            category_id=category_id,
            item=item,
            page_title="%s %s Item" % ("Delete", item.title))
예제 #45
0
def main():
    r = praw.Reddit(user_agent=cfg_file.get('reddit', 'user_agent'))
    r.login(cfg_file.get('reddit', 'username'),
            cfg_file.get('reddit', 'password'))

    # update exclude_banned_modqueue values for subreddits
    subreddits = (session.query(Subreddit)
                         .filter(Subreddit.enabled == True)
                         .all())
    for sr in subreddits:
        try:
            settings = r.get_subreddit(sr.name).get_settings()
            sr.exclude_banned_modqueue = settings['exclude_banned_modqueue']
        except Exception as e:
            sr.exclude_banned_modqueue = False

    session.commit()

    # delete old log entries
    log_retention_days = int(cfg_file.get('database', 'log_retention_days'))
    log_cutoff = datetime.utcnow() - timedelta(days=log_retention_days)
    deleted = session.query(Log).filter(Log.datetime < log_cutoff).delete()
    session.commit()
    print 'Deleted {0} log rows'.format(deleted)
def close_open_election_round(electionroundid: int):
    '''Closes an election round.'''

    try:
        electionround = session.query(ElectionRound).filter(
            ElectionRound.id == electionroundid).first()
    except:
        return Response.database_error()
    if electionround.running != "finished":
        electionround.running = "finished"
    try:
        session.commit()
    except:
        return Response.database_error()
    return Response.ok(model_as_dict(electionround))
예제 #47
0
파일: api.py 프로젝트: JostLuebbe/mypv
def check_password(username, password):
    user: User = session.query(User).filter_by(username=username).first()

    if user is None:
        return False

    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=base64.b64decode(user.salt.encode()),
        iterations=100000,
        backend=default_backend()
    )

    return user.key == base64.urlsafe_b64encode(kdf.derive(password.encode()))
예제 #48
0
def user_list():
    q = sess.query(User)
    priv = '*'
    if 'priv' in request.args:
        priv = request.args.get('priv')
        q = q.filter(User.priv == priv)
    if 'desc' in request.args:
        q = q.filter(User.name.like("%" + request.args.get('name') + "%"))
    users = q.all()
    print len(users)
    return render_template('admin.html',
                           user=g.user,
                           users=users,
                           priv=priv,
                           cur_page='admin')
예제 #49
0
파일: main.py 프로젝트: CaseyK9/ezAntiRaid
    async def on_guild_role_delete(self, channel):

        async for entry in channel.guild.audit_logs(
                action=discord.AuditLogAction.role_delete, limit=1):
            latest = entry

        user = session.query(Role).filter_by(userId=latest.user.id).first()
        if user is None:
            d = Role(userId=latest.user.id,
                     savedTime=(time.time() + 120),
                     deleted=0)
            session.add(d)
            session.commit()
            user = session.query(Role).filter_by(userId=latest.user.id).first()
        elif (user.savedTime - time.time()) <= 0:
            user.savedTime = (time.time() + 120)
            user.deleted = 0
            session.commit()
            user = session.query(Role).filter_by(userId=latest.user.id).first()

        if (user.savedTime - time.time()) > 0:
            user.deleted = user.deleted + 1
            session.commit()
            user = session.query(Role).filter_by(userId=latest.user.id).first()

        if user.deleted == 5:
            d = Raiders(userId=latest.user.id, offense='Role')
            session.add(d)
            session.delete(user)
            session.commit()
            member = channel.guild.get_member(user.userId)
            for role in member.roles[1:]:
                await member.remove_roles(role)
            role = discord.utils.get(channel.guild.roles,
                                     name="Under Investigation")
            await member.add_roles(role)
예제 #50
0
    def delete_patient(self, id=None):
        try:
            p = session.query(Patient).filter_by(id=id).first()
        except:
            return "Could not find patient in database."

        if p:
            try:
                session.delete(p)
                session.commit()
                return "Patient {} deleted".format(id)
            except Exception as e:
                return str(e)
        else:
            return "No Patient found with ID {}.".format(id)
예제 #51
0
    def delete_health_param(self, id=None):
        try:
            hp = session.query(HealthParameter).filter_by(id=id).first()
        except:
            return "Could not find Parameter in database."

        if hp:
            try:
                session.delete(hp)
                session.commit()
                return "Health Parameter '{}' deleted".format(id)
            except Exception as e:
                return str(e)
        else:
            return "No Health Parameter found with ID {}.".format(id)
예제 #52
0
    async def post(self, request):
        data = await request.json()
        instance=self.factory(**data)
        session.add(instance)
        session.commit()

        return Response(status=201, body=self.resource.encode({
            self.collection_name : [
                
                    OrderedDict((key, getattr(instance, key)) for key in self.properties)

                    for instance in session.query(Bid)

                    ]
            }), content_type='application/json')
예제 #53
0
def create_categories():
    urls = ('http://www.sexycaracas.com/sexyccs/p_index.php?ids=1&/Damas',
            'http://www.sexycaracas.com/sexyccs/p_index.php?ids=5&/Trans',
            'http://www.sexycaracas.com/sexyccs/p_index.php?ids=6&/Hombres')
    names = ('Damas', 'Trans', 'Hombres')
    sources_ids = (1, 5, 6)

    if not session.query(CategorySnapshot).all():
        for url, name, source_id in zip(urls, names, sources_ids):
            session.add(
                CategorySnapshot(source_id=source_id,
                                 name=name,
                                 source='sexycaracas',
                                 source_url=url))
    session.commit()
예제 #54
0
def getDictFilterField(db_model,select_filed,key_field,id_list):
    ret = {}
    query = session.query(db_model)
    if id_list and len(id_list) > 0:
        query = query.filter(select_filed.in_( id_list ))

    list = query.all()
    if not list:
        return ret
    for item in list:
        if not hasattr( item,key_field ):
            break

        ret[ getattr(item,key_field) ] = item
    return ret
예제 #55
0
def get_all_games(update) -> list:
    """Returns all Game models for current chat"""
    games = (
        session.query(Game)
        .filter_by(chat_id=update.effective_chat.id)
        .order_by(Game.timeslot)
        .all()
    )
    games_list = []
    for game in games:
        if game_timediff(game, hours=2):
            game.delete()
        else:
            games_list.append(game)
    return games_list
예제 #56
0
def signup(signup_request):
    same_name_count = session.query(Accounts).filter_by(
        name=signup_request['name']).count()
    same_email_count = session.query(Accounts).filter_by(
        email=signup_request['email']).count()

    if same_email_count > 0 or same_name_count > 0:
        return 'CREDENTIALS_ALREADY_EXIST'

    index = ''.join(
        random.choice(string.ascii_lowercase + string.digits)
        for _ in range(40))
    elasticsearch_service.create_index(index)

    new_account = Accounts(
        name=signup_request['name'],
        email=signup_request['email'],
        password=hashlib.sha256(
            signup_request['password'].encode('utf=8')).hexdigest(),
        index=index)

    session.add(new_account)
    session.commit()
    return 'ACCOUNT_CREATED'
예제 #57
0
    def remove_value_from_patient(self, hv_id):
        #TODO: try catch

        try:
            hv = session.query(HealthValue).filter_by(id=hv_id).first()
        except:
            return "No HealthValue with ID {} found.".format(hv_id)

        if hv:
            session.delete(hv)
            session.commit()
            return "Value {} deleted.".format(hv)

        else:
            return "No HealthValue with ID {} found.".format(hv_id)
예제 #58
0
 def set_offline(cls, jid):
     m = cls.get_one(jid)
     if not m: return False
     try:
         status = session.query(Status)\
                 .filter(and_(Status.resource == jid.resource,
                              Status.member == m)).one()
         m.status.pop(m.status.index(status))
         try:
             session.delete(status)
             session.commit()
         except:
             session.rollback()
     except NoResultFound:
         pass
예제 #59
0
 def post(self):
     args = parser.parse_args()
     new_page = Page(
         title=args["title"],
         parent=args["parent"],
         slug=args["slug"],
         content=args["content"]
     )
     # Ensure slug/title pair is not present
     if not session.query(Page).filter_by(parent=new_page.parent, slug=new_page.slug).count() and new_page.title:
         session.add(new_page)
         session.commit()
         return new_page.as_dictionary()
     else:
         return None
예제 #60
0
    def get_values_for_patient(self, patient_id):

        p = session.query(Patient).filter_by(id=patient_id).first()

        if p:
            hvs = p.health_values

            if len(hvs) > 0:
                return [ph.health_value for ph in hvs]

            else:
                return "Patient has no health values yet."

        else:
            return "No Patient with ID {} found.".format(patient_id)