Пример #1
0
async def crawl_one(url: str, **kwargs) -> None:
    html = await parse(url=url, **kwargs)

    if not html:
        return None

    db.update({"html": html}, Link.value == url)
Пример #2
0
def sell_stock():
    aid = request.cookies.get('aid')
    if aid is None or aid == "":
        return redirect(url_for("login.sign_in"))
    sid = request.form.get('sid')
    old_price = float(request.form.get('old_price'))
    cur_price = float(request.form.get('cur_price'))
    sell_num = request.form.get('sell_num')
    num = int(request.form.get('num'))
    if sell_num == "":
        return redirect(url_for(".own_stock"))
    else:
        sell_num = int(sell_num)
    if sell_num >= num:
        db.delete(conn, 'own_stk', {
            'aid': aid,
            'sid': request.form.get('sid')
        })
    else:
        new_num = num - sell_num
        new_price = (old_price * num - cur_price * sell_num) / new_num
        db.update(conn, 'own_stk', {"=": {
            'price': new_price,
            'num': new_num
        }}, {
            'sid': sid,
            'aid': aid
        })
    return redirect(url_for(".own_stock"))
Пример #3
0
 def click_btnupdatefigure(self):
     db.update(
         "figures", {
             "name": self.figurename.text(),
             "imgpath": self.figureimgpath.text(),
             "description": self.figuredescription.toPlainText()
         }, {'id': self.figureid.text()})
Пример #4
0
 def POST(self):
     auth()
     data = web.input(title='', contents='',tag='')
     ''' update tag '''
     for tag in data.tag.split(';'):
         db.query('select name from tag')
         res = db.fetchAllRows()
         if len(tag) == 0:
             continue
         if (tag,) not in res:
             db.insert('insert into tag (name, num) values ("%s",1)'%tag)
         else:
             db.query('select id,num from tag where name="%s"'%tag)
             res = db.fetchOneRow()
             print res
             db.update('update tag set num=%d where id=%d'%((res[1]+1),res[0]))
     ''' update article '''
     db.query('select * from article where title="%s"'%data.title)
     res = db.fetchOneRow()
     if res == None:
         res = db.insert('insert into article (title, content, tag, posttime) values ("%s", "%s", "%s", "%s")'%(data.title, data.contents, data.tag, time.strftime('%Y-%m-%d %H:%M:%S')))
         if not res:
             web.redirect('/edit')
         return 'success'
     return 'repeated title'
Пример #5
0
def delete_record():
    aid = request.cookies.get('aid')
    if aid is None or aid == "":
        return redirect(url_for("login.sign_in"))

    old_amt = float(request.form.get('old_amt'))
    t = request.form.get('time')
    db.delete(conn, 'records', {'reid': request.form.get('reid')})

    # influence plans
    if t == "":
        record_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    else:
        record_time = t
    sql = """select * from plans where aid = '%s' and (ending > '%s' or ending is null);""" % (
        aid, record_time)
    plans = db.special_select(sql)
    for plan in plans:
        if check_time(
                plan['starting'].strftime("%Y-%m-%d %H:%M:%S").split(" ")[0],
                record_time.split(" ")[0], plan['cycle']):
            new_credit = float(plan['credit']) - old_amt
            db.update(conn, "plans", {"=": {
                'credit': new_credit
            }}, {'pid': plan['pid']})

    # influence win_honor
    valid_honor(conn, aid)

    return redirect(url_for(".all_records"))
Пример #6
0
def ship_count(group_id, user_id: int, value: int):
    db.update(TABLE='ship_count',
              SET={'count': value},
              WHERE={
                  'group_id': group_id,
                  'user_id': user_id
              })
Пример #7
0
def put_user():
    if not request.json:
        abort_msg(400, 'Expected JSON parameters')

    if 'password' in request.json:
        passwd = request.json['password']
        if not passwd:
            passwd = utils.generatePassword(20)

        _db = db.connect(settings.settings())
        db.update(_db,
                  'users',
                  'pass="******"' % (passwd),
                  where='name="%s"' % auth.username())
        data = {'user': auth.username(), 'password': passwd}

        return jsonify(data)

    if 'api_key' in request.json:
        apikey = utils.generateApiKey()
        _db = db.connect(settings.settings())
        db.update(_db,
                  'users',
                  'apikey="%s"' % (apikey),
                  where='name="%s"' % auth.username())

        data = {'user': auth.username(), 'api_key': apikey}

        return jsonify(data)

    abort_msg(400, 'Expected "password" or "api_key"')
