def modify_pwd(): if not session.get('name'): return redirect('/') if request.method == 'GET': id = request.args.get('id') return render_template('modify_pwd.html',user = db.update_list(id)) else: data = dict(request.form) if data['newpassword'][0] != data['renewpassword'][0]: errmsg = 'The two passwords you typed do not match' return json.dumps({'code':'1','errmsg':errmsg}) if not data['password'][0] or not data['newpassword'][0] or not data['renewpassword'][0]: errmsg = 'password can not be null' return json.dumps({'code':'1','errmsg':errmsg}) try: condition = [ "%s='%s'" % ('password',v[0]) for k,v in data.items() if k == 'newpassword'] db.update(condition,data['id'][0]) if session.get('role'): return json.dumps({'code':'0','result':'modify success!'}) else: return redirect('/') except: errmsg = "modify failed" return json.dumps({'code':'1','errmsg':errmsg})
def delete(self): self.pre_delete and self.pre_delete pk = self.__primary_key__.name print '###########',pk args = (getattr(self,pk),) db.update('delete from %s where %s=?' %(self.__table__,pk),*args) return self
def delete(self): #self.pre_delete和self.pre_delete()? self.pre_delete and self.pre_delete() pk = self.__primary_key__.name args = (getattr(self, pk),) db.update('delete from ‘%s‘ where ‘%s‘=?' % (self.__table__, pk), *args) return self
def mongo_update(): host = request.form.get('ip') back_num = 'ls /backup/mongodata/backup/full |wc -l' back_name = 'ls -rt /backup/mongodata/backup/full|tail -1' back_size = "ls -lrt --block-size=M /backup/mongodata/backup/full|tail -1|awk '{print $5}'" back_endtime = "ls -lrt /backup/mongodata/backup/full|tail -1|awk '{print $(NF-1)}'" try: # 如果页面没有设置备份时间,则默认设置05:05存入数据库 if json.loads(db.get_one(['back_starttime'], "wan_ip='%s'" % host, 'virtuals'))['back_starttime'] is None: back_startTime = '05:05' data = dict({'back_startTime': back_startTime}) where = 'wan_ip=' + "'%s'" % host db.update(data, where, 'virtuals') else: back_startTime = json.loads(db.get_one(['back_starttime'], "wan_ip='%s'" % host, 'virtuals'))['back_starttime'] back_endTime = util.paramiko_command(host, back_endtime) back_startTime=datetime.datetime.strptime(back_startTime, "%M:%S") if back_endTime == 1: back_endTime = '00:00' back_endTime = datetime.datetime.strptime(back_endTime, "%M:%S") seconds = (back_endTime-back_startTime).seconds hours = seconds / 60 second = seconds % 60 back_used_time = '%s小时%s分' % (hours, second) referesh_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') data = dict({'back_num': util.paramiko_command(host, back_num), 'back_name': util.paramiko_command(host, back_name), 'back_size': util.paramiko_command(host, back_size), 'back_endtime': util.paramiko_command(host, back_endtime), 'back_used_time': back_used_time, 'refresh_time': referesh_time}) if len(str(data['back_size'])) >= 5: data['back_size'] = str(round(float(float(data['back_size'][0:-1]) / 1024),2)) + 'G' where = 'wan_ip=' + "'%s'" % (host) db.update(data, where, 'virtuals') except: traceback.print_exc() return render_template('monitor/mongo_monitor.html', display = dis)
def create_user_token(user_id, **kwargs): user_token_id = db.insert("INSERT INTO user_tokens (user_id, token) VALUES(%s, UUID())", [user_id]) for field_name in kwargs: db.update("UPDATE user_tokens SET " + field_name + " = %s WHERE id = %s", [kwargs[field_name], user_token_id]) return db.fetchrow("SELECT * FROM user_tokens WHERE id = %s", [user_token_id])
def dinge_aendern(request): if request.method != 'POST': return redirect('/helfer') userid = request.session['userid'] new_email = request.form.get('email') new_mobile = request.form.get('mobile') want_shirt = request.form.get('want_participant_shirt') == "on" old_want_shirt = db.select('SELECT want_participant_shirt FROM person WHERE id=?', (userid,)) if len(old_want_shirt) != 1: ## this should never happen, if the @require_login works as expected ## (i.e. if you ever trigger this assertion, go fix @require_login) assert False old_want_shirt= old_want_shirt[0]['want_participant_shirt'] ## XXX: this feels redundant, but also sql-injection-exploitable if ## shortened too much.. if config.shirt_stuff_changeable: db.update('''UPDATE person SET email=?,mobile=?,want_participant_shirt=? WHERE id=?''', (new_email, new_mobile, want_shirt, userid)) else: db.update('''UPDATE person SET email=?,mobile=? WHERE id=?''', (new_email, new_mobile, userid)) return redirect('/helfer/%d' % (userid,))
def update(self): """ 如果该行字段updatable,表示该字段可更新 继承Model的类是一个 Dict对象,该Dict的键值对会变成实例的属性 可以通过属性来判断,该对象是否有这个字段 如果有属性,就是用用户传入的值 否则是用字段的default值 """ if self.pre_update: self.pre_update() L = [] args = [] for k,v in self.__mappings__.iteritems(): if v.updatable: if hasattr(self,k): arg = getattr(self,k) else: arg = v.default setattr(self,k,arg) L.append("`%s` = ?" %k) args.append(arg) pk = self.__primary_key__.name args.append(getattr((self,pk))) db.update('update `%s` set %s where %s = ?' %(self.__table__,','.join(L),pk),*args) return self
def update(self): """ 如果该行的字段属性有 updatable,代表该字段可以被更新 用于定义的表(继承Model的类)是一个 Dict对象,键值会变成实例的属性 所以可以通过属性来判断 用户是否定义了该字段的值 如果有属性, 就使用用户传入的值 如果无属性, 则调用字段对象的 default属性传入 具体见 Field类 的 default 属性 通过的db对象的update接口执行SQL SQL: update `user` set `passwd`=%s,`last_modified`=%s,`name`=%s where id=%s, ARGS: (u'******', 1441878476.202391, u'Michael', 10190 """ self.pre_update and self.pre_update() L = [] args = [] for k, v in self.__mappings__.iteritems(): if v.updatable: if hasattr(self, k): arg = getattr(self, k) else: arg = v.default setattr(self, k, arg) L.append('`%s`=?' % k) args.append(arg) pk = self.__primary_key__.name args.append(getattr(self, pk)) db.update('update `%s` set %s where %s=?' % (self.__table__, ','.join(L), pk), *args) return self
def toggle_admin_flag(request): if request.method != 'POST': return render_template('error.xml', error_short='invalid request', error_long='you didnt send a POST request. we don\'t understand anything else', session=request.session) userid = request.form.get('toggle_uid') valid_uid = True if not db.sane_int(userid): valid_uid = False rows = db.select('SELECT * FROM person WHERE id=?', (userid,)) if len(rows) != 1: valid_uid = False if not valid_uid: return render_template('error.xml', error_short='invalid userid', error_long='that is not a valid userid', session=request.session) ## probably ok by now was_admin_before = rows[0]['is_admin'] db.update('UPDATE person SET is_admin=? WHERE id=?', (not was_admin_before, userid)) return redirect('/admin')
def create_table(self, **kwargs): if kwargs.has_key('sub_name'): sub_name = kwargs['sub_name'] else: sub_name = "" print self.__sql__() db.update(self.__sql__()%(sub_name))
def user_unclaim_schicht(request): if request.method != 'GET': return render_template('error.xml', error_short='invalid request', error_long='you didnt send a GET request. we don\'t understand anything else', session=request.session) if not 'userid' in request.args or not 'schichtid' in request.args or not 'tag' in request.args: return render_template('error.xml', error_short='invalid request', error_long='you didnt send userid or schichtid parameters. we cannot work like this', session=request.session) userid = request.args['userid'] schichtid = request.args['schichtid'] tag = request.args['tag'] if not db.sane_int((userid, schichtid, tag)): return render_template('error.xml', error_short='invalid request', error_long='you didn\'t provide numeric arguments. we cannot work like that', session=request.session) userid = int(userid) schichtid = int(schichtid) tag = int(tag) db.update('DELETE FROM person_schicht WHERE pers_id=? AND schicht_id=?', (request.args['userid'], request.args['schichtid'])) ## redirect zu da wo der request typischerweise her kommt return redirect('/schicht#tabs-%d' % tag)
def passwort_aendern(request): if request.method != 'POST': return redirect('/helfer') old_pw = request.form.get('old_pw') new_first = request.form.get('new_first') new_second = request.form.get('new_second') if not check_login_credentials(request.session['username'], old_pw): error_long = u"Das alte Passwort, das du eingegeben hast, stimmt nicht. Du kannst dein Passwort auch bei einem Admin ändern lassen, frag am besten per Mail bei %s" % config.admin_email return render_template('error.xml', error_short=u"altes passwort falsch", error_long=error_long, session=request.session) if new_first != new_second: error_long = u"Die beiden neuen Passwörter sind nicht gleich. Du hast dich sehr wahrscheinlich vertippt. Du kannst dein Passwort auch bei einem Admin ändern lassen, frag am besten per Mail bei %s" % config.admin_email return render_template('error.xml', error_short=u"Neue Passwörter sind unterschiedlich", error_long=error_long, session=request.session) crypted = sha256_crypt.encrypt(new_first) db.update('UPDATE person SET password=? WHERE id=?', (crypted, request.session['userid'])) return redirect('/redirect/my_page')
def update_contest_statistics(result): """ 更新比赛统计数据 :param result: :return: """ count = db.select_int('select count(*) from t_ranking where contest_id=? and problem_id=? and username=?', result['contest_id'], result['problem_id'], result['user_id']) if count == 0: record = dict(contest_id=result['contest_id'], problem_id=result['problem_id'], username=result['user_id']) db.insert('t_ranking', **record) p_time = db.select_one('select AC_time from t_ranking where contest_id=? and problem_id=? and username=?', result['contest_id'], result['problem_id'], result['user_id']).get('AC_time') if p_time == 0: # 本题还没有AC if result['result'] == configs.result_code.AC: # 本题初次AC with db.connection(): submit_time = db.select_one('select submit_time from t_submission where submission_id=?', result['solution_id']).get('submit_time') # 提交时间, datetime类型 date_time = db.select_one('select contest_date, start_time from t_contest where contest_id=?', result['contest_id']) c_date = date_time.get('contest_date') # 比赛开始日期, date类型 c_time = date_time.get('start_time') # 比赛开始时间, timedelta类型 # 转换为比赛开始时间, datetime类型 contest_time = datetime.strptime(c_date.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S') + c_time ac_time = (submit_time - contest_time).total_seconds() / 60 # 本题初次AC所用时间, 单位为分钟, float类型 with db.transaction(): db.update('update t_ranking set AC_time=? where contest_id=? and problem_id=? and username=?', ac_time, result['contest_id'], result['problem_id'], result['user_id']) # AC题目所用时间 else: db.update('update t_ranking set wrong_submit = wrong_submit + 1 where contest_id=? and problem_id=? ' 'and username=?', result['contest_id'], result['problem_id'], result['user_id'])
def post(self): username = self.get_argument('email', '') birthday = self.get_argument('birthday', '') height = self.get_argument('height', '') weight = self.get_argument('weight', '') date = self.get_argument('date', '') result = self.get_argument('result', '') # 默认为修改失败 data = {'status':101, } # 修改用户的最新身高体重 sql = "update `ofUser` set birthday=?, height=?, weight=? where username=? " db.update(sql, birthday, height, weight, username) # 问卷结果 sql = "select * from `ofQuestionResult` where username=? and date=? " res = db.select_one(sql, username, date) # 今天已经测试过 if res: sql = "update `ofQuestionResult` set birthday=?, height=?, weight=?, result=? where username=? and date=? " res = db.update(sql, birthday, height, weight, result, username, date) # 今天未测试过 else: table = "ofQuestionResult" kw = {"username":username, "birthday":birthday, "height":height, "weight":weight, "date":date, "result":result} res = db.insert(table, **kw) data['status'] = 100 json_result = json.dumps(data , ensure_ascii=False) # 把python对象编码成json格式的字符串 self.write(json_result)
def task_set(arguments): if arguments['schedule']: kwargs = _task_sched_kwargs(arguments) elif arguments['parent']: kwargs = dict(parent=arguments['<parent>']) elif arguments['email']: kwargs = dict(email=arguments['<email>']) elif arguments['resources']: kwargs = dict(resources=arguments['<resources>']) elif arguments['log']: kwargs = dict(log=arguments['<text>']) else: kwargs = dict( (field, arguments['<exe>']) for field in ['condition', 'command'] if arguments[field] ) assert kwargs, 'unexpected empty attrs to set for tasks' db.update('tasks', name=arguments['<name>'], **kwargs) arguments['--fields'] = 'name,' + ','.join(kwargs.keys()) _task_list_table(arguments)
def downloadTar(ftp, path, tarfile): try: ftp.cwd("/" + path) log.logger.debug("Succesfully changed dir to /" + path) except Exception as e: log.logger.critical("Fail during directory change of /" + path) log.logger.debug(e) raise Exception try: ftp.retrbinary("RETR " + tarfile, open(tarfile, "wb").write) log.logger.debug("Succesfully downloaded " + tarfile) except Exception as e: log.logger.critical("Fail retriefing file " + tarfile) log.logger.debug(e) raise Exception ftp_db = db.connect(config.get("db_host"), config.get("db_user"), config.get("db_password"), config.get("db_name")) q = ( 'UPDATE ftp_index SET downloaded = 1, download_date = "' + str(datetime.now()) + '" WHERE tar = "' + tarfile + '"' ) try: db.update(ftp_db, q) log.logger.debug("Succesfully updated ftp_index database with downloaded file") except Exception as e: log.logger.critical("Could not update ftp_index database") log.logger.debug(e)
def indexRemoteTars(tar_list): try: tar_db = db.connect( config.get("db_host"), config.get("db_user"), config.get("db_password"), config.get("db_name") ) log.logger.debug("Succesfully connected to database on: " + config.get("db_host")) except Exception as e: log.logger.critical("Could not connect database to :" + config.get("db_host")) log.logger.debug(e) for tar in tar_list: try: if int(tar["name"].split("_")[2][:8]) < 20130924: remote_dir = tar["name"].split("_")[2][:8] elif tar["remote_dir"] is None: remote_dir = "" else: remote_dir = tar["remote_dir"] q = 'INSERT INTO ftp_index (tar,remote_dir) VALUES ("' + tar["name"] + '","' + str(remote_dir) + '")' db.update(tar_db, q) log.logger.debug("Succesfully added this record to the database: " + tar["name"]) except Exception as e: log.logger.critical("Could not add record " + tar["name"] + " this is a CRITICAL -> EXITING") exit(1)
def update(self): self.pre_update and self.pre_update() pk = self.__primary_key__.name db.update(self.__table__, where=[(self.__primary_key__.name, getattr(self, pk))], **dict([(f.name, getattr(self, f.name)) for f in self.__fields__.itervalues() if f.updatable])) return self
def delete(self): self.pre_delete and self.pre_delete() pk = self.__primary_key__.name args = (getattr(self, pk),) db.update('delete from `%s` where `%s`=?' % (self.__table__, pk), *args) return self
def updateFilename(): try: ml_db = db.connect(config.get('db_host','ml_analyse'),config.get('db_user','ml_analyse'),config.get('db_password','ml_analyse'),config.get('db_name','ml_analyse')) log.logger.debug('Succesfully connected to database ' + config.get('db_host','ml_analyse')) except Exception as e: log.logger.critical('Could not connect to database ' + config.get('db_host','ml_analyse')) log.logger.debug(e) exit(1) q = 'SELECT Id,path FROM ml' try: records = db.query(ml_db,q) log.logger.debug('Succesfully queried tha ml_db database') except Exception as e: log.logger.critical('Unable to query ml_db database') log.logger.debug(e) for record in records: filename_full = record['path'].split('/')[-1] filename = filename_full[:-len(filename_full.split('.')[-1]) - 1] #print filename + '\t' + record['path'] q = 'UPDATE ml SET filename = "' + str(filename) + '" WHERE Id = ' + str(record['Id']) try: db.update(ml_db,q) except Exception as e: log.logger.cirtical('Could not update id ' + str(record['Id']))
def delete(self): print 'enter delete()...' self.pre_delete and self.pre_delete() print '...' pk=self.__primary_key__ args=(getattr(self,pk),) db.update('delete from %s where %s=?' % (self.__table__,pk),*args) return self
def _do_schedule_group(self, name, dateObj, timeObj): groupObj = db.Group.get_by(name=name) if not groupObj: self._output_error("Group name %s is not valid.", name) dbObj = db.Schedule(fk_group=groupObj, date=dateObj, time=timeObj) db.update()
def _do_schedule_element(self, name, dateObj, timeObj): elementObj = db.Element.get_by(name=name) if not elementObj: self._output_error("Element name %s is invalid.", name) dbObj = db.Schedule(fk_element=elementObj, date=dateObj, time=timeObj) db.update()
def test_update(self): row = db.insert('data', {'type': 'weight'}) row['value'] = 150 db.update('data', row) row2 = db.row('select * from data') assert_equal(150, row2['value'])
def delete(self): """通过update接口执行sql sql: delete from 'user' where `id` = %s, args:(1090,) """ self.pre_delete and self.pre_delete() pk = self.__primary_key__.name args = (getattr(self,pk),) db.update('delete from `%s` where `%s`= ?' %(self.__table__,pk), *args) return self
def delete(self): """ 通过db对象的update接口执行sql SQL: delete from `user` where `id`=%s, ARGS:(10190,) """ self.pre_delete and self.pre_delete() pk = self.__primary_key__.name args = (getattr(self, pk),) db.update('delete from `%s` where `%s`=?' % (self.__table__, pk), *args) return self
def acquire(self): if not self._db_record.user: self._db_record.user = active_user_name() db.update(self.tableName, name=self.name, user=self._db_record.user) elif self._db_record.user == active_user_name(): raise UserWarning('you have already acquired: ' + self.name) else: raise PermissionError('already owned by: ' + self._db_record.user)
def updateone(): if request.method=='GET': id = request.args.get('id') return render_template('updateone.html',user = db.update_list(id)) else: data = dict(request.form) conditions = [ "%s='%s'" % (k,v[0]) for k,v in data.items()] db.update(conditions,data['id'][0]) return render_template('userone.html',user = db.update_list(data['id'][0]))
def delete(self): pk=self.__pri_key__.name if pk is None: raise 'no pri_key vaules' kid=getattr(self,pk) sql="delete from %s where %s=? " %(self.__table__,pk) print sql kid=(kid,) db.update(sql,*kid) return self
def release(self, force: bool = False): if not self._db_record.user: raise UserWarning('already free: ' + self.name) elif self._db_record.user != active_user_name() and not force: raise PermissionError('owned by other: {}'.format(self._db_record.user)) else: self._db_record.user = '' db.update(self.tableName, name=self.name, user=self._db_record.user)
def update(self): self.pre_update and self.pre_update() L = [] args = [] for k, v in self.__mappings__.iteritems(): if v.updatable: if hasattr(self, k): arg = getattr(self, k) else: arg = v.default setattr(self, k, arg) L.append('`%s`=?' % k) args.append(arg) pk = self.__primary_key__.name args.append(getattr(self, pk)) db.update( 'update `%s` set %s where %s=?' % (self.__table__, ','.join(L), pk), *args) return self
def update_status(): data = dict((k, v[0]) for k, v in dict(request.form).items()) res = {} if data['work_status'] == '1': data['handle_name'] = session.get('name') # # 获取申请人email地址 # user = db.list('users',fields_user,session.get('id')) # email = user['email'] # res['operate'] = 'Consent to apply' # res['work'] = 'Consent to apply' # # 发送邮件 # myMail.mymail(localemail,passwd,email,res) else: data['handle_time'] = time.strftime(ISOTIMEFORMAT, time.localtime()) # myMail.mymail() conditions = ["%s='%s'" % (k, v) for k, v in data.items()] db.update('work', conditions, data['id']) return json.dumps({'code': 0, 'result': 'execute completed!'})
def remember_link(request): if type(request) == list and len(request) == 3: overwrite = False if request[1] in Links: overwrite = True prevVal = Links[request[1]] request[2] = remove_braces_from_link(request[2]) Links[request[1]] = request[ 2] # + ("v" if str(request[2].endswith(".gif")) else "") # can be activated if overwrite: db.update(links_db, request[1], request[2]) return "'%s' overwritten, previous value: '%s'" % (request[1], prevVal) else: db.insert(links_db, request[1], request[2]) return "'%s' remembered" % request[1] else: return "Wrong number of parameters. Usage: /remember <name> <link>"
def save(self, extend): """Save and update the extend""" attributes = dumps(extend.attributes) return (db.update(self.table). mset(dict(type=extend.type, label=extend.label, key=extend.key, attributes=attributes, field=extend.field)) .condition('eid', extend.eid).execute())
def setUp(self): setattr(db, '__db', {}) db.setup(config, adapter='pymysql') _create() users = [] for i in range(1, 6): users.append((i, 'user_' + str(i))) db.execute('delete from users') db.execute('INSERT INTO users VALUES(%s, %s)', users) self.update = db.update('users')
def modpwd(): if not session.get('name'): return redirect('/') if request.method == 'GET': sesname = session.get('name') name = request.args.get('name') if not name: name = sesname return render_template('modpwd.html', username=sesname, name=name) else: data = dict(request.form) if data['newpassword'][0] != data['renewpassword'][0]: errmsg = 'The two passwords you entered do not match' return json.dumps({'code': '1', 'errmsg': errmsg}) if not data['password'][0] or not data['newpassword'][0] or not data[ 'renewpassword'][0]: errmsg = 'password can not be null' return json.dumps({'code': '1', 'errmsg': errmsg}) try: condition = [ "%s='%s'" % ('password', v[0]) for k, v in data.items() if k == 'newpassword' ] sesname = session.get('name') print db.userlist(sesname) if session.get('role') == 'admin': db.update(condition, data['id'][0]) return json.dumps({'code': '0', 'result': 'modify completed!'}) elif session.get('role') == 'user': if data['password'][0] == db.userlist(sesname)['password']: return json.dumps({ 'code': '0', 'result': 'modify completed!' }) return json.dumps({ 'code': '1', 'errmsg': 'wrong old password' }) else: return redirect('/') except: errmsg = "modify failed" return json.dumps({'code': '1', 'errmsg': errmsg})
def update_all(self): """Update all attributes in the tuple""" L = [] args = [] for k, v in self.__fields__.items(): if v.editable: if hasattr(self, k): arg = getattr(self, k) else: arg = v.default setattr(self, k, arg) L.append('`%s`=?' % k) args.append(arg) pk = self.__primary_key__.name args.append(getattr(self, pk)) db.update( 'update %s set %s where %s=?' % (self.__table_name__, ','.join(L), pk), *args) return self
def update_command(id, enabled): query = """ UPDATE user_commands SET enabled = {enabled} WHERE id = {id} RETURNING id, enabled """.format(id = id, enabled = enabled) print(query) if os.getenv('DEV'): return return db.update(query)[0]
def modify_pwd_all(): if request.method == 'GET': id = request.args.get('id') return render_template('modify_pwd_all.html', user=db.update_list(id)) else: data = dict(request.form) if data['newpassword'][0] != data['renewpassword'][0]: errmsg = 'The two passwords you typed do not match' return render_template('modify_pwd_all.html', result=errmsg) try: condition = [ "%s='%s'" % ('password', v[0]) for k, v in data.items() if k == 'newpassword' ] db.update(condition, data['id'][0]) return render_template('userlist.html', users=db.userlist()) except: errmsg = "modify failed" return render_template('modify_pwd_all.html', result=errmsg)
def setupdates(): ''' The input receives the data of the group that you want to update ''' content = request.get_json() for post in content['content']: users = db.update(post, content['url']) for user in users: bot.send_message(user, "<strong>Поступило обновление с {}:</strong> \n\n {} \n\n {}".format(content['title'], post['text'], post['url']), parse_mode="HTML") return json.dumps({'status': 'ok'})
def updatacab(): if session.get('name', None): redirect('/login') if request.method == 'POST': data = dict(request.form) fields = ['name', 'idc_id', 'u_num', 'power'] table = 'cabinet' condition = ["%s='%s'" % (k, v[0]) for k, v in data.items()] try: db.update(condition, data['id'][0], table) return json.dumps({'code': 0, 'result': 'add cabinet success'}) except: print traceback.print_exc() return json.dumps({'code': 1, 'errmsg': 'update cabinet error'}) else: id = request.args.get('id') print id fields = ['id', 'name', 'idc_id', 'u_num', 'power'] table = 'cabinet' try: result = db.selectId(fields, id, table) cabinet = dict((k, result[i]) for i, k in enumerate(fields)) table_idc = 'idc' fields_idc = ['id', 'name'] result = db.selectAll(fields_idc, table_idc) print result idcs = [ dict((k, row[i]) for i, k in enumerate(fields_idc)) for row in result ] return render_template('cabinet/updatecabinet.html', info=session, cabinet=cabinet, idcs=idcs) except: print traceback.print_exc() return json.dumps({ 'code': 1, 'result': 'select cabinetinfo failed' })
def play(): #game rules global gameStatus #print(gameStatus) #print(playerDeck) #print(turn) if gameStatus == "ingame": #print(playerDeck) if turn == "player" and getTotal(playerDeck) < 21: addCard(playerDeck, "flipped") if getTotal(playerDeck ) > 21: #check if total of player deck is over 21 #print(getTotal(playerDeck)) gameStatus = "lost" dbase.userInfo['coins'] -= wager gameStatus = "standby" flash("YOU LOST!") if turn == "dealer": if getTotal(dealerDeck) < 17 or dealerDeck[0][ 1] == "unflipped": #while dealer has a total less than 17, keep drawing dealerTurn() if getTotal( dealerDeck) > 21: #comparing totals to determine winner gameStatus = "win" dbase.userInfo['coins'] += int(wager * 1.5) gameStatus = "standby" flash("YOU WON!") elif getTotal(playerDeck) == getTotal(dealerDeck): gameStatus = "tie" gameStatus = "standby" flash("TIE!") elif getTotal(playerDeck) > getTotal(dealerDeck): gameStatus = "win" dbase.userInfo['coins'] += int(wager * 1.5) gameStatus = "standby" flash("YOU WON!") elif getTotal(dealerDeck) > getTotal(playerDeck): gameStatus = "lose" dbase.userInfo['coins'] -= wager gameStatus = "standby" flash("YOU LOST!") dbase.update()
def finalize_db(self): main = self.ui.masterpw2_entry.text() conf = self.ui.confirmmasterpw2_entry.text() if main == conf: master_pw = main.encode('utf-8') self.master_hash = process.hasher(master_pw) self.key,salt = process.pbkdf(master_pw) if self.filepath: db.create(self.filepath) db.update(self.filepath, self.master_hash, salt) QMessageBox(QMessageBox.Information,'Success','Database has been created').exec() self.refresh_page2() self.display() self.ui.stacked_wid.setCurrentIndex(2) else: QMessageBox(QMessageBox.Warning,'Error','Please select a path for database first').exec() else: QMessageBox(QMessageBox.Warning,'Error','Those passwords do not match, try again').exec()
def update_picks_table_with_result(current_week, prod_str): """ :return: """ q = """select picks.id, picks.winner_id, picks.result, games.spread_winner_id, games.push from picks LEFT JOIN games on picks.game_id = games.id where games.moneyline_winner_id is not NULL and picks.result is NULL and games.week = {}""".format( current_week) results = pd.read_sql(q, prod_str) if not results.empty: results['result'] = results.apply(determine_result, axis=1) for i, row in results.iterrows(): update_q = """UPDATE picks SET result = '{0}' WHERE id = {1}""".format( row['result'], row['id']) for x in range(0, 2): while True: try: update(prod_str, update_q) except DatabaseError: continue break
def do_query(id): query = """ update feedback set votes = votes + 1 where id = {id} returning votes """.format(id=id, ) print(query) if os.getenv('DEV'): print("skipping db") return return db.update(query)
def predict(address): data[0] = normalizer.open_image(address) prediction = model.predict(data) bad = str(min(prediction[0]) == prediction[0][1] and min(prediction[0]) > 0.2).lower() occupancy = (100 * (prediction[0][0] * 0 + prediction[0][1] * 0.5 + prediction[0][2] * 1)) clarity = 1 - min(prediction[0]) if type(address) == str: filename = address else: filename = address.filename json = {"File": filename, "Relative_occupancy": occupancy, "Signal_clarity": clarity, "Bad_signal": bad} db.update(json) return json
def updateidc(): if not session: return redirect('/login/') if request.method == 'GET': info = {k: v[0] for k, v in dict(request.args).items()} res = getone('idc', filed1, info) if res['code'] == 0: return json.dumps(res['msg']) return json.dumps(res) info = {k: v[0] for k, v in dict(request.form).items()} res = update('idc', filed1, info) return json.dumps(res)
def update1(): filed = ['id', 'username', 'name', 'phone', 'mail'] if not session: return redirect('/login/') if request.method == 'POST': data = {k: v[0] for k, v in dict(request.form).items()} result = update('user', filed, data) if result['code'] == 0: return json.dumps(result) else: return json.dumps(result) return json.dumps(result)
def run(self): logger.info("start task...") self.loginCfg() if True == self.sendWeibo(): logger.info("send ok...") db.update(self.md5, 1) #while not self.stopped.wait(TIME_SLOG): counter = 0 err_counter = 0 cfg = 1 while not self.stopped.wait(self.frequence(cfg)): if counter % 100 == 0: logger.info('success:%d, err:%d' % (counter, err_counter)) if True == self.sendWeibo(): logger.info("send ok, counter:%s" % (counter)) db.update(self.md5, 1) #success published counter = counter + 1 cfg = 0 continue db.update(self.md5, 2) #error published cfg = 1 err_counter = err_counter + 1 logger.info("repeat cause false, err counter: %d" % err_counter) if err_counter > 10: logger.info("try to relogin cause error") self.loginCfg() time.sleep(20) logger.info("end task...")
def update_contact(id): status = False if request.method == 'PUT': if request.form['name'] and request.form['number']: name = request.form['name'] number = request.form['number'] if db.update(id, name, number): status = True return jsonify({"status": status})
def save(self): fields = [] params = [] args = [] for k, v in self.__mappings__.iteritems(): fields.append(v.name) params.append('?') args.append(getattr(self, k, None)) sql = 'insert into %s(%s) values(%s)' % (self.__table__, ','.join(fields), ','.join(params)) print sql print 'args: %s' % ','.join(args) db.create_engine('root', 'root', 'dbwl') return db.update(sql, *args)
def update(id, fields): attrs = ['username', 'password', 'bio'] nonnull = [attr for attr in attrs if fields[attr] is not None] if 'password' in attrs: fields['password'] = bcrypt.hashpw( fields['password'].encode('utf-8)'), bcrypt.gensalt(14) ) return update(table='users', columns=[attr for attr in nonnull], values=[quote_string(fields[attr]) for attr in nonnull], condition="user_id=%d" % id)
def on_post(self, req, resp): #srcId = src file ID #dirId = dir ID result = {'result': 'success'} body = json.loads(req.bounded_stream.read()) srcPath = db.get_path(body['srcId']) dirPath = db.get_path(body['dstId']) fileName = body['fileName'] dstPath = os.path.join(dirPath, fileName) if (srcPath == -1 or dirPath == -1): result['result'] = "failed" return try: os.rename(srcPath, dstPath) db.update(srcId, dstPath) except: result['result'] = "failed" resp.media = result
def comment(): new_comment = request.form.get('new_comment') article_id = request.args.get('articleId') username = session.get('username') sql1 = "select user_id from t_user where username=%s" user_id = db.query(sql1, (username)) sql = "insert into t_comment(content, user_id, article_id) value(%s, %s, %s)" row = db.update(sql, (new_comment, user_id['user_id'], article_id)) if row > 0: return 'ok' else: return 'notok'
def update(self): """ 通过的db对象的update接口执行SQL SQL: update `user` set `passwd`=%s,`last_modified`=%s,`name`=%s where id=%s, ARGS: (u'******', 1441878476.202391, u'Michael', 10190 """ self.pre_update and self.pre_update() L = [] args = [] for k, v in self.__mappings__.iteritems(): if v.updatable: if hasattr(self, k): arg = getattr(self, k) else: arg = v.default setattr(self, k, arg) L.append('`%s`=?' % k) args.append(arg) pk = self.__primary_key__.name args.append(getattr(self, pk)) db.update('update `%s` set %s where %s=?' % (self.__table__, ','.join(L), pk), *args) return self
def CloseEditor(self, evt=None): listmix.TextEditMixin.CloseEditor(self, evt) item = self.GetItem(self.curRow, self.curCol) newValue = item.GetText() oldValue = self.oldvalue if self.curCol == 5: try: newValue = int(newValue) except ValueError: dial = wx.MessageDialog(self, '填写的必须是数字!', '温馨提示', wx.OK) dial.ShowModal() dial.Destroy() item.SetText(str(oldValue)) self.SetItem(item) self.RefreshItem(self.curRow) return if str(newValue).strip() != str(oldValue).strip(): # 修改成功 msg = '您将' + self.columns_labels[self.curCol] + '由[' + str( oldValue) + ']修改为[' + str(newValue) + '],确定要修改吗?' dlg = wx.MessageDialog(self, msg, u"温馨提示", wx.YES_NO | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: stockId = item.GetData() if self.curCol == 5: sql = 'update stock set goods_num = ? where id = ? ' elif self.curCol == 8: sql = 'update stock set op_person = ? where id = ? ' elif self.curCol == 9: sql = 'update stock set op_area = ? where id = ? ' params = (newValue, stockId) db.update(sql, params) else: item.SetText(str(oldValue)) self.SetItem(item) self.RefreshItem(self.curRow) dlg.Destroy()
def play_the_song(self, play): self.kodi.VideoLibrary.Scan() result = self.kodi.Player.Open( item={"file": str(db.path() + play['title'] + ".mp4")}) self.kodi.GUI.ShowNotification(title=play['title'], message="Now Playing", displaytime=20000) if 'error' in result: if play['error'] >= 20: db.update(play['youtube_id'], 'error', 0) db.update(play['youtube_id'], 'status', 'error') self.kodi.VideoLibrary.Scan() db.update(play['youtube_id'], 'error', play['error'] + 1) else: db.set_to_done() db.update(play['youtube_id'], 'status', 'playing')
def updatepassword(): if not session: return redirect('/login/') info = {k: v[0] for k, v in dict(request.form).items()} users = getone('user', filed, session) if info['oldpasswd'] == users['msg']['password']: file = ['id', 'password'] data = {} data['password'] = info['newpasswd'] data['id'] = session['id'] result = update('user', file, data) return json.dumps(result) else: result = {'errmsg': 'password is error'} return json.dumps(result)
def setTag(self,event): tag=self.tags.setTagEn.get() curTag=db.select('select tags from books where id like ?',self._curID)[0]['tags'] curTL=set(curTag.lower().split()) curTag='' for item in curTL: curTag+=item+' ' #print tag #print 'searched:',curTag if not re.match('.*('+re.escape(tag)+').*',curTag,re.I): print 'Set tag...' db.update('UPDATE books SET tags=? WHERE id LIKE ?',curTag+' '+tag,self._curID) else: print '%s already exists' % tag db.update('UPDATE books SET tags=? WHERE id LIKE ?',curTag,self._curID) self.updateDB() self.updateCurBook() self.tags.showTags(self._curBook.tags) self._updateAllTags() self.sBar.sTagEn.update_lista(self._allTags)
def cabinet_update(): if request.method == 'GET': res = db.select('idc') idcs = [ dict((v, idc[k]) for k, v in enumerate(config.idc_fields)) for idc in res ] id = request.args.get('id') cabinet = db.select('cabinet', id=id)[0] cabinet = {v: cabinet[k] for k, v in enumerate(config.cabinet_fields)} return json.dumps({'code': 1, 'idcs': idcs, 'cabinet': cabinet}) data = {k: v[0] for k, v in dict(request.form).items()} conditions = ["%s='%s'" % (k, v) for k, v in data.items()] if db.update('cabinet', conditions, data['id']) > 0: return json.dumps({'code': 1, 'result': 'update completed!'})