def register(): """ 注册 """ oa_account = request.json.get('account') password = request.json.get('password') name = request.json.get('name') filters = {User.oa_account == oa_account} user_data = User().getOne(filters) if user_data is None: create_time = int(time.time()) user = User( oa_account=oa_account, password=User.set_password(password), name=name, status=1, created_time=create_time, role_id='auditor', ) status = user.add(user) if status: return BaseController().successData(result={'name': name}, msg='注册成功') return BaseController().error('注册失败') # else: # user = User.get(user_data['id']) # create_time = int(time.time()) # User().update(user, oa_account, User.set_password(oa_password), company, 1, create_time, 'admin', '管理员', # create_time, 'default', 1) return BaseController().error('账号已注册')
def logout(): token = request.json.get('token') updated_at = int(time.time()) if not token: return BaseController().error(msg='token为空') user = User().getOne(filters={User.remember_token == token}) if not user: return BaseController().error(msg='查询失败') User.update(user['id'], remember_token='') return BaseController().successData(msg='登出成功')
def post(self): # get the post data post_data = request.get_json() if post_data: # check if user already exists user = User.query.filter_by(email=post_data.get('email')).first() if not user: try: user = User(name=post_data.get('name'), email=post_data.get('email'), password=post_data.get('password'), username=post_data.get('username')) # insert to database db.session.add(user) db.session.commit() #genarate auth token auth_token = user.encodeAuthToken(user.id) if not (type(auth_token) is str): if hasattr(auth_token, 'decode'): auth_token = auth_token.decode() responseObject = { 'status': 'success', 'message': 'Successfully registered', 'access_token': str(auth_token) } return make_response(jsonify(responseObject)), 200 except Exception as e: print(e) responseObject = { 'status': 'fail', 'message': 'Some error occurred. Please try again.' } # 'access_token': auth_token.decode() return make_response(jsonify(responseObject)), 401 else: responseObject = { 'status': 'fail', 'message': 'User already exists. Please Log in.' } return make_response(jsonify(responseObject)) else: responseObject = { 'status': 'fail', 'message': 'Some error occurred. Please try again.' } # 'access_token': auth_token.decode() return make_response(jsonify(responseObject)), 401
def get_users(): res = [] companys1 = User().getAll(User, {User.company == '石桥子风电场'}, field=('name', 'company')) companys2 = User().getAll(User, {User.company != '石桥子风电场' or User.company is None}, field=('name', 'company')) if companys1: res.append({ 'label': '石桥子风电场', 'data': companys1 }) if companys2: res.append({ 'label': '其他', 'data': companys2 }) return BaseController().successData(result=res, msg='读取成功')
def get(self, id=None): # get the auth token auth_header = request.headers.get('Authorization') if auth_header: # auth_token = auth_header.split(" ")[1] auth_token = auth_header else: auth_token = '' if auth_token: resp = User.decodeAuthToken(auth_token) if not isinstance(resp, str): user = User.query.filter_by(id=resp).first() responseObject = { 'status': 'success', 'user': { 'user_id': user.id, 'email': user.email } } return make_response(jsonify(responseObject)), 200 responseObject = {'status': 'fail', 'message': resp} return make_response(jsonify(responseObject)), 401 else: responseObject = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return make_response(jsonify(responseObject)), 401
def findOrRegisterUser(userId,name): user = User.query.filter(User.userId == userId).first() if user == None: # Create a new Entry in the database for the user user = User(userId=userId, name=name, authToken='', tokenExpiryDate=datetime.min) db_session.add(user) db_session.commit() return user
def getInfo(): token = request.args.get("token") if not token: return BaseController().error(msg='token为空') filters = {User.remember_token == token} field = ('id', 'name', 'oa_account', 'status', 'last_login_time', 'last_login_ip', 'created_time', 'deleted', 'role_id') user_info = User().getOne(filters=filters, field=field) if not user_info: return BaseController().error(msg='查询失败') return BaseController().successData(result=user_info, msg='获取成功')
def search_users(): data = request.get_json() or '' res = set() if data: res_list = User().getList(User, {User.name.contains(data['value'])}, field=('name',))['list'] users_name = [x['name'] for x in res_list] if len(users_name) == 0: res.add(data['value']) res.update(users_name) else: res_list = Gzp().getList({}, order=Gzp.gzp_id.desc(), field=('manage_person_id', 'members'), offset=0, limit=5)[ 'list'] for item in res_list: manager_person_name = User().getOne(filters={User.id == item['manage_person_id']}, field=('name',))['name'] members_name = [User().getOne(filters={User.id == x['id']}, field=('name',))['name'] for x in item['members']] res.add(manager_person_name) res.update(members_name) return BaseController().successData(result=list(res))
def addUser(): name = request.json.get('name') oa_account = request.json.get('oa_account') company = request.json.get('company') new_user = User() new_user.name = name new_user.oa_account = oa_account new_user.company = company new_user.status = 0 User().add(new_user) return BaseController().successData(msg='用户增加成功')
def register(request): username = GetRequestJsonData(request, 'username', None) email = GetRequestJsonData(request, 'email', None) password = GetRequestJsonData(request, 'password', None) repassword = GetRequestJsonData(request, 'repassword', None) print(username, email, password, repassword) if not all([username, email, password, repassword]): return ReturnCode.paramete_error, '邮箱或用户名密码输入不正确', '' if User.query.filter(User.email == email).first(): return ReturnCode.paramete_error, '该邮箱已被注册', '' if User.query.filter(User.username == username).first(): return ReturnCode.paramete_error, '该用户名已被注册', '' if password != password: return ReturnCode.paramete_error, '两次密码输入不一致', '' adduser = User( reg_time = datetime.now(), password = generate_password_hash(str(password)), email = str(email), username = str(username), token = '', head = 'default.png', userstatus = 0 ) db.session.add(adduser) try: db.session.commit() return ReturnCode.ok, '注册成功', '' except: db.session().rollback() return ReturnCode.server_error, '系统出错', ''
def testSetPassword(self): user = User() user.password = "******" self.assertTrue(user.passwordHash is not None)
def testGetPassword(self): # 试图get会抛异常 user = User() user.password = "******" with self.assertRaises(AttributeError): user.password
def testPasswordSaltsAreRandom(self): userA = User(password="******") userB = User(password="******") self.assertNotEqual(userA.passwordHash, userB.passwordHash)
def testConfirmToken(self): user = User(password="******") token = user.generateConfirmationToken() self.assertTrue(user.confirm(token)) self.assertFalse(user.confirm("error"))
def gzp_syn(): res = [] path = DESK_PATH + r'\5OA系统风机工作票' for year_folder in os.listdir(path): if re.match('\d+年$', year_folder): for month_folder in os.listdir(path + '\\' + year_folder): if re.match('\d+月$', month_folder): for gzp in os.listdir(path + '\\' + year_folder + '\\' + month_folder): if re.match(r'^(风机检修工作票)\S+(\.xls)$', gzp): data_gzp = pd.read_excel( path + '\\' + year_folder + '\\' + month_folder + '\\' + gzp) # 读取 # if not Gzp.query.filter_by(gzp_id=data_gzp.loc[1].values[13]).first(): if not Gzp.get(data_gzp.loc[1].values[13]): gzp = Gzp() else: gzp = Gzp.get(data_gzp.loc[1].values[13]) gzp.firm = data_gzp.loc[1].values[1] # 以下开始对各项数据进行读取 for index, row in data_gzp.fillna('').iterrows(): for col_num in range(0, 19): if row.values[col_num] != '' and isinstance( row.values[col_num], str): # 匹配编号 if re.match(r'\S{4}-\S{2}-\S{2}-\d{9}', row.values[col_num]): gzp.gzp_id = re.match( r'\S{4}-\S{2}-\S{2}-\d{9}', row.values[col_num]).group() # 匹配工作负责人 if row.values[ col_num] == '1、工作负责人(监护人)': gzp.manage_person = User( ).getByName(row.values[col_num + 4]) # 匹配工作班成员 if row.values[ col_num] == '2、工作班成员(不包括工作负责人)': members = re.split( "\W+", data_gzp.loc[ index + 1].values[0].strip()) members_temp = [] for member in members: members_temp.append( User().getByName(member)) gzp.members = members_temp # 匹配故障 if row.values[col_num] == '3、工作任务': if isinstance( data_gzp.loc[index + 1].values[5], str): if re.match( r'(SC\d+_\d+_\d+)\\?(\w+)?', data_gzp.loc[ index + 1].values[5]): gzp.error_code = re.match( r'(SC\d+_\d+_\d+)\\?(\w+)?', data_gzp.loc[index + 1]. values[5]).group(1) if re.match( r'(SC\d+_\d+_\d+)\\?(\w+)?', data_gzp.loc[ index + 1].values[5] ).group(2): gzp.error_content = re.match( r'(SC\d+_\d+_\d+)\\?(\w+)?', data_gzp.loc[index + 1]. values[5]).group(2) else: gzp.error_content = re.match( r'(处理)?(\w+)', data_gzp.loc[ index + 3].values[10] ).group(2) # 匹配风机 gzp_wts_id = list( map( lambda x: re.match( r'^(A)(\d+)$', x). group(2), re.findall( re.compile(r'A\d+'), data_gzp.loc[ index + 3].values[0]))) gzp.wts = list( map(lambda x: WT.get(int(x)), gzp_wts_id)) # wt放在最后 gzp.postion = data_gzp.loc[ index + 3].values[5] gzp.task = data_gzp.loc[ index + 3].values[10] # 匹配时间 if row.values[col_num] == '5、计划工作时间': try: gzp.pstart_time = datetime.datetime( data_gzp.loc[index + 1].values[2], data_gzp.loc[index + 1].values[4], data_gzp.loc[index + 1].values[6], data_gzp.loc[index + 1].values[8], data_gzp.loc[index + 1].values[10]) now = datetime.datetime.now() zeroToday = now - datetime.timedelta( hours=now.hour, minutes=now.minute, seconds=now.second, microseconds=now. microsecond) if gzp.pstart_time < zeroToday: gzp.is_end = 1 # 读取到非今日工作票记为已终结 if data_gzp.loc[ index + 2].values[8] != 24: gzp.pstop_time = datetime.datetime( data_gzp.loc[ index + 2].values[2], data_gzp.loc[ index + 2].values[4], data_gzp.loc[ index + 2].values[6], data_gzp.loc[ index + 2].values[8], data_gzp.loc[ index + 2].values[10]) else: gzp.pstop_time = datetime.datetime( data_gzp.loc[index + 2] .values[2], data_gzp. loc[index + 2].values[4], data_gzp.loc[index + 2] .values[6], 0, data_gzp.loc[index + 2] .values[10] ) + datetime.timedelta( days=1) except ValueError: res.append(gzp.gzp_id) print(gzp.gzp_id) Gzp().add(gzp) return res
def get_gzps_today(): """ 读取今日工作票 """ # test_date = datetime.date(2020,1,1) gzps = Gzp().getList({Gzp.pstart_time >= datetime.date.today()}, Gzp.pstart_time.desc(), ('gzp_id', 'manager', 'date', 'mgp', 'agp')) # gzps = Gzp().getGzpList(0, 10) gzps_list = gzps['list'] data = [] for item in gzps_list: members = '' for member in item['members']: members = members + member['name'] + ',' members = members[:-1] wts = '' wtms = list() index = 0 for wt_id in item['wts']: wtms.append({}) if len(list(filter(lambda x: x['wt_id'] == wt_id, item['wtms']))): wtm = list(filter(lambda x: x['wt_id'] == wt_id, item['wtms']))[0] wtms[index] = { 'wt_id': wt_id, 'stop_time': datetime.datetime.strftime(wtm['stop_time'], '%Y-%m-%d %H:%M'), 'start_time': '' if not wtm['start_time'] else datetime.datetime.strftime( wtm['start_time'], '%Y-%m-%d %H:%M'), 'lost_power': wtm['lost_power'], 'time': wtm['time'] } else: wtms[index] = { 'wt_id': wt_id, 'stop_time': '', 'start_time': '', 'lost_power': '', 'time': '' } wts = wts + 'A' + str(wt_id) + ',' index = index + 1 wts = wts[:-1] x = { 'id': item['gzp_id'], 'wt_id': wts, 'manager': User().get(item['manage_person_id']).name, 'task': item['task'], 'members': members, 'pstart_time': datetime.datetime.strftime(item['pstart_time'], '%Y-%m-%d %H:%M'), 'pstop_time': datetime.datetime.strftime(item['pstop_time'], '%Y-%m-%d %H:%M'), 'wtms': wtms, 'is_end': item['is_end'], } if item['error_code']: x['error_code'] = item['error_code'] data.append(x) # index = index + 1 print(data) return BaseController().successData(result=data, msg='工作票读取成功')
def testUserPermissions(self): user = User(email="*****@*****.**", username="******", password="******") self.assertTrue(user.can(Permission.FOLLOW)) self.assertFalse(user.can(Permission.ADMINISTER))
def testAdministratorPermissions(self): administrator = User(email="*****@*****.**", username="******", password="******") self.assertTrue(administrator.can(Permission.FOLLOW)) self.assertTrue(administrator.can(Permission.ADMINISTER))
def testVerifyPassword(self): user = User() user.password = "******" self.assertTrue(user.verifyPassword("abcabc"))
def testIsAdministrator(self): administrator = User(email="*****@*****.**", username="******", password="******") self.assertTrue(administrator.isAdministrator())