Пример #8
0
    def POST(self):
        if (web.config._session.roleid != 1):
            raise web.seeother('/')
        pdata = web.input(item=None, action=None, picture={}, category_id=None)
        if pdata.action == "create":
            fullpath=None
            if 'picture' in pdata:#what I added for storing the picture
                if len(pdata.picture.filename)>0:
                    filedir='./static'
                    filepath=pdata.picture.filename.replace('\\','/')
                    filename=filepath.split('/')[-1]
		    fullpath=filedir+'/'+filename
                    fout=open(fullpath,'wb')
                    fout.write(pdata.picture.file.read())
                    fout.close()
            create_item(pdata.item, pdata.description, pdata.price,fullpath)
        elif pdata.action == 'delete':
            if len(pdata.picture)>0:
                os.remove(pdata.picture)
            delete_item(pdata.item)
        elif pdata.action == 'hide':
            set_status(pdata.item, False)
        elif pdata.action == 'show':
            set_status(pdata.item, True)
        elif pdata.action == 'update':
            db.update('MenuItems', where='id=$pdata.item', vars=locals(), price=pdata.price)
        elif pdata.action == 'category':
            db.insert('Item_Categories', item_id = pdata.item, category_id = pdata.category_id)
        elif pdata.action == 'delete_category':
            db.delete('Item_Categories', vars=locals(), where= 'item_id = $pdata.item and category_id = $pdata.category_id')
        raise web.seeother('/menu_editor')
Пример #9
0
def buy_stock():
    aid = request.cookies.get('aid')
    if aid is None or aid == "":
        return redirect(url_for("login.sign_in"))
    data = {
        'aid': aid,
        'sid': request.form.get('sid'),
        'num': request.form.get('num'),
        'price': float(request.form.get('price'))
    }
    if data['num'] == "":
        return redirect(url_for(".stock_market"))
    else:
        data['num'] = int(data['num'])
    tmp = db.select(conn, 'own_stk', "*", {'sid': data['sid'], 'aid': aid})
    if len(tmp) == 0:
        db.insert(conn, 'own_stk', data)
    else:
        new_num = int(tmp[0]['num']) + data['num']
        new_price = (float(tmp[0]['price']) * int(tmp[0]['num']) +
                     data['num'] * data['price']) / new_num
        db.update(conn, 'own_stk', {"=": {
            'price': new_price,
            'num': new_num
        }}, {
            'sid': data['sid'],
            'aid': aid
        })
    return redirect(url_for(".own_stock"))
Пример #10
0
def check_plans():
    cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    sql = "select * from plans where ending > '%s' or ending is null;" % cur_time
    plans = db.special_select(sql)
    for plan in plans:
        if check_time(plan['starting'], plan['cycle']):
            plan['credit'] = plan['budget']
            db.update(conn, "plans", plan, {'pid': plan['pid']})
Пример #11
0
    def createMachine(self, res):
        extras = []
        extra = ''

        base = ''

        inf = infra.provider(settings.settings())

        volume = self.get_volume_from_image(res['image'], utils.generateID() + '_', resize=res['size'])
        if volume:
            base = os.path.basename(res['image'])
            extras.append(inf.fileStorage(volume))

        cdrom = self.get_cdrom_image(res['cdrom'])
        if cdrom:
            if not base:
                base = os.path.basename(cdrom)
            extras.append(inf.cdromStorage(cdrom))

        image_extra_loader = None
        if volume or cdrom:
            item = cdrom
            if volume:
                item = volume

            image_extra_loader = self.image_extra_config(os.path.basename(item), res['name'])

        image_extra_userdata = {}
        if image_extra_loader is not None:
            print ('Found image loader: %s' % (image_extra_loader.base()))
            extra_device = image_extra_loader.extraDeviceConfig(inf)
            if extra_device:
                extras.append(extra_device)
            image_extra = image_extra_loader.extra()
            if image_extra:
                extra += image_extra

            image_extra_userdata = image_extra_loader.userdata()
            # TODO: Support other features


        if 'network_name' in settings.settings():
            extras.append(inf.defineNetworkInterface(settings.settings()['network_name']))

        extradevices = '\n'.join(extras)

        dom_xml = inf.customDomain(res['name'], res['cpus'], res['memory'], extradevices=extradevices, extra=extra)
        dom = inf.createDomain(dom_xml)

        dom_res = dom.create()

        _db = db.connect(settings.settings())
        config_data = json.dumps(image_extra_userdata)
        config_data = config_data.replace('\'', '\\\'')
        db.update(_db, 'machines',
            'config=\'%s\'' % (config_data),
            where='id="%s"' % (res['name']))
