def post(self): body_json = request.json utoken = body_json.get('utoken', None) user_info = verify_json_web_token(utoken) if not user_info: return jsonify({"message": "登录已过期!"}), 400 if user_info['role_num'] > 2: return jsonify({"message": "没有权限进行这个操作!"}), 400 module_name = body_json.get('module_name', None) parent_id = body_json.get('parent_id', None) if not module_name: return jsonify({"message": "参数错误! NOT FOUND NAME."}), 400 db_connection = MySQLConnection() cursor = db_connection.get_cursor() try: if not parent_id: insert_statement = "INSERT INTO `info_module` (`name`) VALUES (%s);" cursor.execute(insert_statement, module_name) else: parent_id = int(parent_id) insert_statement = "INSERT INTO `info_module`(`name`,`parent_id`) VALUES (%s,%s);" cursor.execute(insert_statement, (module_name, parent_id)) new_mid = db_connection.insert_id() # 新加入的id update_statement = "UPDATE `info_module` SET `sort`=%s WHERE `id`=%s;" cursor.execute(update_statement, (new_mid, new_mid)) db_connection.commit() except Exception as e: db_connection.rollback() db_connection.close() return jsonify({"message": "添加失败{}".format(e)}), 400 else: db_connection.close() return jsonify({"message": "添加成功!"}), 201
def post(self): body_json = request.json try: variety_id = int(body_json.get('variety_id')) group_name = body_json.get('name') if not group_name: raise ValueError('group ERROR') utoken = body_json.get('utoken') except Exception as e: return jsonify({"message": "参数错误"}), 400 user_info = verify_json_web_token(utoken) if not user_info or user_info['role_num'] > enums.RESEARCH: return jsonify({"message": "登录已过期或不能操作"}) user_id = user_info['id'] db_connection = MySQLConnection() cursor = db_connection.get_cursor() # 查询用户权限 auth_statement = "SELECT `id` FROM `link_user_variety` " \ "WHERE `user_id`=%d AND `variety_id`=%d;" % (user_id, variety_id) cursor.execute(auth_statement) if not cursor.fetchone(): db_connection.close() return jsonify({"message": "没有权限,不能这样操作"}), 400 save_statement = "INSERT INTO `info_variety_trendgroup` " \ "(`name`,`variety_id`,`author_id`) " \ "VALUES (%s,%s,%s);" cursor.execute(save_statement, (group_name, variety_id, user_id)) new_id = db_connection.insert_id() update_sort_statement = "UPDATE `info_variety_trendgroup` SET `sort`=%d WHERE `id`=%d;" % ( new_id, new_id) cursor.execute(update_sort_statement) db_connection.commit() db_connection.close() return jsonify({"message": "添加组成功!"}), 201
def get(self, mid): if mid < 1: return jsonify({"message": "验证完毕!", "auth": 1}) utoken = request.json.get('utoken', None) user_info = verify_json_web_token(utoken) if not user_info: return jsonify({"message": "验证完毕!", "auth": 0}) db_connection = MySQLConnection() cursor = db_connection.get_cursor() # 查询模块等级 level_statement = "SELECT `id`,`level` FROM `info_module` WHERE `id`=%s;" cursor.execute(level_statement, mid) module_info = cursor.fetchone() if not module_info: db_connection.close() return jsonify({"message": "验证完毕!", "auth": 0}) if user_info['role_num'] <= enums.RESEARCH and user_info[ 'role_num'] <= mid: db_connection.close() return jsonify({"message": "验证完毕!", "auth": 1}) now = datetime.datetime.now() select_statement = "SELECT `id`,`user_id`,`module_id` " \ "FROM `link_user_module` " \ "WHERE `user_id`=%s AND `module_id`=%s AND `expire_time`>%s;" cursor.execute(select_statement, (user_info['id'], mid, now)) auth = 1 if cursor.fetchone() else 0 db_connection.close() return jsonify({"message": "验证完毕!", "auth": auth})
def post(self): body_json = request.json utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) if not user_info or user_info['role_num'] > enums.RESEARCH: return jsonify({"message":"登录过期或不能执行操作."}), 400 today = datetime.datetime.today() custom_time = body_json.get('custom_time', today) content = body_json.get('content') if not content: return jsonify({"message":"请输入内容"}), 400 db_connection = MySQLConnection() try: custom_time = datetime.datetime.strptime(custom_time, "%Y-%m-%d %H:%M:%S") author_id = int(user_info['id']) save_statement = "INSERT INTO `info_shortmessage` (`create_time`,`custom_time`,`content`,`author_id`) " \ "VALUES (%s,%s,%s,%s);" cursor = db_connection.get_cursor() cursor.execute(save_statement,(today, custom_time,content,author_id)) db_connection.commit() except Exception as e: db_connection.rollback() db_connection.close() current_app.logger.error("添加短信通错误:{}".format(e)), 400 return jsonify({'message':'添加错误:{}'.format(e)}) else: db_connection.close() return jsonify({"message":"添加成功!"}), 201
def post(self): body_json = request.json utoken = body_json.get('utoken', None) operate_user = verify_json_web_token(utoken) if not operate_user or operate_user['role_num'] > 2: return jsonify({'message': '登录过期或不能进行这个操作!'}), 400 current_id = body_json.get('c_id', None) target_id = body_json.get('t_id', None) try: current_id = int(current_id) target_id = int(target_id) except Exception as e: return jsonify({'message': '参数错误!'}), 400 db_connection = MySQLConnection() cursor = db_connection.get_cursor() query_statement = "SELECT `sort` FROM `info_module` WHERE `id`=%s;" cursor.execute(query_statement, current_id) current_sort = cursor.fetchone() cursor.execute(query_statement, target_id) target_sort = cursor.fetchone() if not all([current_sort, target_sort]): db_connection.close() return jsonify({'message': '要排序的模块不存在!'}), 400 current_sort = current_sort['sort'] target_sort = target_sort['sort'] update_statement = "UPDATE `info_module` SET `sort`=%s WHERE `id`=%s;" cursor.execute(update_statement, (target_sort, current_id)) cursor.execute(update_statement, (current_sort, target_id)) db_connection.commit() db_connection.close() return jsonify({'message': '排序成功!'})
def get(self): body_json = request.json utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) if not user_info: return jsonify({'message': '请登录后再操作..'}), 400 user_id = user_info['id'] variety_id = body_json.get('variety_id', None) machine_code = body_json.get('machine_code') client_info = get_client(machine_code) if not all([user_id, variety_id, client_info]): return jsonify({'message': '参数错误'}), 400 client_id = client_info['id'] db_connection = MySQLConnection() cursor = db_connection.get_cursor() select_statement = "SELECT * FROM `info_tablesource_configs` " \ "WHERE `variety_id`=%s AND `client_id`=%s AND `user_id`=%s;" cursor.execute(select_statement, (variety_id, client_id, user_id)) records = cursor.fetchall() configs = list() for item in records: new = dict() new['id'] = item['id'] new['update_time'] = item['update_time'].strftime( '%Y-%m-%d %H:%M:%S') new['variety_name'] = item['variety_name'] new['variety_id'] = item['variety_id'] new['group_name'] = item['group_name'] new['group_id'] = item['group_id'] new['file_folder'] = item['file_folder'] configs.append(new) return jsonify({'message': '查询成功', 'configs': configs})
def save_json_data(self): body_json = request.json utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) if not user_info or user_info['role_num'] > enums.COLLECTOR: return jsonify({"message": "登录已过期或不能操作."}), 400 today = datetime.datetime.today() date = body_json.get('date') time = body_json.get('time') country = body_json.get('country', '') event = body_json.get('event', '') expected = body_json.get('expected', '') if not all([date, time, event]): return jsonify({"message": "参数错误."}), 400 save_statement = "INSERT INTO `info_finance` " \ "(`create_time`,`date`, `time`,`country`,`event`,`expected`,`author_id`) " \ "VALUES (%s,%s,%s,%s,%s,%s,%s);" db_connection = MySQLConnection() try: date = datetime.datetime.strptime(date, "%Y-%m-%d") time = datetime.datetime.strptime(time, "%H:%M:%S") user_id = user_info['id'] cursor = db_connection.get_cursor() cursor.execute( save_statement, (today, date, time, country, event, expected, user_id)) db_connection.commit() except Exception as e: db_connection.close() current_app.logger.error("写入财经日历错误:{}".format(e)) return jsonify({"message": "错误:{}".format(e)}) else: return jsonify({"message": "添加成功!"}), 201
def get(self): utoken = request.args.get('utoken') role_num = request.args.get('role_num', 0) try: role_num = int(role_num) except Exception as e: return jsonify({"message": "参数错误"}), 400 user_info = verify_json_web_token(utoken) if not user_info or user_info['role_num'] > enums.OPERATOR: return jsonify({"message": "不能访问或登录已过期。"}), 400 if role_num == 0: query_statement = "SELECT `id`,`username`,`avatar`,`phone`,`email`,`role_num`,`note`, " \ "DATE_FORMAT(`join_time`,'%Y-%m-%d') AS `join_time`,DATE_FORMAT(`update_time`,'%Y-%m-%d') AS `update_time`" \ "FROM `info_user` WHERE `id`>1;" else: query_statement = "SELECT `id`,`username`,`avatar`,`phone`,`email`,`role_num`,`note`," \ "DATE_FORMAT(`join_time`,'%%Y-%%m-%%d') AS `join_time`," \ "DATE_FORMAT(`update_time`,'%%Y-%%m-%%d') AS `update_time` " \ "FROM `info_user` WHERE `role_num`=%d;" % role_num db_connection = MySQLConnection() cursor = db_connection.get_cursor() cursor.execute(query_statement) response_users = list() for user_item in cursor.fetchall(): user_item['role_text'] = enums.user_roles.get( user_item['role_num'], '未知') response_users.append(user_item) return jsonify({"message": "获取信息成功!", "users": response_users})
def delete(self, uid, nid): utoken = request.args.get('utoken') user_info = verify_json_web_token(utoken) if not user_info or user_info['id'] != uid: return jsonify({"message": "参数错误"}), 400 db_connection = MySQLConnection() try: cursor = db_connection.get_cursor() select_statement = "SELECT `file_url` FROM `info_exnotice` WHERE `id`=%d;" % nid cursor.execute(select_statement) file_url = cursor.fetchone()['file_url'] delete_statement = "DELETE FROM `info_exnotice` " \ "WHERE `id`=%d AND `author_id`=%d AND DATEDIFF(NOW(),`create_time`) < 3;" % (nid, uid) lines_changed = cursor.execute(delete_statement) if lines_changed <= 0: raise ValueError("不能删除较早期的通知了.") db_connection.commit() except Exception as e: db_connection.rollback() db_connection.close() return jsonify({"message": "删除失败{}".format(e)}), 400 else: db_connection.close() # 删除文件 if file_url: file_addr = os.path.join(BASE_DIR, "fileStorage/" + file_url) if os.path.isfile(file_addr): os.remove(file_addr) return jsonify({"message": "删除成功!"})
def put(self, rid): body_json = request.json record_info = body_json.get('record_data') utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) user_id = user_info['uid'] # 不为空的信息判断 content = record_info.get('content', False) if not content: return jsonify("参数错误,NOT FOUND CONTENT"), 400 # 组织信息 custom_time = record_info.get('custom_time') note = record_info.get('note', '') # 存入数据库 update_statement = "UPDATE `onduty_message` SET " \ "`custom_time`=%s,`content`=%s,`note`=%s" \ "WHERE `id`=%s AND `author_id`=%s;" try: user_id = int(user_id) custom_time = datetime.datetime.strptime( custom_time, '%Y-%m-%d') if custom_time else datetime.datetime.now() db_connection = MySQLConnection() cursor = db_connection.get_cursor() cursor.execute(update_statement, (custom_time, content, note, rid, user_id)) db_connection.commit() db_connection.close() except Exception as e: current_app.logger.error("修改值班记录错误:" + str(e)) return jsonify("参数错误!无法修改。"), 400 else: return jsonify("修改成功!")
def patch(self, uid): body_json = request.json utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) if not user_info: return jsonify({'message': '登录已过期,重新登录再进行修改'}), 400 user_id = int(user_info['id']) modify_dict = dict() for can_modify_key in ['username', 'password', 'phone', 'email']: if can_modify_key in body_json: if can_modify_key == 'password': modify_dict['password'] = hash_user_password( body_json['password']) else: modify_dict[can_modify_key] = body_json[can_modify_key] update_str = "" for modify_key in modify_dict: update_str += "`{}`='{}',".format(modify_key, modify_dict[modify_key]) update_str = update_str[:-1] update_statement = "UPDATE `info_user` SET %s WHERE `id`=%d;" % ( update_str, user_id) db_connection = MySQLConnection() cursor = db_connection.get_cursor() cursor.execute(update_statement) db_connection.commit() db_connection.close() return jsonify({"message": "修改成功!"})
def patch(self): body_json = request.json utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) if not user_info: return jsonify({'message': '请登录后再操作..'}), 400 user_id = user_info['id'] variety_id = body_json.get('variety_id', None) group_id = body_json.get('group_id', None) machine_code = body_json.get('machine_code') client_info = get_client(machine_code) if not all([user_id, variety_id, client_info, group_id]): return jsonify({'message': '参数错误'}), 400 client_id = client_info['id'] now = datetime.datetime.now() update_statement = "UPDATE `info_tablesource_configs` " \ "SET `update_time`=%s " \ "WHERE `client_id`=%s AND `user_id`=%s AND `variety_id`=%s AND `group_id`=%s;" db_connection = MySQLConnection() cursor = db_connection.get_cursor() cursor.execute(update_statement, (now, client_id, user_id, variety_id, group_id)) db_connection.commit() db_connection.close() return jsonify({'message': '修改成功'})
def delete(self, uid, sid): utoken = request.args.get('utoken') user_info = verify_json_web_token(utoken) if not user_info or user_info['id'] != uid: return jsonify({"message": "参数错误"}), 400 db_connection = MySQLConnection() try: cursor = db_connection.get_cursor() select_statement = "SELECT `file_url` FROM `info_searchreport` WHERE `id`=%d;" % sid cursor.execute(select_statement) file_url = cursor.fetchone()['file_url'] delete_statement = "DELETE FROM `info_searchreport` " \ "WHERE `id`=%d AND `author_id`=%d;" % (sid, uid) cursor.execute(delete_statement) db_connection.commit() except Exception as e: db_connection.rollback() db_connection.close() return jsonify({"message": "删除失败{}".format(e)}), 400 else: db_connection.close() # 删除文件 if file_url: file_addr = os.path.join(BASE_DIR, "fileStorage/" + file_url) if os.path.isfile(file_addr): os.remove(file_addr) return jsonify({"message": "删除成功!"})
def delete(self, cid): utoken = request.args.get('utoken') user_info = verify_json_web_token(utoken) if not user_info or int(user_info['role_num']) > 4: return jsonify({"message": "登录过期或不能进行这样的操作。"}), 400 # 查询配置文件 db_connection = MySQLConnection() cursor = db_connection.get_cursor() select_option_file = "SELECT `id`,`options_file` FROM `info_trend_echart` WHERE `id`=%s AND `author_id`=%s;" cursor.execute(select_option_file, (cid, user_info['id'])) fetch_one = cursor.fetchone() if not fetch_one: db_connection.close() return jsonify({'message': '系统中没有此图形信息。'}), 400 options_file_path = fetch_one['options_file'] options_file_path = os.path.join(BASE_DIR, options_file_path) try: delete_statement = "DELETE FROM `info_trend_echart` WHERE `id`=%s AND `author_id`=%s;" cursor.execute(delete_statement, (cid, user_info['id'])) db_connection.commit() except Exception as e: db_connection.close() current_app.logger.error("id={}用户删除图形失败:{}".format( user_info['id'], e)) return jsonify({'message': '删除失败!'}), 400 else: db_connection.close() if os.path.exists(options_file_path): os.remove(options_file_path) return jsonify({'message': '删除成功!'})
def delete(self, rid): utoken = request.args.get('utoken') user_info = verify_json_web_token(utoken) db_connection = MySQLConnection() annex_file_path = None try: cursor = db_connection.get_cursor() annex_query_statement = "SELECT `annex_url` FROM `monographic` WHERE `id`=%d;" % rid cursor.execute(annex_query_statement) annex_file = cursor.fetchone() if annex_file: annex_file_path = annex_file['annex_url'] user_id = int(user_info['uid']) delete_statement = "DELETE FROM `monographic` " \ "WHERE `id`=%d AND `author_id`=%d;" % (rid, user_id) lines_changed = cursor.execute(delete_statement) db_connection.commit() if lines_changed <= 0: raise ValueError("删除错误,没有记录被删除>…<") except Exception as e: db_connection.rollback() db_connection.close() return jsonify(str(e)) else: db_connection.close() if annex_file_path: file_local_path = os.path.join(BASE_DIR, annex_file_path) if os.path.isfile(file_local_path): os.remove(file_local_path) return jsonify("删除成功^.^!")
def get(self): params = request.args utoken = params.get('utoken') user_info = verify_json_web_token(utoken) if not user_info: return jsonify("登录已过期!刷新网页重新登录."), 400 try: start_date = params.get('startDate') end_date = params.get('endDate') end_date = datetime.datetime.strptime( end_date, '%Y-%m-%d') + datetime.timedelta(days=1) end_date = ( end_date + datetime.timedelta(seconds=-1)).strftime('%Y-%m-%d %H:%M:%S') except Exception: return jsonify("参数错误:DATE FORMAT ERROR!") query_statement = "SELECT usertb.name,usertb.org_id,ondmsgtb.custom_time,ondmsgtb.content,ondmsgtb.note " \ "FROM `user_info` AS usertb INNER JOIN `onduty_message` AS ondmsgtb ON " \ "usertb.id=%s AND usertb.id=ondmsgtb.author_id AND (ondmsgtb.custom_time BETWEEN %s AND %s) " \ "ORDER BY ondmsgtb.custom_time ASC;" db_connection = MySQLConnection() cursor = db_connection.get_cursor() cursor.execute(query_statement, (user_info['uid'], start_date, end_date)) records_all = cursor.fetchall() db_connection.close() # 生成承载数据的文件 t = "%.4f" % time.time() md5_hash = hashlib.md5() md5_hash.update(t.encode('utf-8')) md5_hash.update(user_info['name'].encode('utf-8')) md5_str = md5_hash.hexdigest() file_folder = os.path.join(BASE_DIR, 'fileStore/exports/') if not os.path.exists(file_folder): os.makedirs(file_folder) file_path = os.path.join(file_folder, '{}.xlsx'.format(md5_str)) file_records = list() for record_item in records_all: row_content = list() row_content.append(record_item['custom_time'].strftime("%Y-%m-%d")) row_content.append(ORGANIZATIONS.get(record_item['org_id'], '未知')) row_content.append(record_item['name']) row_content.append(record_item['content']) row_content.append(record_item['note']) file_records.append(row_content) export_df = pd.DataFrame(file_records) export_df.columns = ['日期', '部门小组', '姓名', '信息内容', '备注'] export_df.to_excel(excel_writer=file_path, index=False, sheet_name='值班信息记录') return send_from_directory( directory=file_folder, filename='{}.xlsx'.format(md5_str), as_attachment=True, attachment_filename='{}.xlsx'.format(md5_str))
def get(self): utoken = request.args.get('utoken') user_info = verify_json_web_token(utoken) if not user_info: message = '登录已过期' else: user_info['utoken'] = utoken message = "登录成功!" return jsonify({"message": message, "user_data": user_info})
def get(self): params = request.args # 解析用户信息 token = params.get('utoken') user_info = verify_json_web_token(token) if not user_info: return jsonify("您的登录已过期,请重新登录查看.") user_id = user_info['uid'] try: start_date = params.get('startDate') end_date = params.get('endDate') end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d') + datetime.timedelta(days=1) end_date = (end_date + datetime.timedelta(seconds=-1)).strftime('%Y-%m-%d %H:%M:%S') current_page = int(params.get('page', 1)) - 1 page_size = int(params.get('pagesize', 30)) except Exception: return jsonify("参数错误:INT TYPE REQUIRED!") start_id = current_page * page_size db_connection = MySQLConnection() cursor = db_connection.get_cursor() # sql内联查询 inner_join_statement = "SELECT usertb.name,usertb.org_id,smsgtb.id,smsgtb.custom_time,smsgtb.content,smsgtb.msg_type,smsgtb.effect_variety,smsgtb.note " \ "FROM `user_info` AS usertb INNER JOIN `short_message` AS smsgtb " \ "ON usertb.id=%s AND usertb.id=smsgtb.author_id AND (smsgtb.custom_time BETWEEN %s AND %s) " \ "ORDER BY smsgtb.custom_time DESC " \ "limit %s,%s;" cursor.execute(inner_join_statement, (user_id, start_date, end_date, start_id, page_size)) result_records = cursor.fetchall() # print("内连接查短讯通结果", result_records) # 查询总条数 count_statement = "SELECT COUNT(smsgtb.id) as total FROM `user_info` AS usertb INNER JOIN `short_message`AS smsgtb " \ "ON usertb.id=%s AND usertb.id=smsgtb.author_id AND (smsgtb.custom_time BETWEEN %s AND %s);" cursor.execute(count_statement, (user_id, start_date, end_date)) # print("条目记录:", cursor.fetchone()) 打开注释下行将无法解释编译 # 计算总页数 total_count = cursor.fetchone()['total'] db_connection.close() total_page = int((total_count + page_size - 1) / page_size) # print('total_page',total_page) # 组织数据返回 response_data = dict() response_data['records'] = list() for record_item in result_records: record_item['custom_time'] = record_item['custom_time'].strftime('%Y-%m-%d') record_item['org_name'] = ORGANIZATIONS.get(int(record_item['org_id']), "未知") response_data['records'].append(record_item) response_data['current_page'] = current_page + 1 # 查询前给减1处理了,加回来 response_data['total_page'] = total_page response_data['current_count'] = len(result_records) response_data['total_count'] = total_count return jsonify(response_data)
def save_file_data(self, spot_file): utoken = request.form.get('utoken') user_info = verify_json_web_token(utoken) if not user_info: return jsonify({"message": "登录已过期"}), 400 file_contents = xlrd.open_workbook(file_contents=spot_file.read()) table_data = file_contents.sheets()[0] if not file_contents.sheet_loaded(0): return jsonify({"message": "数据导入失败."}), 400 table_headers = table_data.row_values(0) if table_headers != ["日期", "名称", "地区", "等级", "价格", "增减", "备注"]: return jsonify({"message": "文件格式有误,请检查后再上传."}), 400 ready_to_save = list() start_data_in = False message = "表格数据类型有误,请检查后上传." today = datetime.datetime.today() user_id = int(user_info['id']) try: for row in range(table_data.nrows): row_content = table_data.row_values(row) if row_content[0] == "start": start_data_in = True continue if row_content[0] == 'end': start_data_in = False continue if start_data_in: record_row = list() #"日期", "名称","地区","等级","价格","增减","备注" record_row.append(today) record_row.append( xlrd.xldate_as_datetime(row_content[0], 0)) record_row.append(row_content[1]) record_row.append(row_content[2]) record_row.append(row_content[3]) record_row.append(float(row_content[4])) record_row.append(float(row_content[5])) record_row.append(row_content[6]) record_row.append(user_id) ready_to_save.append(record_row) except Exception as e: current_app.logger.error("批量上传现货报表数据错误:{}".format(e)) return jsonify({"message": message}), 400 insert_statement = "INSERT INTO `info_spot` " \ "(`create_time`,`custom_time`,`name`,`area`,`level`,`price`,`increase`,`note`,`author_id`) " \ "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s);" db_connection = MySQLConnection() cursor = db_connection.get_cursor() cursor.executemany(insert_statement, ready_to_save) db_connection.commit() db_connection.close() return jsonify({"message": "上传成功"}), 201
def get(self, uid): utoken = request.args.get('utoken') user_info = verify_json_web_token(utoken) user_id = user_info['id'] db_connection = MySQLConnection() cursor = db_connection.get_cursor() select_statement = "SELECT `id`,`phone`,`username`,`email`, `avatar` FROM `info_user` WHERE `id`=%s;" cursor.execute(select_statement, user_id) user_data = cursor.fetchone() db_connection.close() return jsonify({"message": "获取信息成功", "data": user_data})
def get(self): token = request.args.get('utoken') user_info = psd_handler.verify_json_web_token(token) if not user_info: # 状态保持错误 return jsonify('登录已过期.'), 400 org_id = user_info.get('org_id', None) if org_id: user_info['org_name'] = ORGANIZATIONS.get(int(org_id), '未知') else: user_info['org_name'] = '无' return jsonify(user_info)
def get(self): # 验证token token = request.args.get('token', None) user_info = psd_handler.verify_json_web_token(token) if not user_info: # 状态保持错误 return jsonify('登录已过期.'), 400 # 查询系统模块 db_connection = MySQLConnection() cursor = db_connection.get_cursor() uid = user_info['uid'] # 查询用户无需填报的模块 no_work_statement = "SELECT module_id FROM user_ndo_module WHERE user_id=%s AND is_active=1;" cursor.execute(no_work_statement, uid) no_work_module = cursor.fetchall() no_work_module = [item['module_id'] for item in no_work_module ] if no_work_module else [] # print('no_work_module', no_work_module) # 查询系统模块 if user_info['is_admin']: # print('管理员') # 查询主功能 modules_statement = "SELECT `id`,`name` FROM `work_module` WHERE `is_active`=1 AND `parent_id` is NULL ORDER BY `sort`;" # 查询子集的语句 sub_modules_statement = "SELECT `id`,`name`,`page_url` FROM `work_module` WHERE `is_active`=1 AND `parent_id`=%s ORDER BY `sort`;" else: # print('非管理员') # 查询主功能 modules_statement = "SELECT `id`,`name`,`page_url` FROM `work_module` WHERE `is_active`=1 AND `is_private`=0 AND `parent_id` is NULL ORDER BY `sort`;" # 查询子集的语句 sub_modules_statement = "SELECT `id`,`name`,`page_url` FROM `work_module` WHERE `is_active`=1 AND `is_private`=0 AND `parent_id`=%s ORDER BY `sort`;" cursor.execute(modules_statement) # 剔除无需处理的模块 response_modules = list() for module_item in cursor.fetchall(): # 注意 cursor.fetchall()只能用一次 if module_item['id'] in no_work_module: continue # 查询模块的子集 cursor.execute(sub_modules_statement, module_item['id']) # print('子集',cursor.fetchall(),type(cursor.fetchall())) sub_fetchall = cursor.fetchall() if not sub_fetchall: # 没有需工作的子集 continue # 遍历子集 module_item['subs'] = list() for sub_module_item in sub_fetchall: if sub_module_item['id'] in no_work_module: continue module_item['subs'].append(sub_module_item) if len(module_item['subs']) > 0: response_modules.append(module_item) # print(response_modules) db_connection.close() return jsonify(response_modules), 200
def put(self, rid): body_json = request.json record_info = body_json.get('record_data') utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) user_id = user_info['uid'] # 不为空的信息判断 content = record_info.get('content', False) variety_id = record_info.get('variety_id', False) direction = record_info.get('direction', False) if not content or not variety_id or not direction: return jsonify("参数错误,NOT FOUND CONTENT,VARIETY,DIRECTION."), 400 # 组织信息 custom_time = record_info.get('custom_time') contract = record_info.get('contract', '') hands = record_info.get('hands', 0) open_position = record_info.get('open_position', 0) close_position = record_info.get('close_position', 0) profit = record_info.get('profit') # 存入数据库 save_invest_statement = "UPDATE `investrategy` SET " \ "`custom_time`=%s,`content`=%s,`variety_id`=%s,`contract`=%s,`direction`=%s,`hands`=%s," \ "`open_position`=%s,`close_position`=%s,`profit`=%s " \ "WHERE `id`=%s AND `author_id`=%s;" db_connection = MySQLConnection() cursor = db_connection.get_cursor() try: # 转换类型 custom_time = datetime.datetime.strptime( custom_time, '%Y-%m-%d') if custom_time else datetime.datetime.now() variety_id = int(variety_id) hands = int(hands) if hands else 0 open_position = float(open_position) if open_position else 0 close_position = float(close_position) if close_position else 0 profit = float(profit) if profit else 0 cursor.execute( save_invest_statement, (custom_time, content, variety_id, contract, direction, hands, open_position, close_position, profit, rid, user_id)) db_connection.commit() except Exception as e: db_connection.rollback() db_connection.close() current_app.logger.error("更新投顾策略记录错误:" + str(e)) return jsonify("参数错误!无法修改。"), 400 else: db_connection.close() return jsonify("修改成功!"), 201
def put(self, tid): """修改id=tid的表内的指定一行数据""" body_json = request.json utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) user_id = user_info['id'] record_id = body_json.get('record_id') record_content = body_json.get('record_content') # 第一列的数据类型检测 try: record_content[0] = datetime.datetime.strptime( record_content[0], '%Y-%m-%d').strftime('%Y-%m-%d') except Exception as e: return jsonify({"message": "第一列时间数据格式错误!\n{}".format(e)}), 400 select_table_info = "SELECT `sql_table` " \ "FROM `info_trend_table` " \ "WHERE `is_active`=1 AND `id`=%d;" % tid db_connection = MySQLConnection() cursor = db_connection.get_cursor() cursor.execute(select_table_info) table_info = cursor.fetchone() table_sql_name = table_info['sql_table'] if not table_sql_name: db_connection.close() return jsonify({"message": "数据表不存在"}), 400 # 修改数据 col_str = "" for col_index in range(len(record_content)): if col_index == len(record_content) - 1: col_str += "`column_{}`=%s".format(col_index) else: col_str += "`column_{}`=%s,".format(col_index) update_statement = "UPDATE `%s` " \ "SET %s " \ "WHERE `id`=%s;" % (table_sql_name, col_str, record_id) # print("修改的sql:\n", update_statement) try: today = datetime.datetime.today() cursor.execute(update_statement, record_content) update_table_info = "UPDATE `info_trend_table` " \ "SET `updater_id`=%s,`update_time`=%s " \ "WHERE `id`=%s;" cursor.execute(update_table_info, (user_id, today, tid)) db_connection.commit() except Exception as e: db_connection.rollback() db_connection.close() return jsonify({"message": "修改失败{}".format(e)}), 400 else: db_connection.close() return jsonify({"message": "修改记录成功!"}), 200
def post(self): body_form = request.form utoken = body_form.get('utoken') user_info = verify_json_web_token(utoken) if not user_info or user_info['role_num'] > enums.COLLECTOR: return jsonify({"message": "登录已过期或不能进行操作。"}), 400 title = body_form.get('title', None) notice_file = request.files.get('notice_file') category = body_form.get('category', 0) if not all([title, notice_file]): return jsonify({"message": "参数错误!"}), 400 db_connection = MySQLConnection() cursor = db_connection.get_cursor() notice_filename = notice_file.filename file_hash_name = hash_filename(notice_filename) today = datetime.datetime.today() year = today.year month = "%.2d" % today.month day = "%.2d" % today.day exnotice_folder = os.path.join( BASE_DIR, "fileStorage/homepage/exnotice/{}/{}/".format(year, month)) if not os.path.exists(exnotice_folder): os.makedirs(exnotice_folder) prefix_filename = "{}_".format(day) file_path = os.path.join(exnotice_folder, prefix_filename + file_hash_name) file_save_url = "homepage/exnotice/{}/{}/".format( year, month) + prefix_filename + file_hash_name notice_file.save(file_path) save_statement = "INSERT INTO `info_exnotice` (`create_time`,`title`,`file_url`,`category`,`author_id`) " \ "VALUES (%s,%s,%s,%s,%s);" try: user_id = int(user_info['id']) category = int(category) if category < 0 or category > 3: raise ValueError('分类错误!') cursor.execute(save_statement, (today, title, file_save_url, category, user_id)) db_connection.commit() except Exception as e: db_connection.rollback() os.remove(file_path) db_connection.close() current_app.logger.error("上传交易通知错误:{}".format(e)) return jsonify({'message': "上传交易通知错误"}), 400 else: db_connection.close() return jsonify({"message": "上传交易通知成功!"}), 201
def post(self, user_id): utoken = request.json.get('utoken') operator_user = psd_handler.verify_json_web_token(utoken) if not operator_user or not operator_user['is_admin']: return jsonify("登录已过期或无权限操作!"), 400 password = request.json.get('password') new_password = psd_handler.hash_user_password(password) # 设置新密码 update_statement = "UPDATE `user_info` SET `password`=%s WHERE `id`=%s;" db_connection = MySQLConnection() cursor = db_connection.get_cursor() cursor.execute(update_statement, (new_password, user_id)) db_connection.commit() db_connection.close() return jsonify("重置用户密码成功!\n新密码为:123456")
def post(self): body_json = request.json utoken = body_json.get('utoken') password = body_json.get('password') user_info = psd_handler.verify_json_web_token(utoken) if not user_info: return jsonify("登录已过期,重新登录"), 400 # 重定向 user_id = user_info['uid'] new_password = psd_handler.hash_user_password(password) db_connection = MySQLConnection() cursor = db_connection.get_cursor() modify_statement = "UPDATE `user_info` SET `password`=%s WHERE `id`=%s;" cursor.execute(modify_statement, (new_password, user_id)) db_connection.commit() db_connection.close() return jsonify("修改密码成功!请重新登录!") # 重定向
def post(self, tid): """给一张表新增数据""" body_json = request.json utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) user_id = user_info['id'] new_contents = body_json.get('new_contents') if len(new_contents) <= 0: return jsonify({"message": '没有发现任何新数据..'}), 400 new_headers = body_json.get('new_header') select_table_info = "SELECT `sql_table` " \ "FROM `info_trend_table` " \ "WHERE `is_active`=1 AND `id`=%d;" % tid db_connection = MySQLConnection() cursor = db_connection.get_cursor() cursor.execute(select_table_info) table_info = cursor.fetchone() table_sql_name = table_info['sql_table'] if not table_sql_name: db_connection.close() return jsonify({"message": "数据表不存在"}), 400 col_str = "" content_str = "" for col_index in range(len(new_headers)): if col_index == len(new_headers) - 1: col_str += "`column_{}`".format(col_index) content_str += "%s" else: col_str += "`column_{}`,".format(col_index) content_str += "%s," insert_statement = "INSERT INTO `%s` (%s) " \ "VALUES (%s);" % (table_sql_name, col_str, content_str) today = datetime.datetime.today() try: cursor.executemany(insert_statement, new_contents) update_info_statement = "UPDATE `info_trend_table` " \ "SET `update_time`=%s, `updater_id`=%s " \ "WHERE `id`=%s;" cursor.execute(update_info_statement, (today, user_id, tid)) db_connection.commit() except Exception as e: db_connection.rollback() db_connection.close() return jsonify({'message': "失败{}".format(e)}) else: db_connection.close() return jsonify({"message": '添加成功'}), 201
def post(self): body_json = request.json utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) if not user_info: return jsonify({'message': '请登录后再操作..'}), 400 user_id = user_info['id'] variety_name = body_json.get('variety_name', '') variety_id = body_json.get('variety_id', None) group_name = body_json.get('group_name', '') group_id = body_json.get('group_id', None) machine_code = body_json.get('machine_code') file_folder = body_json.get('file_folder', None) client_info = get_client(machine_code) if not all([user_id, variety_id, group_id, client_info, file_folder]): return jsonify({'message': '参数错误'}), 400 db_connection = MySQLConnection() cursor = db_connection.get_cursor() now = datetime.datetime.now() client_id = client_info['id'] # 查找当前配置是否存在 exist_statement = "SELECT `id` FROM `info_tablesource_configs` " \ "WHERE `client_id`=%s AND `variety_id`=%s AND `group_id`=%s AND `user_id`=%s;" cursor.execute(exist_statement, (client_id, variety_id, group_id, user_id)) record_exist = cursor.fetchone() if record_exist: # 更新 exist_id = record_exist['id'] update_statement = "UPDATE `info_tablesource_configs` SET " \ "`update_time`=%s,`variety_name`=%s, `variety_id`=%s,`group_name`=%s,`group_id`=%s, `client_id`=%s,`user_id`=%s,`file_folder`=%s " \ "WHERE `id`=%s;" cursor.execute( update_statement, (now, variety_name, variety_id, group_name, group_id, client_id, user_id, file_folder, exist_id)) else: insert_statement = "INSERT INTO `info_tablesource_configs` " \ "(`update_time`,`variety_name`, `variety_id`,`group_name`,`group_id`, `client_id`,`user_id`,`file_folder`) " \ "VALUES (%s,%s,%s,%s,%s,%s,%s,%s);" \ cursor.execute(insert_statement, (now, variety_name, variety_id, group_name, group_id, client_id, user_id, file_folder)) db_connection.commit() db_connection.close() return jsonify({'message': '配置成功!'})
def post(self): body_json = request.form utoken = body_json.get('utoken') user_info = verify_json_web_token(utoken) if user_info['role_num'] > 3: return jsonify({"message": "登录已过期或不能进行这个操作."}), 400 bulletin_title = body_json.get('bulletin_title') bulletin_file = request.files.get('bulletin_file', None) if not all([bulletin_title, bulletin_file]): return jsonify({"message": "参数错误!NOT FOUND NAME OR FILE."}), 400 # hash文件名 bulletin_filename = bulletin_file.filename file_hash_name = hash_filename(bulletin_filename) today = datetime.datetime.today() year = today.year month = "%.2d" % today.month day = "%.2d" % today.day bulletin_folder = os.path.join( BASE_DIR, "fileStorage/homepage/bulletin/{}/{}/".format(year, month)) if not os.path.exists(bulletin_folder): os.makedirs(bulletin_folder) prefix_filename = "{}_".format(day) file_path = os.path.join(bulletin_folder, prefix_filename + file_hash_name) file_save_url = "homepage/bulletin/{}/{}/".format( year, month) + prefix_filename + file_hash_name bulletin_file.save(file_path) # 保存到数据库 save_bulletin_statement = "INSERT INTO `info_bulletin` (`create_time`,`title`,`file_url`) " \ "VALUES (%s, %s,%s);" db_connection = MySQLConnection() cursor = db_connection.get_cursor() try: cursor.execute(save_bulletin_statement, (today, bulletin_title, file_save_url)) db_connection.commit() except Exception as e: current_app.logger.error("保存公告错误:{}".format(e)), 400 db_connection.rollback() db_connection.close() return jsonify({"message": "上传公告失败!"}), 400 else: db_connection.close() return jsonify({"message": "上传公告成功!"}), 201