def delete_file(fid): ''' delete file from database and disk ''' finfo = get_file_info(fid) if finfo['code'] != 0: return finfo if len(finfo['data']) == 0: return ee.IDERR(msg='file with this id not found') finfo = finfo['data'][0] _fn = finfo['filename'] _fpath = os.path.join(filedir, _fn) if os.path.exists(_fpath): try: os.remove(_fpath) except: return ee.UNKNOWN(msg='error occured when deleting file') # delete info in db sqlstr = 'delete from files where id={};'.format(str(fid)) try: conn = gv.dbpool.connection() cur = conn.cursor() cur.execute("SET NAMES UTF8mb4;") cur.execute(sqlstr.encode('utf-8', 'ignore')) conn.commit() cur.close() conn.close() return ee.NORMAL() except: estr = traceback.format_exc() gv.logger.error('database error!\n' + estr) return ee.DBERR() return ee.UNKNOWN()
def children_info_get(): vres = verify_auto(request, allows=['admin', 'staff', 'parent']) if not vres['code'] == 0: # verification failed vres['count'] = 0 vres['data'] = [] return vres _id = request.args.get('id') alias = request.args.get('alias') if _id is None and alias is None: return ee.PARAMERR(app=": id or alias is needed") if type(_id) == type('') and not str.isdigit(_id): return ee.PARAMERR(app=': id') if _id is None: uidfa = get_cid_by_alias(alias) if uidfa['code'] != 0: return uidfa if len(uidfa['data'])==0 or \ uidfa['data'][0]['id'] is None: return ee.IDERR(app=': alias not exists') _id = uidfa['data'][0]['id'] _sk = request.args.get('secret_key') if _sk is None: return ee.NOT_LOGGED() res = get_children_info(_id, _sk) return res
def update_status(stype, sid): ''' ''' tdef = copy.deepcopy(sttb[stype]) del tdef['flist'][get_index(tdef['flist'], 'id')] # get and check params for fd in tdef['flist']: if fd['fn'] == 'staff_id': # 直接获取当前登录id,不需取值 _sk = request.form.get('secret_key') fd['val'] = gv.logged[_sk]['id'] continue val = request.form.get(fd['fn']) if fd['type'] == 'int': # 检验是否是int if type(val) == type(''): if not str.isdigit(val): return ee.PARAMERR(app=': ' + fd['fn']) # child id 需要检验存在性 if fd['fn'] == 'child_id': if val is None: return ee.PARAMERR(app=': ' + fd['fn'] + ' is needed') _ex = child_exists(val) if _ex['code'] != 0: return _ex if not _ex['data'][0]['exists']: return ee.IDERR(app=': child id incorrect') elif fd['fn'] == 'time': if type(val) == type(''): try: # check datetime.datetime.strptime(val, '%Y-%m-%d %H:%M:%S') except: return ee.PARAMERR(app=': ' + fd['fn']) elif val is not None: return ee.PARAMERR(app=': ' + fd['fn']) fd['val'] = val sstr = funcs.build_set_str(tdef['flist']) if sstr is None: return ee.PARAMERR() if sstr == '': return ee.PARAMERR(app=': no values to update') sqlstr = 'update `{tbn}` set {sstr} where id={sid};'.format( tbn=tdef['tbn'], sstr=sstr, sid=str(sid)) # update try: conn = gv.dbpool.connection() cur = conn.cursor() cur.execute("SET NAMES UTF8mb4;") cur.execute(sqlstr.encode("utf-8", "ignore")) conn.commit() cur.close() conn.close() return ee.NORMAL() except: estr = traceback.format_exc() gv.logger.error('database error!\n' + estr) return ee.DBERR() return ee.UNKNOWN()
def file_get(): vres = verify_auto(request, allows=['admin', 'staff']) if not vres['code'] == 0: # verification failed vres['count'] = 0 vres['data'] = [] return vres fid = request.args.get('id') if not (type(fid) == type('') and str.isdigit(fid)): return ee.PARAMERR(app=": id") finfo = get_file_info(fid) if finfo['code'] != 0: return finfo if len(finfo['data']) == 0: return ee.IDERR(msg='file id is incorrect') fullfilename = os.path.join(filedir, finfo['data'][0]['filename']) if not os.path.exists(fullfilename): return ee.IDERR('file not found') # 普通下载 # response = make_response(send_from_directory(filepath, filename, as_attachment=True)) # response.headers["Content-Disposition"] = "attachment; filename={}".format(filepath.encode().decode('latin-1')) # return send_from_directory(filepath, filename, as_attachment=True) # 流式读取 _block_size = 8 * 1024 * 1024 def send_file(): store_path = fullfilename with open(store_path, 'rb') as targetfile: while 1: data = targetfile.read(_block_size) if not data: break yield data response = Response(send_file(), content_type='application/octet-stream') # 设置文件名,url编码以适应中文 _fn = quote(finfo['data'][0]['originfn']) response.headers[ 'Content-disposition'] = "attachment; filename*=utf-8''{}".format(_fn) #response.headers["Content-disposition"] = 'attachment; filename=%s' % finfo['data'][0]['originfn'] return response
def send_vcode(): # test username, email, time username = request.args.get('username') email = request.args.get('email') if username is None or username == '': return ee.PARAMERR(app=': username') if email is None or email == '': return ee.PARAMERR(app=': email') if username in gv.vcode: _t = int(time.time()) if _t - gv.vcode[username]['time'] < 25: return ee.FREQ(app=': less than 25s') _user = get_id_by_username(username) if _user['code'] != 0: return ee.DBERR(': chk un') if len(_user['data']) == 0: return ee.IDERR(app=': username is incorrect') if _user['data'][0]['email'] != email: return ee.IDERR(app=': email is incorrect') gv.vcode[username] = { 'email': email, 'id': _user['data'][0]['id'], 'time': int(time.time()) } try: vcode = random.randint(0, 99999999) vcode = str(vcode).zfill(8) gv.vcode[username]['vcode'] = vcode _html = render_template('mail_vcode.html', vcode=vcode) app = current_app._get_current_object() thr = Thread(target=send_email, args=[app, username, _html]) thr.start() except: emsg = 'Error when sending email\n' + traceback.format_exc() gv.logger.error(emsg) return ee.UNKNOWN() return ee.NORMAL()
def _chk_param_n_gsbc(): ''' check param and do get_status_by_cid ''' # get and check params startt = request.args.get('startt') endt = request.args.get('endt') cid = request.args.get('id') alias = request.args.get('alias') if cid is None and alias is None: return ee.PARAMERR(app=': id or alias is needed') if type(cid) == type('') and not str.isdigit(cid): return ee.PARAMERR(app=': id') if cid is None: uidfa = get_cid_by_alias(alias) if uidfa['code'] != 0: return uidfa if len(uidfa['data']) == 0: return ee.IDERR(app=': alias not exists') cid = uidfa['data'][0]['id'] _sk = request.args.get('secret_key') if _sk is None or _sk not in gv.logged: return ee.NOT_LOGGED() return get_status_by_cid(cid, startt, endt, _sk)
def file_post(): vres = verify_auto(request, allows=['admin', 'staff']) if not vres['code'] == 0: # verification failed vres['count'] = 0 vres['data'] = [] return vres cid = request.form.get('child_id') if type(cid) == type('') and not str.isdigit(cid): return ee.PARAMERR(app=": child_id") if cid is None: _alias = request.form.get('alias') if _alias is None: return ee.PARAMERR(app=': child_id or alias is needed') _cidfa = get_cid_by_alias(_alias) if _cidfa['code'] != 0: return _cidfa if len(_cidfa['data']) > 0: cid = _cidfa['data'][0]['id'] if cid is None: return ee.IDERR(app=': incorrect id or alias') file = request.files['file'] if file is None: return ee.PARAMERR(': no file') originfn = file.filename if originfn is None or len(originfn) < 1: return ee.PARAMERR(app=": filename error") filename = funcs.get_md5(originfn + str(cid)) filepath = os.path.join(filedir, filename) if os.path.exists(filepath): return ee.PARAMERR(': file already exists') funcs.mkdir(filedir) file.save(filepath) res = insert_file_info(cid, filename, originfn) return res
def insert_child(): """ insert child info into database """ uid = funcs.get_random_int64() tbn = 'child' alias = request.form.get('alias') flist = [{ 'fn': 'id', 'type': 'int', 'val': uid }, { 'fn': 'name', 'type': 'b64str', 'val': request.form.get('name') }, { 'fn': 'name_chs', 'type': 'b64str', 'val': request.form.get('name_chs') }, { 'fn': 'alias', 'type': 'b64str', 'val': alias }, { 'fn': 'gender', 'type': 'str', 'val': request.form.get('gender') }, { 'fn': 'religion', 'type': 'b64str', 'val': request.form.get('religion') }, { 'fn': 'born_day', 'type': 'str', 'val': request.form.get('born_day') }, { 'fn': 'birth_cert_no', 'type': 'str', 'val': request.form.get('birth_cert_no') }, { 'fn': 'place_birth', 'type': 'b64str', 'val': request.form.get('place_birth') }, { 'fn': 'address', 'type': 'b64str', 'val': request.form.get('address') }, { 'fn': 'date_in', 'type': 'str', 'val': request.form.get('date_in') }, { 'fn': 'tel', 'type': 'str', 'val': request.form.get('tel') }, { 'fn': 'email', 'type': 'b64str', 'val': request.form.get('email') }, { 'fn': 'caregiver', 'type': 'int', 'val': request.form.get('caregiver') }, { 'fn': 'lang', 'type': 'b64str', 'val': request.form.get('lang') }, { 'fn': 'group_id', 'type': 'int', 'val': request.form.get('group_id') }] # check parameters # gender gi = get_index(flist, 'gender') if type(flist[gi]['val']) == type(''): if flist[gi]['val'].lower() == 'female': flist[gi]['val'] = 'f' elif flist[gi]['val'].lower() == 'male': flist[gi]['val'] = 'm' elif flist[gi]['val'].lower() == 'boy': flist[gi]['val'] = 'm' elif flist[gi]['val'].lower() == 'girl': flist[gi]['val'] = 'f' elif flist[gi]['val'].lower() == 'man': flist[gi]['val'] = 'm' # alias if alias is None: return ee.PARAMERR(app=': alias is needed') _cidfa = get_cid_by_alias(alias) if _cidfa['code'] != 0: return _cidfa if len(_cidfa['data']) > 0: return ee.UN_EXISTS(app=': alias already exists') # born_day bdi = get_index(flist, 'born_day') if type(flist[bdi]['val']) == type(''): try: # check bd = datetime.datetime.strptime(flist[bdi]['val'], '%Y-%m-%d').date() # get group id today = datetime.date.today() tdd = (today - bd).days tdm = tdd // 30 if tdd % 30 != 0: tdm += 1 for g in gv.groups: if tdm >= g['smon'] and tdm <= g['emon']: flist[-1]['val'] = g['id'] except: return ee.PARAMERR(app=': born_day') # date_in di = get_index(flist, 'date_in') if flist[di]['val'] is None or flist[di]['val'] == '': flist[di]['val'] = time.strftime('%Y-%m-%d', time.localtime(time.time())) else: try: time.strptime(flist[di]['val'], '%Y-%m-%d') except: return ee.PARAMERR(app='date_in') # parent cid = None if flist[-3]['val'] is not None: _pun = flist[-3]['val'] pid = get_id_by_username(_pun) if pid['code'] != 0: return pid if pid['count'] == 0 or len(pid['data']) == 0: return ee.IDERR(msg='username of caregiver not exists') cid = int(pid['data'][0]['id']) flist[-3]['val'] = cid try: conn = gv.dbpool.connection() cur = conn.cursor() cur.execute("SET NAMES UTF8mb4;") res = funcs.insert_if_not_exists(cur, tbn, flist, chkfn=None, logger=gv.logger) if res['code'] != 0: cur.close() conn.close() return res # add to parent if cid is not None: s1 = 'select child_ids from parent where id={0};'.format(str(cid)) cur.execute(s1.encode("utf-8", "ignore")) cidsres = cur.fetchall() cids = [] if cidsres is not None and len(cidsres) > 0: if cidsres[0][0] is not None and len(cidsres[0][0]) > 0: _tmp = cidsres[0][0].split(',') for _t in _tmp: if len(_t) > 0: cids.append(str(_t)) cids.append(str(uid)) newcids = ','.join(cids) s2 = "update parent set child_ids='{0}' where id={1};".format( newcids, str(cid)) cur.execute(s2.encode("utf-8", "ignore")) conn.commit() cur.close() conn.close() return ee.NORMAL() except: estr = traceback.format_exc() gv.logger.error('database error!\n' + estr) return ee.DBERR() return ee.UNKNOWN()
def update_child(): """ update child info in database """ uid = request.form.get('id') alias = request.form.get('alias') if uid is None and alias is None: return ee.PARAMERR(app=": id or alias is needed") if type(uid) == type('') and not str.isdigit(uid): return ee.PARAMERR(app=': id') uidfa = None if alias is not None: uidfa = get_cid_by_alias(alias) if uid is not None and alias is not None: # 检查唯一性 if uidfa['code'] != 0: return uidfa if len(uidfa['data'])>0 and \ str(uidfa['data'][0]['id'])!=str(uid): return ee.UN_EXISTS(app=': alias already exists') if uid is None: if uidfa['code'] != 0: return uidfa if len(uidfa['data']) == 0: return ee.IDERR(app=': alias not exists') uid = uidfa['data'][0]['id'] tbn = 'child' flist = [{ 'fn': 'name', 'type': 'b64str', 'val': request.form.get('name') }, { 'fn': 'name_chs', 'type': 'b64str', 'val': request.form.get('name_chs') }, { 'fn': 'alias', 'type': 'b64str', 'val': alias }, { 'fn': 'gender', 'type': 'str', 'val': request.form.get('gender') }, { 'fn': 'religion', 'type': 'b64str', 'val': request.form.get('religion') }, { 'fn': 'born_day', 'type': 'str', 'val': request.form.get('born_day') }, { 'fn': 'birth_cert_no', 'type': 'str', 'val': request.form.get('birth_cert_no') }, { 'fn': 'place_birth', 'type': 'b64str', 'val': request.form.get('place_birth') }, { 'fn': 'address', 'type': 'b64str', 'val': request.form.get('address') }, { 'fn': 'date_in', 'type': 'str', 'val': request.form.get('date_in') }, { 'fn': 'tel', 'type': 'str', 'val': request.form.get('tel') }, { 'fn': 'email', 'type': 'b64str', 'val': request.form.get('email') }, { 'fn': 'caregiver', 'type': 'int', 'val': request.form.get('caregiver') }, { 'fn': 'lang', 'type': 'b64str', 'val': request.form.get('lang') }, { 'fn': 'group_id', 'type': 'int', 'val': request.form.get('group_id') }] # check parameters # gender gi = get_index(flist, 'gender') if type(flist[gi]['val']) == type(''): if flist[gi]['val'].lower() == 'female': flist[gi]['val'] = 'f' elif flist[gi]['val'].lower() == 'male': flist[gi]['val'] = 'm' elif flist[gi]['val'].lower() == 'boy': flist[gi]['val'] = 'm' elif flist[gi]['val'].lower() == 'girl': flist[gi]['val'] = 'f' elif flist[gi]['val'].lower() == 'man': flist[gi]['val'] = 'm' # born_day bdi = get_index(flist, 'born_day') if type(flist[bdi]['val']) == type(''): try: # check bd = datetime.datetime.strptime(flist[bdi]['val'], '%Y-%m-%d').date() # get group id today = datetime.date.today() tdd = (today - bd).days tdm = tdd // 30 if tdd % 30 != 0: tdm += 1 for g in gv.groups: if tdm >= g['smon'] and tdm <= g['emon']: flist[-1]['val'] = g['id'] except: return ee.PARAMERR(app='born_day') # date_in di = get_index(flist, 'date_in') if flist[di]['val'] is None or flist[di]['val'] == '': flist[di]['val'] = time.strftime('%Y-%m-%d', time.localtime(time.time())) else: try: time.strptime(flist[di]['val'], '%Y-%m-%d') except: return ee.PARAMERR(app='date_in') # parent cid = None if flist[-3]['val'] is not None: _pun = flist[-3]['val'] pid = get_id_by_username(_pun) if pid['code'] != 0: return pid if pid['count'] == 0 or len(pid['data']) == 0: return ee.IDERR(msg='username of caregiver not exists') cid = int(pid['data'][0]['id']) flist[-3]['val'] = cid try: conn = gv.dbpool.connection() cur = conn.cursor() cur.execute("SET NAMES UTF8mb4;") # get origin cid cidorg = None if cid is not None: sqlstr = 'select caregiver from child where id={0};'.format( str(uid)) cur.execute(sqlstr.encode("utf-8", "ignore")) cidorg = cur.fetchall() if cidorg is None or len(cidorg) == 0: cur.close() conn.close() return ee.IDERR(msg='child id is incorrect') cidorg = cidorg[0][0] vstr = funcs.build_set_str(flist) if vstr is None: cur.close() conn.close() return ee.PARAMERR() sqlstr = 'update `{tbn}` set {sstr} where id={cid};'.format(tbn=tbn, sstr=vstr, cid=uid) cur.execute(sqlstr.encode("utf-8", "ignore")) # add to parent if cid is not None and str(cidorg) != str(cid): # 抹除旧的 s1 = 'select child_ids from parent where id={0};'.format( str(cidorg)) cur.execute(s1.encode("utf-8", "ignore")) cidsres = cur.fetchall() if cidsres is not None and len(cidsres) > 0: if cidsres[0][0] is not None and len(cidsres[0][0]) > 0: newcids = cidsres[0][0].replace(str(uid), '').replace(',,', ',') s2 = "update parent set child_ids='{0}' where id={1};".format( newcids, str(cidorg)) cur.execute(s2.encode("utf-8", "ignore")) # 设置新的 s1 = 'select child_ids from parent where id={0};'.format(str(cid)) cur.execute(s1.encode("utf-8", "ignore")) cidsres = cur.fetchall() cids = [] if cidsres is not None and len(cidsres) > 0: if cidsres[0][0] is not None and len(cidsres[0][0]) > 0: _tmp = cidsres[0][0].split(',') for _t in _tmp: if len(_t) > 0: cids.append(str(_t)) cids.append(str(uid)) newcids = ','.join(cids) s2 = "update parent set child_ids='{0}' where id={1};".format( newcids, str(cid)) cur.execute(s2.encode("utf-8", "ignore")) conn.commit() cur.close() conn.close() return ee.NORMAL() except: estr = traceback.format_exc() gv.logger.error('database error!\n' + estr) return ee.DBERR() return ee.UNKNOWN()
def insert_status(stype): ''' ''' tdef = copy.deepcopy(sttb[stype]) del tdef['flist'][get_index(tdef['flist'], 'id')] # get and check params for fd in tdef['flist']: if fd['fn'] == 'staff_id': # 直接获取当前登录id,不需取值 _sk = request.form.get('secret_key') fd['val'] = gv.logged[_sk]['id'] continue val = request.form.get(fd['fn']) if fd['type'] == 'int': if type(val) == type(''): if not str.isdigit(val): return ee.PARAMERR(app=': ' + fd['fn']) if fd['fn'] == 'child_id': if val is None: # check alias _alias = request.form.get('alias') if _alias is None: return ee.PARAMERR(app=': child_id or alias is needed') _cid = get_cid_by_alias(_alias) if _cid['code'] != 0: return _cid if len(_cid['data']) == 0: return ee.IDERR(app=': alias not exists') val = _cid['data'][0]['id'] else: _ex = child_exists(val) if _ex['code'] != 0: return _ex if not _ex['data'][0]['exists']: return ee.IDERR(app=': child id incorrect') elif fd['fn'] == 'time': if type(val) == type(''): try: # check datetime.datetime.strptime(val, '%Y-%m-%d %H:%M:%S') except: return ee.PARAMERR(app=': ' + fd['fn']) elif val is not None: return ee.PARAMERR(app=': ' + fd['fn']) else: val = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) fd['val'] = val # insert try: conn = gv.dbpool.connection() cur = conn.cursor() cur.execute("SET NAMES UTF8mb4;") res = funcs.insert_if_not_exists(cur, tdef['tbn'], tdef['flist'], chkfn=None, logger=gv.logger) conn.commit() cur.close() conn.close() return res except: estr = traceback.format_exc() gv.logger.error('database error!\n' + estr) return ee.DBERR() return ee.UNKNOWN()