Пример #12
0
def custom_name(user_id: int, new_name: str):
    if new_name == 'default':
        new_name = ''

    db.update(TABLE='users',
              SET={'custom_name': new_name},
              WHERE={
                  'user_id': user_id,
              })
Пример #13
0
 def update(self, id, param):
     job = JobModel.find_by_id(id)
     if job:
         db.update(job).values(**param)
     if param == true:
         result = self.checkValidationPermission()
         if not result:
             raise Exception("User unauthorized")
         self.SendJob(id)
Пример #14
0
def modifying_profile():
    aid = request.cookies.get('aid')
    if aid is None or aid == "":
        return redirect(url_for("login.sign_in"))
    account = dict()
    account['name'] = request.form.get("name")
    account['pwd'] = request.form.get("password")
    account['email'] = request.form.get("email")
    db.update(conn, 'account', {"=": account}, {'aid': aid})
    return redirect(url_for("user.profile"))
Пример #15
0
async def add_bw(message: types.Message):
    db.update(TABLE='users',
              SET={'admin': 'False'},
              WHERE={'user_id': int(message.text)})

    user = db.select(SELECT='name',
                     TABLE='users',
                     WHERE={'user_id': int(message.text)})

    await message.reply(f"{user} removed from admins", parse_mode=PM)
    await Branch.admin_panel.set()
Пример #16
0
def merge(phone_id, card_id):
    """手机临时账号和校园卡账号合并"""
    record_table = 'record'
    t = db.transaction()
    phone_id, card_id = int(phone_id), int(card_id)
    # db.update(record_table, where="lost_id=%i" % phone_id, lost_id=card_id)
    # db.update(record_table, where="find_id=%i" % phone_id, find_id=card_id)
    # # 删除合并用户
    # phone_user = db.select(_table, where="id=%i" % phone_id, limit=1, what='phone')
    # try:
    #     db.delete(_table, where="id=%i" % phone_id)
    # except:
    #     db.update(_table, where="id=%i" % phone_id, phone=None)
    # db.update(_table, where="id=%i" % card_id, phone=phone_user[0].phone)

    try:
        # 转移记录
        db.update(record_table, where="lost_id=%i" % phone_id, lost_id=card_id)
        db.update(record_table, where="find_id=%i" % phone_id, find_id=card_id)
        # 删除合并用户
        phone_user = db.select(_table, where="id=%i" % phone_id, limit=1, what='phone')
        try:
            db.delete(_table, where="id=%i" % phone_id)
        except:
            db.update(_table, where="id=%i" % phone_id, phone=None)
        db.update(_table, where="id=%i" % card_id, phone=phone_user[0].phone)
    except:
        t.rollback()
        return False
    else:
        t.commit()
        return card_id
Пример #17
0
def add_record():
    aid = request.cookies.get('aid')
    if aid is None or aid == "":
        return redirect(url_for("login.sign_in"))
    record = dict()
    record['name'] = request.form.get("name")
    record['be_from'] = request.form.get("be_from")
    record['be_to'] = request.form.get("be_to")
    record['amt'] = request.form.get("amt")
    record['tag'] = request.form.get("tag")
    record['time'] = to_valid_time(request.form.get("time"))
    record['remark'] = request.form.get("remark")
    record['aid'] = request.cookies.get("aid")

    reids = db.select(conn, 'records', ['reid'], dict())
    reids = [t['reid'] for t in reids]

    record['reid'] = ''.join(
        random.choice(letters + numbers) for j in range(10))
    while record['reid'] in reids:
        record['reid'] = ''.join(
            random.choice(letters + numbers) for j in range(10))

    res = db.insert(conn, 'records', record)
    if res is True:
        # influence plans
        if record['time'] == "":
            record_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        else:
            record_time = record['time']
        sql = """select * from plans where aid = '%s' and (ending > '%s' or ending is null);""" % (
            aid, record_time)
        plans = db.special_select(sql)
        for plan in plans:
            if check_time(
                    plan['starting'].strftime("%Y-%m-%d %H:%M:%S").split(" ")
                [0],
                    record_time.split(" ")[0], plan['cycle']):
                new_credit = float(plan['credit']) + float(record['amt'])
                db.update(conn, "plans", {"=": {
                    'credit': new_credit
                }}, {'pid': plan['pid']})

        # influence win_honor
        valid_honor(conn, aid)

        return redirect(url_for('homepage.all_records'))
    else:
        return render_template("/homepage/AddingRecord.html",
                               msg="illegal values")
Пример #18
0
def writeDb(twoTeam, beforeAloRank, calResult):
    updateData = calResult
    updateData['host']['alo_rank_before'] = beforeAloRank['host']
    updateData['guest']['alo_rank_before'] = beforeAloRank['guest']

    sqlHost = "UPDATE {session} SET alo_rank_before={before},alo_rank={rank},alo_win_percentage={per} WHERE id={id} LIMIT 1".\
    format(session = matchDataSession, before = updateData['host']['alo_rank_before'], rank = updateData['host']['alo_rank'], \
    per = updateData['host']['alo_win_percentage'], id = twoTeam['host']['id'])

    sqlGuest = "UPDATE {session} SET alo_rank_before={before},alo_rank={rank},alo_win_percentage={per} WHERE id={id} LIMIT 1".\
    format(session = matchDataSession, before = updateData['guest']['alo_rank_before'], rank = updateData['guest']['alo_rank'], \
    per = updateData['guest']['alo_win_percentage'], id = twoTeam['guest']['id'])

    db.update(sqlHost)
    db.update(sqlGuest)
Пример #19
0
def push():
	sql = "SELECT * from ds_push where is_push=0";
	pushData = db.find(sql)

	mailTitle = '334规则'
	mailContent = ''
	pushIds = []
	for i in range(0, len(pushData)):
		tmpContent = pushData[i]['league_name'] + "\r\n<br>" + pushData[i]['host_name'] + "(" + str(pushData[i]['host_goal_num']) + "):(" + str(pushData[i]['guest_goal_num']) + ")" + pushData[i]['guest_name'] + "\r\n<br>"
		mailContent = tmpContent + mailContent
		pushIds.append(str(pushData[i]['match_id']))

	if pushIds:
		updateSql = "UPDATE ds_push SET is_push=1 WHERE match_id in (" + str(','.join(pushIds)) + ")"
		db.update(updateSql)

		#历史记录
		historySql = "SELECT * FROM ds_push order by id desc limit 20"
		historyData = db.find(historySql)
		historyContent = "\r\n<br>\r\n<br>历史记录\r\n<br>"
		if historyData:
			for k in range(0, len(historyData)):
				status = ''
				result = historyData[k]['result']
				if str(result) == '0':
					status = '<span style="color:#FFB848">未结算</span>'
				elif str(result) == '1':
					status = '<span style="color:red">红</span>'
				elif str(result) == '-1':
					status = '<span style="color:black">黑</span>'
				else:
					status = '未知错误'
				tmp = "          " + historyData[k]['league_name'] + "\r\n<br>(" + status + ")---" + historyData[k]['host_name'] + historyData[k]['guest_name'] + "\r\n<br>"
				
				historyContent = historyContent + tmp
		
		#历史rate
		winNumSql = "SELECT count(*) as win from ds_push where result=1"
		loseNumSql= "SELECT count(*) as lose from ds_push where result=-1"
		win = db.find(winNumSql)
		lose = db.find(loseNumSql)
		winNum = int(win[0]['win'])
		loseNum = int(lose[0]['lose'])
		rate = round(100*winNum/(winNum+loseNum), 2)

		mailContent += str(rate) + "%<br>"
		mailContent += historyContent
		mail(mailTitle, mailContent)
Пример #20
0
def updateResult(resultString):
	beforeTime = int(time.time()) - 86400*2
	needUpdateSql = "SELECT match_id FROM ds_push WHERE result=0 and created_at>{beforeTime}".format(beforeTime = beforeTime)
	needUpdateData= db.find(needUpdateSql)
	if len(needUpdateData) <= 0:
		return

	resultJson = json.loads(resultString)
	matchList = resultJson['rs']
	for i in range(0, len(matchList)):
		matchData = matchList[i]
		#比赛状态,int为分钟,’半‘表示半场结束,’全‘表示全场结束
		matchStatus = str(matchData['status'])
		if matchStatus == '-1':
			continue

		events = matchData['events_graph']['events']
		matchId = matchData['id']

		tmp = False
		for k in range(0, len(needUpdateData)):
			if str(matchId) == str(needUpdateData[k]['match_id']):
				tmp = True

		if tmp == False:
			continue

		num = 0;
		if events:
			for j in range(0, len(events)):
				t = events[j]['t']
				status = events[j]['status']
				if (status < '30') and ((t == 'gg') or (t == 'hg')):
					num += 1
				elif (status >= '30') and ((t == 'gg') or (t == 'hg') or (t == 'gp') or (t == 'hp')):
					num += 1
			
			if num >= 4:
				updateResult = 1
				updateSql = "UPDATE ds_push SET result={updateResult} WHERE match_id={matchId}".format(updateResult = updateResult, matchId = matchId)
				db.update(updateSql)
				continue

			if matchStatus == '半' or matchStatus == '全' or matchStatus > '45':
				updateResult = -1
				updateSql = "UPDATE ds_push SET result={updateResult} WHERE match_id={matchId}".format(updateResult = updateResult, matchId = matchId)
				db.update(updateSql)
				continue
Пример #21
0
async def parse(url: str, session: ClientSession, **kwargs) -> None:
    try:
        html = await fetch_html(url=url, session=session, **kwargs)
        soup = BeautifulSoup(html)
        body = soup.get_text()

    except (
            aiohttp.ClientError,
            aiohttp.http_exceptions.HttpProcessingError,
            Exception,
    ) as e:
        logging.warning(e)
        print(e)
        db.update({"error": str(e)}, Link.value == url)
        return None
    else:
        return body
Пример #22
0
def test_unsuccessful_update(rethink_connect):
    global unique_id
    update_statement = {"runtime": 164}
    result = update(database, empty_table, unique_id, update_statement,
                    rethink_connect)
    assert result is not None
    assert len(result) == 1
    assert result["objects_updated"] == 0
Пример #23
0
def show_projects():
    """
    call github api to get all repositories
    """
    #global glob_username
    url = 'https://api.github.com/users/YechengZhou/repos'
    last_update_time = db.select('select created_at from projects limit 0,1;')
    all_repositories_info = []
    print last_update_time

    if len(last_update_time) != 0 and int(time.time()) - int(last_update_time[0].created_at) < 3600 * 12:  # do not update within 12 hours
        all_repositories_info = db.select('select * from projects')
    else:
        all_rep = git_api_query(url)
        if isinstance(all_rep, list):
            for i in all_rep:
                logging.info("query url is : %s" % i['url'])
                i_result = git_api_query(i['url'])
                this_rep = db.MyDict()
                if isinstance(i_result, dict):
                    this_rep['name'] = i_result['name']
                    this_rep['html_url'] = i_result['html_url']
                    this_rep['description'] = i_result['description']
                    all_repositories_info.append(this_rep)
        #if len(last_update_time) == 0: # no project items currently, just insert what have got
            #flag_just_insert = True
        # update project schema based on new query result from Github api
        all_repo_name_db = db.select('select name from projects;')

        for p in all_repositories_info:
            if db.MyDict(('name',), (p.name,)) in all_repo_name_db:  # just update
                db.update("update projects set url=?, description=?, created_at=? where name=?", p['html_url'], p['description'], time.time(), p.name)
            else:
                this_project = Projects(
                    name=p['name'],
                    url=p['html_url'],
                    description=p['description']
                )
                this_project.insert()

    if session.has_key('username'):
        #dir(all_repositories_info[0])
        return render_template('projects.html', projects=all_repositories_info, username=session['username'], title='Projects')
    else:
        return render_template('projects.html', projects=all_repositories_info, title='Projects')
Пример #24
0
def modify_record():
    aid = request.cookies.get('aid')
    if aid is None or aid == "":
        return redirect(url_for("login.sign_in"))
    record = dict()
    reid = request.form.get("reid")
    record['name'] = request.form.get("name")
    record['be_from'] = request.form.get("be_from")
    record['be_to'] = request.form.get("be_to")
    record['amt'] = request.form.get("amt")
    record['time'] = to_valid_time(request.form.get("time"))
    record['tag'] = request.form.get("tag")
    record['remark'] = request.form.get("remark")

    old_amt = float(request.form.get('old_amt'))
    old_time = request.form.get('old_time')
    res = db.update(conn, 'records', {"=": record}, {'aid': aid})
    if res is True:
        # influence plans
        if record['time'] == "":
            record_time = old_time
        else:
            record_time = record['time']
        sql = """select * from plans where aid = '%s' and (ending > '%s' or ending is null);""" % (
            aid, record_time)
        plans = db.special_select(sql)
        for plan in plans:
            if record['amt'] != "" and check_time(
                    plan['starting'].strftime("%Y-%m-%d %H:%M:%S").split(" ")
                [0],
                    record_time.split(" ")[0], plan['cycle']):
                new_credit = plan['credit'] - old_amt + float(record['amt'])
                db.update(conn, "plans", {"=": {
                    'credit': new_credit
                }}, {'pid': plan['pid']})

        # influence win_honor
        valid_honor(conn, aid)

        return redirect(url_for(".all_records"))
    else:
        record = db.select(conn, "records", "*", {'reid': reid})[0]
        return render_template("/homepage/ModifyRecord.html",
                               record=record,
                               msg="illegal value")
Пример #25
0
def test_successful_update(rethink_connect):
    global unique_id
    update_statement = {"runtime": 164}
    result = update(database, table, unique_id, update_statement,
                    rethink_connect)
    assert result is not None
    assert len(result) == 2
    assert result["objects_updated"] == 1
    assert result["changes"][0]["new_val"]["runtime"] == 164 \
        and result["changes"][0]["old_val"]["runtime"] == 163
Пример #26
0
def test_successful_update(rethink_connect):
    global unique_id
    update_statement = {'runtime': 164}
    result = update(database, table, unique_id, update_statement,
                    rethink_connect)
    assert result is not None
    assert len(result) is 2
    assert result['objects_updated'] is 1
    assert result['changes'][0]['new_val']['runtime'] == 164 and \
        result['changes'][0]['old_val']['runtime'] == 163
Пример #27
0
def modify_post(**kwargs):
    action = kwargs.get('action', 'create')
    if action == 'create':
        kwargs['author_id'] = web.config.get('_session').user_id
        kwargs['create_time'] = kwargs['update_time'] = time.mktime(
            datetime.utcnow().timetuple())
        return db.insert('articals', **kwargs)
    elif action == 'update':
        artical_id = kwargs.pop('artical_id')
        #kwargs['update_time'] = time.mktime(
        return db.update('articals', **kwargs)
Пример #28
0
def hide(keep, color, archived, count):
    with db.cursor() as cur:
        for item in cur:
            raise click.Abort("DB isn't empty")

    notes = keep.find(colors=[gkeepapi.node.ColorValue[color]],
                      archived=archived)
    data = {}
    for i, n in enumerate(notes, start=1):
        print_note(n)
        n.pinned = True
        n.archived = False
        data[n.id] = n.title + TEXT_TITLE_SEP + n.text
        n.title = n.text = ''
        if i == count:
            break

    print(len(data))
    db.update(data)

    keep.sync(dump=True)
Пример #29
0
def valid(proxy):
    print('test proxy %s' % proxy)
    proxies = {'http': 'http://%s' % proxy, 'https': 'https://%s' % proxy}
    headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0 Win64 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
    }
    try:
        start = time.time()
        urllib3.disable_warnings()
        resp = requests.get(VALID_URL,
                            proxies=proxies,
                            headers=headers,
                            verify=False)
        if resp.status_code in [200, 302]:
            delay = round(time.time() - start)
            print('update %s by delay %s' % (proxies, delay))
            db.update({'address': proxy}, {'delay': delay})
        else:
            print('验证请求错误!', proxy)
    except Exception:
        pass
Пример #30
0
    def put(self, id_):
        entry = json.loads(request.form["entry"])
        question = entry.get("question", None)
        answer = entry.get("answer", None)
        date = entry.get("date", None)
        tags = entry.get("tags", None)
        try:
            record = db[id_]
            if question is not None:
                db.update(record, question=question)
            if answer is not None:
                db.update(record, answer=answer)
            if date is not None:
                db.update(record, date=date)
            if tags is not None:
                db.update(record, tags=tags)
        except KeyError:
            db.insert(question, answer, date, tags)

        db.commit()
        return "", 200
Пример #31
0
def modify_plans():
    aid = request.cookies.get('aid')
    if aid is None or aid == "":
        return redirect(url_for("login.sign_in"))
    plan = dict()
    pid = request.form.get("pid")
    plan['starting'] = to_valid_time(request.form.get("starting"))
    plan['ending'] = to_valid_time(request.form.get("ending"))
    plan['cycle'] = request.form.get("cycle")
    plan['budget'] = request.form.get("budget")

    old_budget = float(request.form.get("old_budget"))
    old_credit = float(request.form.get("old_credit"))
    if plan['budget'] != "":
        plan['credit'] = float(plan['budget']) - (old_budget - old_credit)

    res = db.update(conn, 'plans', {"=": plan}, {'aid': aid})
    if res is False:
        plan = db.select(conn, "plans", "*", {'pid': pid})
        return render_template("/plans/ModifyPlans.html",
                               plan=plan,
                               msg="illegal value")
    else:
        return redirect(url_for(".own_plans"))
Пример #32
0
def modify_defaults():
    aid = request.cookies.get('aid')
    if aid is None or aid == "":
        return redirect(url_for("login.sign_in"))
    default = dict()
    did = request.form.get("did")
    default['name'] = request.form.get("name")
    default['be_from'] = request.form.get("be_from")
    default['be_to'] = request.form.get("be_to")
    default['amt'] = request.form.get("amt")
    default['starting'] = to_valid_time(request.form.get("starting"))
    default['ending'] = to_valid_time(request.form.get("ending"))
    default['cycle'] = request.form.get("cycle")
    default['tag'] = request.form.get("tag")
    default['remark'] = request.form.get("remark")

    res = db.update(conn, 'defaults', {"=": default}, {'aid': aid})
    if res is False:
        default = db.select(conn, "defaults", "*", {'did': did})
        return render_template("/defaults/ModifyDefaults.html",
                               default=default,
                               msg="illegal value")
    else:
        return redirect(url_for(".own_defaults"))
Пример #33
0
def update_status(order, status):
    args = dict(order = order)
    res = db.update('Orders', vars=args,
            where='id = $order', status = status)
    update_ingredients(order);
Пример #34
0
# coding=utf-8
Пример #35
0
def update_qty(ingredient, qty):
    init = db.select('Ingredient_Inventory', vars = dict(ingredient = ingredient), where='ingredient=$ingredient').list()
    args = dict(ingredient = ingredient)
    for x in init:
        res = db.update('Ingredient_Inventory', vars = args, where='ingredient = $ingredient', qty = x.qty - qty)
Пример #36
0
 def update(self, id, param):
     task = cls.find({"id": id})
     if task:
         db.update(task).values(**param)
Пример #37
0
def update_email(userid, email):
    try:
        return db.update(table, where="id=$userid", vars={'userid':userid}, email=email)  
    except:
        return None
Пример #38
0
def set_status( item_id, status):
    db.update('MenuItems', vars=locals(), where='id=$item_id', available=status)
Пример #39
0
 def save(self,update=False):
     if update == False:
         db.insert(table, username=self.username, password=self.encrypt_passwd, **self.opts)
     else:
         db.update(table, where="username=$username", vars={'username':self.username}, password=self.encrypt_passwd, **self.opts)    
Пример #40
0
# coding=utf-8
Пример #41
0
def pay_receipt(order_no):
    args = dict(order_no=order_no)
    db.update("Receipts", vars=args, where="order_id=$order_no", paid=1)
Пример #42
0
def update_quantity(order, item, qty):
    args = dict(order=order, item=item, qty=qty)
    res = db.update("OrderedItems", vars=args,
            where='order_id = $order and item_id = $item', qty = qty)
Пример #43
0
def reject_receipt(order_no):
    args = dict(order_no=order_no)
    db.update("Receipts", vars=args, where="order_id=$order_no", paid=0)
    return "Receipt for order "+str(order_no)+" rejected"
Пример #44
0
def change_pass(uid, passwd):
    db.update('Users',vars=locals(),  where="id = $uid",
            password=bcrypt.hashpw(str(passwd), bcrypt.gensalt()) )
Пример #45
0
def modify_user(uname, utype):
    db.update('Users', vars=dict(uname=uname, utype = utype), where="uname=$uname", role = utype)
Пример #46
0
def accept_receipt(order_no):
    args = dict(order_no=order_no)
    db.update("Receipts", vars=args, where="order_id=$order_no", paid=2)
    return "Receipt for order "+str(order_no)+" accepted"
Пример #47
0
def onedata(id):

    # GET a specific data by id
    if request.method == 'GET':
        r, status = db.read(id)
        if status != 200:
            return jsonify({"status": "get failed", "error": r}), status
            # return Response({"status": "get failed", "error": err}, 500, mimetype='application/json')

        print(r)
        if len(r) > 0:
            r = r[0]
            result = {
                "id": r[0],
                "username": r[1],
                "firstname": r[2],
                "lastname": r[3],
                "uploadTime": r[4],
                "createdAt": r[5],
                "updatedAt": r[6],
                "description": r[7],
                "isDeleted": r[8]
            }

            return jsonify({"status": "get success", "data": result}), status
        else:
            return jsonify({
                "status": "not found",
                "data": f"No record found for id: {id}"
            }), 404
        # return Response({"status": "get success", "data": result}, 200, mimetype='application/json')

    # DELETE a data
    if request.method == 'DELETE':
        resp, status = db.delete(id)
        if status != 204:
            return jsonify({"status": "delete failed", "error": resp}), status
            # return Response({"status": "delete failed", "error": err}, 500, mimetype='application/json')
        if resp > 0:
            return jsonify({"status": "delete success", "data": resp}), 200
        else:
            return jsonify({
                "status": "not found",
                "data": f"No record found to delete for id: {id}"
            }), 404

        # return Response({"status": "delete success", "data": resp}, 200, mimetype='application/json')

    # UPDATE a data by id
    if request.method == 'PUT':
        if id is None:
            return jsonify({
                "status": "failed",
                "msg": "invalid id to update data"
            }), 400

        body = request.json
        if body:
            if "username" not in body:
                return jsonify({
                    "status": "failed",
                    "msg": "username required"
                }), 400
            elif "firstname" not in body:
                return jsonify({
                    "status": "failed",
                    "msg": "firstname required"
                }), 400
            elif "lastname" not in body:
                return jsonify({
                    "status": "failed",
                    "msg": "lastname required"
                }), 400
            elif "uploadTime" not in body:
                return jsonify({
                    "status": "failed",
                    "msg": "uploadTime required"
                }), 400
            elif "updatedAt" not in body:
                return jsonify({
                    "status": "failed",
                    "msg": "updatedAt required"
                }), 400
            elif "description" not in body:
                return jsonify({
                    "status": "failed",
                    "msg": "description required"
                }), 400

            # username = body['username']
            # firstname = body["firstname"]
            # lastname = body["lastname"]
            # uploadTime = body["uploadTime"]
            # description = body["description"]

            resp, status = db.update(id, body)
            if status != 201:
                return jsonify({
                    "status": "update failed",
                    "error": resp
                }), status
                # return Response({"status": "update failed", "error": err}, 500, mimetype='application/json')

            return jsonify({"status": "update success", "data": resp}), status
            # return Response({"status": "update success", "data": resp}, 200, mimetype='application/json')

        else:
            return jsonify({
                "status": "failed",
                "msg": "invalid request body"
            }), 400
Пример #48
0
def modify_user_settings(uid, values):
    db.update(table='user_settings', conditions={'user': uid}, values=values)