├── .DS_Store ├── README.md ├── api ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ └── resource.cpython-36.pyc ├── department │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── interface_department.cpython-36.pyc │ │ └── interface_department_staff.cpython-36.pyc │ ├── interface_department.py │ └── interface_department_staff.py ├── login │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── interface_login.cpython-36.pyc │ └── interface_login.py ├── resource.py ├── role │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── interface_permission.cpython-36.pyc │ │ ├── interface_role.cpython-36.pyc │ │ └── interface_role_permission.cpython-36.pyc │ ├── interface_permission.py │ ├── interface_role.py │ └── interface_role_permission.py ├── user │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── interface_basic.cpython-36.pyc │ │ ├── interface_password.cpython-36.pyc │ │ └── interface_user.cpython-36.pyc │ ├── interface_basic.py │ ├── interface_password.py │ └── interface_user.py └── user_group │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── interface_user_group.cpython-36.pyc │ ├── interface_user_group_role.cpython-36.pyc │ └── interface_user_group_staff.cpython-36.pyc │ ├── interface_user_group.py │ ├── interface_user_group_role.py │ └── interface_user_group_staff.py ├── common ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── common_api_version.cpython-36.pyc │ ├── common_log.cpython-36.pyc │ ├── common_login_helper.cpython-36.pyc │ ├── common_model_enum.cpython-36.pyc │ ├── common_request_process.cpython-36.pyc │ ├── common_response_code.cpython-36.pyc │ ├── common_response_log.cpython-36.pyc │ ├── common_response_process.cpython-36.pyc │ └── common_time.cpython-36.pyc ├── common_api_version.py ├── common_log.py ├── common_login_helper.py ├── common_model_enum.py ├── common_request_process.py ├── common_response_code.py ├── common_response_log.py ├── common_response_process.py └── common_time.py ├── config.ini ├── config.py ├── core ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── department_singleton.cpython-36.pyc │ ├── role_permission_singleton.cpython-36.pyc │ ├── user_group_singleton.cpython-36.pyc │ └── user_singleton.cpython-36.pyc ├── department_singleton.py ├── role_permission_singleton.py ├── user_group_singleton.py └── user_singleton.py ├── db ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── base.cpython-36.pyc │ └── connection_pool.cpython-36.pyc ├── base.py ├── connection_pool.py ├── department │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── db_department_mgr.cpython-36.pyc │ └── db_department_mgr.py ├── logger │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── db_log_mgr.cpython-36.pyc │ └── db_log_mgr.py ├── role │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── db_role_permission_mgr.cpython-36.pyc │ └── db_role_permission_mgr.py ├── user │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── db_user_mgr.cpython-36.pyc │ └── db_user_mgr.py └── user_group │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-36.pyc │ └── db_group_mgr.cpython-36.pyc │ └── db_group_mgr.py ├── dbsql └── user_api.sql ├── requirements.txt ├── start.py ├── utils ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── api_version_verify.cpython-36.pyc │ ├── auth_helper.cpython-36.pyc │ ├── fun_name_to_enum.cpython-36.pyc │ ├── log_helper.cpython-36.pyc │ ├── status_code.cpython-36.pyc │ └── xml_json_process.cpython-36.pyc ├── api_version_verify.py ├── auth_helper.py ├── fun_name_to_enum.py ├── log_helper.py ├── status_code.py └── xml_json_process.py └── var └── log └── user_api.log /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/.DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### user_restful_api 2 | 这是一个通用的用户、部门、角色、权限管理的API接口 3 | 4 | ##### 1.项目依赖 5 | 6 | ``` 7 | aniso8601==8.0.0 8 | Click==7.0 9 | DBUtils==1.3 10 | Flask==1.1.1 11 | Flask-Cors==3.0.8 12 | Flask-JWT==0.3.2 13 | Flask-RESTful==0.3.7 14 | itsdangerous==1.1.0 15 | Jinja2==2.10.3 16 | MarkupSafe==1.1.1 17 | PyJWT==1.4.2 18 | PyMySQL==0.9.3 19 | xmltodict==0.12.0 20 | ``` 21 | 22 | 安装依赖,请切换到项目工程目录下面。然后使用如下命令进行安装: 23 | 24 | ``` 25 | pip install -r requirements.txt 26 | ``` 27 | 28 | ##### 2. 项目的启动文件 29 | 30 | ``` 31 | start.py 32 | ``` 33 | 34 | ##### 3. 项目配置文件 35 | 36 | ``` 37 | config.ini 38 | ``` 39 | 40 | ##### 4 .项目数据sql 41 | 42 | ``` 43 | user_api.sql 44 | ``` 45 | 46 | >数据库中默认有一个用户名为:super 密码为:123456 47 | 48 | -------------------------------------------------------------------------------- /api/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 13:26 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from flask import Flask 12 | from flask_cors import CORS 13 | 14 | 15 | from api.resource import api 16 | from utils.log_helper import init_log 17 | 18 | from config import config, Config 19 | 20 | 21 | def create_app(config_name): 22 | app = Flask(__name__) 23 | # 验证 24 | CORS(app,supports_credentials=True) 25 | app.config.from_object(config[config_name]) 26 | config[config_name].init_app(app) 27 | ###初始化数据库 28 | # db.init_app(app) 29 | # 返回数据中response为中文 30 | app.config['JSON_AS_ASCII'] = False 31 | 32 | 33 | ###初始化日志### 34 | init_log() 35 | api.init_app(app) 36 | return app -------------------------------------------------------------------------------- /api/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /api/__pycache__/resource.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/__pycache__/resource.cpython-36.pyc -------------------------------------------------------------------------------- /api/department/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 14:35 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /api/department/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/department/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /api/department/__pycache__/interface_department.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/department/__pycache__/interface_department.cpython-36.pyc -------------------------------------------------------------------------------- /api/department/__pycache__/interface_department_staff.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/department/__pycache__/interface_department_staff.cpython-36.pyc -------------------------------------------------------------------------------- /api/department/interface_department.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_department.py 6 | @create date: 2019-10-27 14:48 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | from flask import request 13 | from flask_restful import Resource 14 | 15 | from common.common_login_helper import login_required 16 | from common.common_request_process import req 17 | from common.common_response_process import response_result_process 18 | from core.department_singleton import department_singleton 19 | 20 | from utils.api_version_verify import api_version 21 | from utils.log_helper import lg 22 | from utils.status_code import response_code 23 | from common.common_model_enum import modelEnum 24 | 25 | 26 | class interfaceDepartment(Resource): 27 | @api_version 28 | @login_required 29 | def get(self, version,dpt_id=None): 30 | xml = request.args.get('format') 31 | try: 32 | if dpt_id is not None: 33 | data = response_code.NOT_FOUND 34 | return response_result_process(data, xml=xml) 35 | data = department_singleton.get_department() 36 | body = modelEnum.department.value.get('body') 37 | return response_result_process(data, xml_structure_str=body, xml=xml) 38 | except Exception as e: 39 | lg.error(e) 40 | error_data = response_code.GET_DATA_FAIL 41 | return response_result_process(error_data, xml=xml) 42 | 43 | @api_version 44 | @login_required 45 | def post(self,version,dpt_id=None): 46 | xml = request.args.get('format') 47 | try: 48 | if dpt_id is not None: 49 | data = response_code.NOT_FOUND 50 | return response_result_process(data, xml=xml) 51 | request_data = req.request_process(request, xml, modelEnum.department.value) 52 | if isinstance(request_data, bool): 53 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 54 | return response_result_process(request_data, xml=xml) 55 | if not request_data: 56 | data = response_code.REQUEST_PARAM_MISSED 57 | return response_result_process(data, xml=xml) 58 | fields = ['dpt_name', 'p_id'] 59 | must = req.verify_all_param_must(request_data, fields) 60 | if must: 61 | return response_result_process(must, xml=xml) 62 | par_type = {'dpt_name': str, 'p_id': int} 63 | param_type = req.verify_all_param_type(request_data, par_type) 64 | if param_type: 65 | return response_result_process(param_type, xml=xml) 66 | dpt_name,dpt_p_id = request_data.get('dpt_name'),request_data.get('p_id') 67 | data = department_singleton.add_department(dpt_name, dpt_p_id) 68 | return response_result_process(data, xml=xml) 69 | except Exception as e: 70 | lg.error(e) 71 | error_data = response_code.ADD_DATA_FAIL 72 | return response_result_process(error_data, xml=xml) 73 | 74 | @api_version 75 | @login_required 76 | def put(self,version,dpt_id=None): 77 | xml = request.args.get('format') 78 | try: 79 | if dpt_id is None: 80 | data = response_code.NOT_FOUND 81 | return response_result_process(data, xml=xml) 82 | 83 | if dpt_id is not None: 84 | request_data = req.request_process(request, xml, modelEnum.department.value) 85 | if isinstance(request_data, bool): 86 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 87 | return response_result_process(request_data, xml=xml) 88 | if not request_data: 89 | data = response_code.REQUEST_PARAM_MISSED 90 | return response_result_process(data, xml=xml) 91 | 92 | fields = ['dpt_name','p_id'] 93 | must = req.verify_all_param_must(request_data, fields) 94 | if must: 95 | return response_result_process(must, xml=xml) 96 | 97 | par_type = {'dpt_name': str, 'p_id': int} 98 | 99 | param_type = req.verify_all_param_type(request_data, par_type) 100 | if param_type: 101 | return response_result_process(param_type, xml=xml) 102 | dpt_name = request_data.get('dpt_name') 103 | p_id = request_data.get('p_id') 104 | data = department_singleton.update_department(dpt_id, dpt_name,p_id) 105 | return response_result_process(data, xml=xml) 106 | except Exception as e: 107 | lg.error(e) 108 | error_data = response_code.UPDATE_DATA_FAIL 109 | return response_result_process(error_data, xml=xml) 110 | 111 | @api_version 112 | @login_required 113 | def delete(self,version,dpt_id=None): 114 | xml = request.args.get('format') 115 | try: 116 | if dpt_id is None: 117 | data = response_code.NOT_FOUND 118 | return response_result_process(data, xml=xml) 119 | 120 | if dpt_id is not None: 121 | data = department_singleton.delete_department(dpt_id) 122 | return response_result_process(data, xml=xml) 123 | 124 | except Exception as e: 125 | lg.error(e) 126 | error_data = response_code.DELETE_DATA_FAIL 127 | return response_result_process(error_data, xml=xml) -------------------------------------------------------------------------------- /api/department/interface_department_staff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_department_staff.py 6 | @create date: 2019-10-27 14:50 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | from flask import request 13 | from flask_restful import Resource 14 | 15 | from common.common_login_helper import login_required 16 | from common.common_model_enum import modelEnum 17 | from common.common_request_process import req 18 | from common.common_response_code import response_code 19 | from common.common_response_process import response_result_process 20 | from core.department_singleton import department_singleton 21 | 22 | from utils.api_version_verify import api_version 23 | from utils.log_helper import lg 24 | 25 | 26 | class interfaceDepartmentStaff(Resource): 27 | @api_version 28 | @login_required 29 | def get(self, version, dpt_id=None): 30 | xml = request.args.get('format') 31 | try: 32 | if dpt_id is None: 33 | data = response_code.NOT_FOUND 34 | return response_result_process(data, xml=xml) 35 | 36 | request_data = req.request_process(request, xml, modelEnum.department.value) 37 | if isinstance(request_data, bool): 38 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 39 | return response_result_process(request_data, xml=xml) 40 | if not request_data: 41 | data = response_code.REQUEST_PARAM_MISSED 42 | return response_result_process(data, xml=xml) 43 | fields = ['current_page', 'page_size'] 44 | must = req.verify_all_param_must(request_data, fields) 45 | if must: 46 | return response_result_process(must, xml=xml) 47 | par_type = {'page_size': int, 'current_page': int} 48 | param_type = req.verify_all_param_type(request_data, par_type) 49 | if param_type: 50 | return response_result_process(param_type, xml=xml) 51 | 52 | current_page, page_size = int(request_data.get('current_page')), int(request_data.get('page_size')) 53 | data = department_singleton.get_dpt_user_info_by_id(dpt_id, current_page, page_size) 54 | body = modelEnum.department.value.get('body') 55 | return response_result_process(data, xml_structure_str=body, xml=xml) 56 | except Exception as e: 57 | lg.error(e) 58 | error_data = response_code.GET_DATA_FAIL 59 | return response_result_process(error_data, xml=xml) 60 | 61 | @api_version 62 | @login_required 63 | def post(self, version, dpt_id=None): 64 | xml = request.args.get('format') 65 | try: 66 | if dpt_id is None: 67 | data = response_code.NOT_FOUND 68 | return response_result_process(data, xml=xml) 69 | request_data = req.request_process(request, xml, modelEnum.department.value) 70 | if isinstance(request_data, bool): 71 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 72 | return response_result_process(request_data, xml=xml) 73 | if not request_data: 74 | data = response_code.REQUEST_PARAM_MISSED 75 | return response_result_process(data, xml=xml) 76 | fields = ['user_ids'] 77 | must = req.verify_all_param_must(request_data, fields) 78 | if must: 79 | return response_result_process(must, xml=xml) 80 | par_type = {'user_ids': list} 81 | param_type = req.verify_all_param_type(request_data, par_type) 82 | if param_type: 83 | return response_result_process(param_type, xml=xml) 84 | user_ids = str(request_data.get('user_ids')) 85 | data = department_singleton.department_add_staff(dpt_id, user_ids) 86 | return response_result_process(data, xml=xml) 87 | except Exception as e: 88 | lg.error(e) 89 | error_data = response_code.ADD_DATA_FAIL 90 | return response_result_process(error_data, xml=xml) 91 | 92 | @api_version 93 | @login_required 94 | def delete(self, version, dpt_id=None): 95 | xml = request.args.get('format') 96 | try: 97 | if dpt_id is None: 98 | data = response_code.NOT_FOUND 99 | return response_result_process(data, xml=xml) 100 | request_data = req.request_process(request, xml, modelEnum.department.value) 101 | if isinstance(request_data, bool): 102 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 103 | return response_result_process(request_data, xml=xml) 104 | if not request_data: 105 | data = response_code.REQUEST_PARAM_MISSED 106 | return response_result_process(data, xml=xml) 107 | fields = ['user_ids'] 108 | must = req.verify_all_param_must(request_data, fields) 109 | if must: 110 | return response_result_process(must, xml=xml) 111 | par_type = {'user_ids': list} 112 | param_type = req.verify_all_param_type(request_data, par_type) 113 | if param_type: 114 | return response_result_process(param_type, xml=xml) 115 | user_ids = str(request_data.get('user_ids')) 116 | 117 | data = department_singleton.delete_department_staff(dpt_id, user_ids) 118 | return response_result_process(data, xml=xml) 119 | 120 | except Exception as e: 121 | lg.error(e) 122 | error_data = response_code.DELETE_DATA_FAIL 123 | return response_result_process(error_data, xml=xml) 124 | -------------------------------------------------------------------------------- /api/login/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 14:36 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /api/login/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/login/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /api/login/__pycache__/interface_login.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/login/__pycache__/interface_login.cpython-36.pyc -------------------------------------------------------------------------------- /api/login/interface_login.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_login.py 6 | @create date: 2019-10-27 14:36 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | from flask import request, g 13 | from flask_restful import Resource 14 | 15 | from common.common_log import operation_log 16 | from common.common_model_enum import modelEnum 17 | from common.common_request_process import req 18 | from common.common_response_process import response_result_process 19 | 20 | from utils.api_version_verify import api_version 21 | from utils.auth_helper import Auth 22 | from utils.log_helper import lg 23 | from utils.status_code import response_code 24 | 25 | 26 | class interfaceLogin(Resource): 27 | 28 | @api_version 29 | def post(self, version): 30 | xml = request.args.get('format') 31 | try: 32 | request_data = req.request_process(request, xml, modelEnum.login.value) 33 | if isinstance(request_data, bool): 34 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 35 | return response_result_process(request_data, xml=xml) 36 | if not request_data: 37 | data = response_code.REQUEST_PARAM_MISSED 38 | return response_result_process(data, xml=xml) 39 | fields = ['login_name', 'login_password'] 40 | must = req.verify_all_param_must(request_data, fields) 41 | if must: 42 | return response_result_process(must, xml=xml) 43 | 44 | login_name, login_password = request_data.get('login_name'), request_data.get('login_password') 45 | # 对登录情况进行验证 46 | dict_user = Auth.authenticate(login_name, login_password) 47 | # 将用户信息写到全局 48 | user_key = dict_user.get('id') 49 | operation_log(description='login') 50 | if user_key: 51 | g.user_key = user_key 52 | data = {} 53 | data['code'] = 200 54 | data['msg'] = '请求成功' 55 | data['data'] = dict_user 56 | else: 57 | data = dict_user 58 | 59 | return response_result_process(data, xml=xml) 60 | except Exception as e: 61 | lg.error(e) 62 | error_data = response_code.LOGIN_FAIL 63 | return response_result_process(error_data, xml=xml) 64 | -------------------------------------------------------------------------------- /api/resource.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: resource.py 6 | @create date: 2019-10-27 13:28 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from flask_restful import Api 12 | 13 | from api.department.interface_department import interfaceDepartment 14 | from api.department.interface_department_staff import interfaceDepartmentStaff 15 | from api.login.interface_login import interfaceLogin 16 | from api.role.interface_permission import interfacePermission 17 | from api.role.interface_role import interfaceRole 18 | from api.role.interface_role_permission import interfaceRolePermission 19 | from api.user.interface_basic import interfaceUserBasic 20 | from api.user.interface_password import interfacePassword 21 | from api.user.interface_user import interfaceUser 22 | from api.user_group.interface_user_group import interfaceUserGroup 23 | from api.user_group.interface_user_group_role import interfaceUserGroupRole 24 | from api.user_group.interface_user_group_staff import interfaceUserGroupStaff 25 | 26 | api = Api() 27 | 28 | # 部门管理 29 | api.add_resource( 30 | interfaceDepartment, 31 | '/li-boss//department', 32 | '/li-boss//department/' 33 | ) 34 | 35 | 36 | api.add_resource( 37 | interfaceDepartmentStaff, 38 | '/li-boss//department/staff/' 39 | ) 40 | 41 | # 用户 42 | api.add_resource( 43 | interfaceUser, 44 | '/li-boss//user', 45 | '/li-boss//user/', 46 | 47 | ) 48 | 49 | # 密码 50 | api.add_resource( 51 | interfacePassword, 52 | '/li-boss//user//password' 53 | ) 54 | 55 | # 基本信息修改 56 | api.add_resource( 57 | interfaceUserBasic, 58 | '/li-boss//user//base/info' 59 | ) 60 | 61 | # 角色 62 | api.add_resource( 63 | interfaceRole, 64 | '/li-boss//role', 65 | '/li-boss//role/' 66 | ) 67 | # 角色权限 68 | api.add_resource( 69 | interfaceRolePermission, 70 | '/li-boss//role//permission' 71 | ) 72 | # 权限 73 | api.add_resource( 74 | interfacePermission, 75 | '/li-boss//permission' 76 | ) 77 | 78 | # 用户组 79 | api.add_resource( 80 | interfaceUserGroup, 81 | '/li-boss//user/group', 82 | '/li-boss//user/group/' 83 | ) 84 | 85 | 86 | api.add_resource( 87 | interfaceUserGroupStaff, 88 | '/li-boss//user/group//staff' 89 | ) 90 | 91 | # 获取用户组的角色信息 92 | api.add_resource( 93 | interfaceUserGroupRole, 94 | '/li-boss//user/group//role' 95 | ) 96 | 97 | api.add_resource( 98 | interfaceLogin, 99 | '/li-boss//login' 100 | ) -------------------------------------------------------------------------------- /api/role/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 14:35 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /api/role/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/role/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /api/role/__pycache__/interface_permission.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/role/__pycache__/interface_permission.cpython-36.pyc -------------------------------------------------------------------------------- /api/role/__pycache__/interface_role.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/role/__pycache__/interface_role.cpython-36.pyc -------------------------------------------------------------------------------- /api/role/__pycache__/interface_role_permission.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/role/__pycache__/interface_role_permission.cpython-36.pyc -------------------------------------------------------------------------------- /api/role/interface_permission.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_permission.py 6 | @create date: 2019-10-27 14:51 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from flask import request 12 | from flask_restful import Resource 13 | 14 | from common.common_login_helper import login_required 15 | from common.common_model_enum import modelEnum 16 | from common.common_response_code import response_code 17 | from common.common_response_process import response_result_process 18 | from core.role_permission_singleton import role_permission_singleton 19 | 20 | from utils.api_version_verify import api_version 21 | from utils.log_helper import lg 22 | 23 | 24 | class interfacePermission(Resource): 25 | @api_version 26 | @login_required 27 | def get(self, version): 28 | xml = request.args.get('format') 29 | try: 30 | body = modelEnum.permission.value.get('body') 31 | data = role_permission_singleton.get_user_permission_info() 32 | return response_result_process(data, xml_structure_str=body, xml=xml) 33 | except Exception as e: 34 | lg.error(e) 35 | error_data = response_code.GET_DATA_FAIL 36 | return response_result_process(error_data, xml=xml) -------------------------------------------------------------------------------- /api/role/interface_role.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_role.py 6 | @create date: 2019-10-27 14:51 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from flask import request 12 | from flask_restful import Resource 13 | 14 | from common.common_login_helper import login_required 15 | from common.common_model_enum import modelEnum 16 | from common.common_request_process import req 17 | from common.common_response_process import response_result_process 18 | from core.role_permission_singleton import role_permission_singleton 19 | 20 | from utils.api_version_verify import api_version 21 | from utils.log_helper import lg 22 | from utils.status_code import response_code 23 | 24 | 25 | class interfaceRole(Resource): 26 | @api_version 27 | @login_required 28 | def get(self, version, role_id=None): 29 | xml = request.args.get('format') 30 | try: 31 | if role_id is not None: 32 | data = response_code.NOT_FOUND 33 | return response_result_process(data, xml=xml) 34 | 35 | request_data = req.request_process(request, xml, modelEnum.role.value) 36 | if isinstance(request_data, bool): 37 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 38 | return response_result_process(request_data, xml=xml) 39 | if not request_data: 40 | data = role_permission_singleton.get_all_roles() 41 | else: 42 | fields = ['current_page', 'page_size'] 43 | must = req.verify_all_param_must(request_data, fields) 44 | if must: 45 | return response_result_process(must, xml=xml) 46 | par_type = {'page_size': int, 'current_page': int,'search_data':dict} 47 | param_type = req.verify_all_param_type(request_data, par_type) 48 | if param_type: 49 | return response_result_process(param_type, xml=xml) 50 | 51 | current_page, page_size = int(request_data.get('current_page')), int(request_data.get('page_size')) 52 | search_data = request_data.get('search_data') if request_data.get('search_data') else {} 53 | 54 | data = role_permission_singleton.get_pages_roles(current_page,page_size,search_data) 55 | 56 | body = modelEnum.role.value.get('body') 57 | return response_result_process(data, xml_structure_str=body, xml=xml) 58 | except Exception as e: 59 | lg.error(e) 60 | error_data = response_code.GET_DATA_FAIL 61 | return response_result_process(error_data, xml=xml) 62 | 63 | @api_version 64 | @login_required 65 | def post(self, version, role_id=None): 66 | xml = request.args.get('format') 67 | try: 68 | if role_id is not None: 69 | data = response_code.NOT_FOUND 70 | return response_result_process(data, xml=xml) 71 | request_data = req.request_process(request, xml, modelEnum.role.value) 72 | if isinstance(request_data, bool): 73 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 74 | return response_result_process(request_data, xml=xml) 75 | if not request_data: 76 | data = response_code.REQUEST_PARAM_MISSED 77 | return response_result_process(data, xml=xml) 78 | fields = ['role_name'] 79 | must = req.verify_all_param_must(request_data, fields) 80 | if must: 81 | return response_result_process(must, xml=xml) 82 | par_type = {'role_name': str, 'note_info': str} 83 | param_type = req.verify_all_param_type(request_data, par_type) 84 | if param_type: 85 | return response_result_process(param_type, xml=xml) 86 | role_name = request_data.get('role_name') 87 | note_info = request_data.get('note_info') if request_data.get('note_info') is not None else '' 88 | 89 | data = role_permission_singleton.add_role(role_name, note_info) 90 | return response_result_process(data, xml=xml) 91 | except Exception as e: 92 | lg.error(e) 93 | error_data = response_code.ADD_DATA_FAIL 94 | return response_result_process(error_data, xml=xml) 95 | 96 | @api_version 97 | @login_required 98 | def put(self, version, role_id=None): 99 | xml = request.args.get('format') 100 | try: 101 | if role_id is None: 102 | data = response_code.NOT_FOUND 103 | return response_result_process(data, xml=xml) 104 | 105 | if role_id is not None: 106 | request_data = req.request_process(request, xml, modelEnum.role.value) 107 | if isinstance(request_data, bool): 108 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 109 | return response_result_process(request_data, xml=xml) 110 | if not request_data: 111 | data = response_code.REQUEST_PARAM_MISSED 112 | return response_result_process(data, xml=xml) 113 | 114 | fields = ['role_name'] 115 | must = req.verify_all_param_must(request_data, fields) 116 | if must: 117 | return response_result_process(must, xml=xml) 118 | 119 | par_type = {'role_name': str, 'note_info':str} 120 | 121 | param_type = req.verify_all_param_type(request_data, par_type) 122 | if param_type: 123 | return response_result_process(param_type, xml=xml) 124 | role_name = request_data.get('role_name') 125 | note_info = request_data.get('note_info') if request_data.get('note_info') else '' 126 | 127 | 128 | data = role_permission_singleton.update_role(role_id, role_name, note_info) 129 | return response_result_process(data, xml=xml) 130 | except Exception as e: 131 | lg.error(e) 132 | error_data = response_code.UPDATE_DATA_FAIL 133 | return response_result_process(error_data, xml=xml) 134 | 135 | @api_version 136 | @login_required 137 | def delete(self, version, role_id=None): 138 | xml = request.args.get('format') 139 | try: 140 | if role_id is None: 141 | data = response_code.NOT_FOUND 142 | return response_result_process(data, xml=xml) 143 | 144 | if role_id is not None: 145 | data = role_permission_singleton.delete_role(role_id) 146 | return response_result_process(data, xml=xml) 147 | 148 | except Exception as e: 149 | lg.error(e) 150 | error_data = response_code.DELETE_DATA_FAIL 151 | return response_result_process(error_data, xml=xml) -------------------------------------------------------------------------------- /api/role/interface_role_permission.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_role_permission.py 6 | @create date: 2019-10-27 14:52 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | from flask import request 13 | from flask_restful import Resource 14 | 15 | from common.common_login_helper import login_required 16 | from common.common_model_enum import modelEnum 17 | from common.common_request_process import req 18 | from common.common_response_code import response_code 19 | from common.common_response_process import response_result_process 20 | from core.role_permission_singleton import role_permission_singleton 21 | 22 | from utils.api_version_verify import api_version 23 | from utils.log_helper import lg 24 | 25 | 26 | class interfaceRolePermission(Resource): 27 | 28 | @api_version 29 | @login_required 30 | def get(self, version, role_id=None): 31 | xml = request.args.get('format') 32 | try: 33 | if role_id is None: 34 | data = response_code.NOT_FOUND 35 | return response_result_process(data, xml=xml) 36 | data = role_permission_singleton.get_role_permission_info(role_id) 37 | body = modelEnum.role_permission.value.get('body') 38 | return response_result_process(data, xml_structure_str=body, xml=xml) 39 | except Exception as e: 40 | lg.error(e) 41 | error_data = response_code.GET_DATA_FAIL 42 | return response_result_process(error_data, xml=xml) 43 | 44 | @api_version 45 | @login_required 46 | def post(self, version, role_id=None): 47 | xml = request.args.get('format') 48 | try: 49 | if role_id is None: 50 | data = response_code.NOT_FOUND 51 | return response_result_process(data, xml=xml) 52 | request_data = req.request_process(request, xml, modelEnum.role_permission.value) 53 | if isinstance(request_data, bool): 54 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 55 | return response_result_process(request_data, xml=xml) 56 | if not request_data: 57 | data = response_code.REQUEST_PARAM_MISSED 58 | return response_result_process(data, xml=xml) 59 | fields = ['per_keys'] 60 | must = req.verify_all_param_must(request_data, fields) 61 | if must: 62 | return response_result_process(must, xml=xml) 63 | par_type = {'per_keys': list} 64 | param_type = req.verify_all_param_type(request_data, par_type) 65 | if param_type: 66 | return response_result_process(param_type, xml=xml) 67 | per_keys = str(request_data.get('per_keys')) 68 | data = role_permission_singleton.add_role_permission(role_id, per_keys) 69 | return response_result_process(data, xml=xml) 70 | except Exception as e: 71 | lg.error(e) 72 | error_data = response_code.ADD_DATA_FAIL 73 | return response_result_process(error_data, xml=xml) 74 | -------------------------------------------------------------------------------- /api/user/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 14:35 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /api/user/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/user/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /api/user/__pycache__/interface_basic.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/user/__pycache__/interface_basic.cpython-36.pyc -------------------------------------------------------------------------------- /api/user/__pycache__/interface_password.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/user/__pycache__/interface_password.cpython-36.pyc -------------------------------------------------------------------------------- /api/user/__pycache__/interface_user.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/user/__pycache__/interface_user.cpython-36.pyc -------------------------------------------------------------------------------- /api/user/interface_basic.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_basic.py 6 | @create date: 2019-10-27 14:54 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from flask import request 12 | from flask_restful import Resource 13 | 14 | from common.common_login_helper import login_required 15 | from common.common_model_enum import modelEnum 16 | from common.common_request_process import req 17 | from common.common_response_code import response_code 18 | from common.common_response_process import response_result_process 19 | from core.user_singleton import user_singleton 20 | 21 | from utils.api_version_verify import api_version 22 | from utils.log_helper import lg 23 | 24 | 25 | class interfaceUserBasic(Resource): 26 | @api_version 27 | @login_required 28 | def put(self, version, user_id=None): 29 | xml = request.args.get('format') 30 | try: 31 | if user_id is None: 32 | data = response_code.NOT_FOUND 33 | return response_result_process(data, xml=xml) 34 | 35 | if user_id is not None: 36 | request_data = req.request_process(request, xml, modelEnum.user.value) 37 | if isinstance(request_data, bool): 38 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 39 | return response_result_process(request_data, xml=xml) 40 | if not request_data: 41 | data = response_code.REQUEST_PARAM_MISSED 42 | return response_result_process(data, xml=xml) 43 | 44 | fields = ['user_name', 'login_name', 'phone', 'email'] 45 | must = req.verify_all_param_must(request_data, fields) 46 | if must: 47 | return response_result_process(must, xml=xml) 48 | par_type = {'user_name': str, 'login_name': str, 'phone': str,'email':str} 49 | param_type = req.verify_all_param_type(request_data, par_type) 50 | if param_type: 51 | return response_result_process(param_type, xml=xml) 52 | 53 | request_data['user_id'] = user_id 54 | data = user_singleton.update_header_user_info(request_data) 55 | return response_result_process(data, xml=xml) 56 | except Exception as e: 57 | lg.error(e) 58 | error_data = response_code.UPDATE_DATA_FAIL 59 | return response_result_process(error_data, xml=xml) -------------------------------------------------------------------------------- /api/user/interface_password.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_password.py 6 | @create date: 2019-10-27 14:53 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from flask import request 12 | from flask_restful import Resource 13 | 14 | from common.common_login_helper import login_required 15 | from common.common_model_enum import modelEnum 16 | from common.common_request_process import req 17 | from common.common_response_code import response_code 18 | from common.common_response_process import response_result_process 19 | from core.user_singleton import user_singleton 20 | 21 | from utils.api_version_verify import api_version 22 | from utils.log_helper import lg 23 | 24 | 25 | class interfacePassword(Resource): 26 | 27 | @api_version 28 | @login_required 29 | def post(self, version, user_id=None): 30 | xml = request.args.get('format') 31 | try: 32 | if user_id is None: 33 | data = response_code.NOT_FOUND 34 | return response_result_process(data, xml=xml) 35 | data = user_singleton.reset_password([user_id]) 36 | return response_result_process(data, xml=xml) 37 | except Exception as e: 38 | lg.error(e) 39 | error_data = response_code.UPDATE_DATA_FAIL 40 | return response_result_process(error_data, xml=xml) 41 | 42 | @api_version 43 | @login_required 44 | def put(self, version, user_id=None): 45 | xml = request.args.get('format') 46 | try: 47 | if user_id is None: 48 | data = response_code.NOT_FOUND 49 | return response_result_process(data, xml=xml) 50 | 51 | if user_id is not None: 52 | request_data = req.request_process(request, xml, modelEnum.user.value) 53 | if isinstance(request_data, bool): 54 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 55 | return response_result_process(request_data, xml=xml) 56 | if not request_data: 57 | data = response_code.REQUEST_PARAM_MISSED 58 | return response_result_process(data, xml=xml) 59 | 60 | fields = ['old_password', 'new_password', 'new_password_ok'] 61 | must = req.verify_all_param_must(request_data, fields) 62 | if must: 63 | return response_result_process(must, xml=xml) 64 | par_type = {'old_password': str, 'new_password': str, 'new_password_ok': str} 65 | param_type = req.verify_all_param_type(request_data, par_type) 66 | if param_type: 67 | return response_result_process(param_type, xml=xml) 68 | 69 | old_pwd = request_data.get('old_password') 70 | new_pwd = request_data.get('new_password') 71 | new_pwd_ok = request_data.get('new_password_ok') 72 | 73 | # 判断输入的数据是否为空 74 | if not all([user_id, old_pwd, new_pwd_ok]): 75 | error_data = response_code.PASS_WORD_INFO_NOT_FILL 76 | return response_result_process(error_data, xml=xml) 77 | # 核对两次输入的密码是否一致 78 | if new_pwd_ok != new_pwd: 79 | error_data = response_code.TWO_PASS_WORD_DIFFERENT 80 | return response_result_process(error_data, xml=xml) 81 | 82 | data = user_singleton.update_user_password(user_id, old_pwd, new_pwd) 83 | return response_result_process(data, xml=xml) 84 | except Exception as e: 85 | lg.error(e) 86 | error_data = response_code.UPDATE_DATA_FAIL 87 | return response_result_process(error_data, xml=xml) -------------------------------------------------------------------------------- /api/user/interface_user.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_user.py 6 | @create date: 2019-10-27 14:53 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from flask import request 12 | from flask_restful import Resource 13 | 14 | from common.common_login_helper import login_required 15 | from common.common_model_enum import modelEnum 16 | from common.common_request_process import req 17 | from common.common_response_process import response_result_process 18 | from core.user_singleton import user_singleton 19 | 20 | from utils.api_version_verify import api_version 21 | from utils.log_helper import lg 22 | from utils.status_code import response_code 23 | 24 | 25 | class interfaceUser(Resource): 26 | @api_version 27 | @login_required 28 | def get(self, version, user_id=None): 29 | xml = request.args.get('format') 30 | try: 31 | body = modelEnum.user.value.get('body') 32 | if user_id is None: 33 | request_data = req.request_process(request, xml, modelEnum.user.value) 34 | if isinstance(request_data, bool): 35 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 36 | return response_result_process(request_data, xml=xml) 37 | if not request_data: 38 | data = user_singleton.get_all_users() 39 | else: 40 | fields = ['current_page', 'page_size'] 41 | must = req.verify_all_param_must(request_data, fields) 42 | if must: 43 | return response_result_process(must, xml=xml) 44 | par_type = {'page_size': int, 'current_page': int, 'search_data': dict} 45 | param_type = req.verify_all_param_type(request_data, par_type) 46 | if param_type: 47 | return response_result_process(param_type, xml=xml) 48 | 49 | current_page, page_size = int(request_data.get('current_page')), int(request_data.get('page_size')) 50 | search_data = request_data.get('search_data') if request_data.get('search_data') else {} 51 | data = user_singleton.get_users_info(current_page, page_size, search_data) 52 | else: 53 | data = user_singleton.get_user_info_by_id(user_id) 54 | 55 | return response_result_process(data, xml_structure_str=body, xml=xml) 56 | except Exception as e: 57 | lg.error(e) 58 | error_data = response_code.GET_DATA_FAIL 59 | return response_result_process(error_data, xml=xml) 60 | 61 | @api_version 62 | @login_required 63 | def post(self, version, user_id=None): 64 | xml = request.args.get('format') 65 | try: 66 | if user_id is not None: 67 | data = response_code.NOT_FOUND 68 | return response_result_process(data, xml=xml) 69 | request_data = req.request_process(request, xml, modelEnum.user.value) 70 | if isinstance(request_data, bool): 71 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 72 | return response_result_process(request_data, xml=xml) 73 | if not request_data: 74 | data = response_code.REQUEST_PARAM_MISSED 75 | return response_result_process(data, xml=xml) 76 | fields = ['user_name', 'login_name', 'user_sex', 'icon', 'position', 'email', 'phone', 'note_info', 'icon', 77 | 'role_ids', 'group_ids', 'dpt_ids'] 78 | must = req.verify_all_param_must(request_data, fields) 79 | if must: 80 | return response_result_process(must, xml=xml) 81 | par_type = {'user_name': str, 'login_name': str, 'user_sex': int, 'icon': str, 'position': str, 82 | 'email': str, 'phone': str, 'note_info': str, 83 | } 84 | param_type = req.verify_all_param_type(request_data, par_type) 85 | if param_type: 86 | return response_result_process(param_type, xml=xml) 87 | 88 | data = user_singleton.add_user(request_data) 89 | return response_result_process(data, xml=xml) 90 | except Exception as e: 91 | lg.error(e) 92 | error_data = response_code.ADD_DATA_FAIL 93 | return response_result_process(error_data, xml=xml) 94 | 95 | @api_version 96 | @login_required 97 | def put(self, version, user_id=None): 98 | xml = request.args.get('format') 99 | try: 100 | if user_id is None: 101 | data = response_code.NOT_FOUND 102 | return response_result_process(data, xml=xml) 103 | 104 | if user_id is not None: 105 | request_data = req.request_process(request, xml, modelEnum.user.value) 106 | if isinstance(request_data, bool): 107 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 108 | return response_result_process(request_data, xml=xml) 109 | if not request_data: 110 | data = response_code.REQUEST_PARAM_MISSED 111 | return response_result_process(data, xml=xml) 112 | 113 | fields = ['user_name', 'login_name', 'user_sex', 'icon', 'position', 'email', 'phone', 'note_info', 114 | 'icon', 115 | 'role_ids', 'group_ids', 'dpt_ids'] 116 | must = req.verify_all_param_must(request_data, fields) 117 | if must: 118 | return response_result_process(must, xml=xml) 119 | par_type = {'user_name': str, 'login_name': str, 'user_sex': int, 'icon': str, 'position': str, 120 | 'email': str, 'phone': str, 'note_info': str, 121 | } 122 | param_type = req.verify_all_param_type(request_data, par_type) 123 | if param_type: 124 | return response_result_process(param_type, xml=xml) 125 | request_data['user_id'] = user_id 126 | data = user_singleton.update_user(request_data) 127 | return response_result_process(data, xml=xml) 128 | except Exception as e: 129 | lg.error(e) 130 | error_data = response_code.UPDATE_DATA_FAIL 131 | return response_result_process(error_data, xml=xml) 132 | 133 | @api_version 134 | @login_required 135 | def delete(self, version, user_id=None): 136 | xml = request.args.get('format') 137 | try: 138 | if user_id is None: 139 | data = response_code.NOT_FOUND 140 | return response_result_process(data, xml=xml) 141 | 142 | if user_id is not None: 143 | data = user_singleton.delete_user([user_id]) 144 | return response_result_process(data, xml=xml) 145 | except Exception as e: 146 | lg.error(e) 147 | error_data = response_code.DELETE_DATA_FAIL 148 | return response_result_process(error_data, xml=xml) 149 | -------------------------------------------------------------------------------- /api/user_group/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 14:35 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /api/user_group/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/user_group/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /api/user_group/__pycache__/interface_user_group.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/user_group/__pycache__/interface_user_group.cpython-36.pyc -------------------------------------------------------------------------------- /api/user_group/__pycache__/interface_user_group_role.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/user_group/__pycache__/interface_user_group_role.cpython-36.pyc -------------------------------------------------------------------------------- /api/user_group/__pycache__/interface_user_group_staff.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/api/user_group/__pycache__/interface_user_group_staff.cpython-36.pyc -------------------------------------------------------------------------------- /api/user_group/interface_user_group.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_user_group.py 6 | @create date: 2019-10-27 14:54 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from flask import request 12 | from flask_restful import Resource 13 | 14 | from common.common_login_helper import login_required 15 | from common.common_model_enum import modelEnum 16 | from common.common_request_process import req 17 | from common.common_response_process import response_result_process 18 | from core.user_group_singleton import user_group_singleton 19 | 20 | from utils.api_version_verify import api_version 21 | from utils.log_helper import lg 22 | from utils.status_code import response_code 23 | 24 | 25 | class interfaceUserGroup(Resource): 26 | @api_version 27 | @login_required 28 | def get(self, version, group_id=None): 29 | xml = request.args.get('format') 30 | try: 31 | body = modelEnum.user_group.value.get('body') 32 | if group_id is None: 33 | request_data = req.request_process(request, xml, modelEnum.user_group.value) 34 | if isinstance(request_data, bool): 35 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 36 | return response_result_process(request_data, xml=xml) 37 | if not request_data: 38 | data = user_group_singleton.get_groups_list(1, 1000000, '') 39 | else: 40 | fields = ['current_page', 'page_size'] 41 | must = req.verify_all_param_must(request_data, fields) 42 | if must: 43 | return response_result_process(must, xml=xml) 44 | par_type = {'page_size': int, 'current_page': int, 'search_data': dict} 45 | param_type = req.verify_all_param_type(request_data, par_type) 46 | if param_type: 47 | return response_result_process(param_type, xml=xml) 48 | 49 | current_page, page_size = int(request_data.get('current_page')), int(request_data.get('page_size')) 50 | search_name = request_data.get('search_name') if request_data.get('search_name') else {} 51 | 52 | data = user_group_singleton.get_groups_list(current_page, page_size, search_name) 53 | 54 | return response_result_process(data, xml_structure_str=body, xml=xml) 55 | 56 | except Exception as e: 57 | lg.error(e) 58 | error_data = response_code.GET_DATA_FAIL 59 | return response_result_process(error_data, xml=xml) 60 | 61 | @api_version 62 | @login_required 63 | def post(self, version, group_id=None): 64 | xml = request.args.get('format') 65 | try: 66 | if group_id is not None: 67 | data = response_code.NOT_FOUND 68 | return response_result_process(data, xml=xml) 69 | request_data = req.request_process(request, xml, modelEnum.user_group.value) 70 | if isinstance(request_data, bool): 71 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 72 | return response_result_process(request_data, xml=xml) 73 | if not request_data: 74 | data = response_code.REQUEST_PARAM_MISSED 75 | return response_result_process(data, xml=xml) 76 | fields = ['name'] 77 | must = req.verify_all_param_must(request_data, fields) 78 | if must: 79 | return response_result_process(must, xml=xml) 80 | par_type = {'name': str, 'desc': str, 'role_ids': list} 81 | param_type = req.verify_all_param_type(request_data, par_type) 82 | if param_type: 83 | return response_result_process(param_type, xml=xml) 84 | 85 | group_name = request_data.get('name') 86 | group_desc = request_data.get('desc') if request_data.get('desc') else '' 87 | role_ids = request_data.get('role_ids') if request_data.get('role_ids') else [] 88 | data = user_group_singleton.add_user_group(group_name, group_desc, role_ids) 89 | return response_result_process(data, xml=xml) 90 | except Exception as e: 91 | lg.error(e) 92 | error_data = response_code.ADD_DATA_FAIL 93 | return response_result_process(error_data, xml=xml) 94 | 95 | @api_version 96 | @login_required 97 | def put(self, version, group_id=None): 98 | xml = request.args.get('format') 99 | try: 100 | if group_id is None: 101 | data = response_code.NOT_FOUND 102 | return response_result_process(data, xml=xml) 103 | 104 | if group_id is not None: 105 | request_data = req.request_process(request, xml, modelEnum.user_group.value) 106 | if isinstance(request_data, bool): 107 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 108 | return response_result_process(request_data, xml=xml) 109 | if not request_data: 110 | data = response_code.REQUEST_PARAM_MISSED 111 | return response_result_process(data, xml=xml) 112 | 113 | fields = ['name'] 114 | must = req.verify_all_param_must(request_data, fields) 115 | if must: 116 | return response_result_process(must, xml=xml) 117 | par_type = {'name': str, 'desc': str, 'role_ids': list} 118 | param_type = req.verify_all_param_type(request_data, par_type) 119 | if param_type: 120 | return response_result_process(param_type, xml=xml) 121 | 122 | group_name = request_data.get('name') 123 | group_desc = request_data.get('desc') 124 | role_ids = request_data.get('role_ids') 125 | infos = { 126 | 'id': group_id, 127 | 'name': group_name if group_name else '', 128 | 'desc': group_desc if group_desc else '', 129 | 'role_ids': role_ids if role_ids else [] 130 | } 131 | 132 | data = user_group_singleton.update_user_group(infos) 133 | return response_result_process(data, xml=xml) 134 | except Exception as e: 135 | lg.error(e) 136 | error_data = response_code.UPDATE_DATA_FAIL 137 | return response_result_process(error_data, xml=xml) 138 | 139 | @api_version 140 | @login_required 141 | def delete(self, version, group_id=None): 142 | xml = request.args.get('format') 143 | try: 144 | if group_id is None: 145 | data = response_code.NOT_FOUND 146 | return response_result_process(data, xml=xml) 147 | 148 | if group_id is not None: 149 | request_data = req.request_process(request, xml, modelEnum.user_group.value) 150 | if isinstance(request_data, bool): 151 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 152 | return response_result_process(request_data, xml=xml) 153 | if not request_data: 154 | data = response_code.REQUEST_PARAM_MISSED 155 | return response_result_process(data, xml=xml) 156 | 157 | fields = ['role_ids'] 158 | must = req.verify_all_param_must(request_data, fields) 159 | if must: 160 | return response_result_process(must, xml=xml) 161 | par_type = {'role_ids': list} 162 | param_type = req.verify_all_param_type(request_data, par_type) 163 | if param_type: 164 | return response_result_process(param_type, xml=xml) 165 | role_ids = request_data.get('role_ids') 166 | data = user_group_singleton.delete_user_group(group_id, role_ids) 167 | return response_result_process(data, xml=xml) 168 | except Exception as e: 169 | lg.error(e) 170 | error_data = response_code.DELETE_DATA_FAIL 171 | return response_result_process(error_data, xml=xml) 172 | -------------------------------------------------------------------------------- /api/user_group/interface_user_group_role.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_user_group_role.py 6 | @create date: 2019-10-27 14:55 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from flask import request 12 | from flask_restful import Resource 13 | 14 | from common.common_login_helper import login_required 15 | from common.common_model_enum import modelEnum 16 | from common.common_request_process import req 17 | from common.common_response_code import response_code 18 | from common.common_response_process import response_result_process 19 | from core.user_group_singleton import user_group_singleton 20 | 21 | from utils.api_version_verify import api_version 22 | from utils.log_helper import lg 23 | 24 | 25 | class interfaceUserGroupRole(Resource): 26 | @api_version 27 | @login_required 28 | def get(self, version, group_id=None): 29 | xml = request.args.get('format') 30 | try: 31 | if group_id is None: 32 | data = response_code.NOT_FOUND 33 | return response_result_process(data, xml=xml) 34 | data = user_group_singleton.get_user_group_roles(group_id) 35 | body = modelEnum.department.value.get('body') 36 | return response_result_process(data, xml_structure_str=body, xml=xml) 37 | except Exception as e: 38 | lg.error(e) 39 | error_data = response_code.GET_DATA_FAIL 40 | return response_result_process(error_data, xml=xml) 41 | 42 | @api_version 43 | @login_required 44 | def post(self, version, group_id=None): 45 | xml = request.args.get('format') 46 | try: 47 | if group_id is None: 48 | data = response_code.NOT_FOUND 49 | return response_result_process(data, xml=xml) 50 | request_data = req.request_process(request, xml, modelEnum.user_group.value) 51 | if isinstance(request_data, bool): 52 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 53 | return response_result_process(request_data, xml=xml) 54 | if not request_data: 55 | data = response_code.REQUEST_PARAM_MISSED 56 | return response_result_process(data, xml=xml) 57 | fields = ['role_ids'] 58 | must = req.verify_all_param_must(request_data, fields) 59 | if must: 60 | return response_result_process(must, xml=xml) 61 | par_type = {'role_ids': list} 62 | param_type = req.verify_all_param_type(request_data, par_type) 63 | if param_type: 64 | return response_result_process(param_type, xml=xml) 65 | role_ids = str(request_data.get('role_ids')) 66 | data = user_group_singleton.add_user_group_roles(group_id, role_ids) 67 | return response_result_process(data, xml=xml) 68 | except Exception as e: 69 | lg.error(e) 70 | error_data = response_code.ADD_DATA_FAIL 71 | return response_result_process(error_data, xml=xml) 72 | 73 | @api_version 74 | @login_required 75 | def delete(self, version, group_id=None): 76 | xml = request.args.get('format') 77 | try: 78 | if group_id is None: 79 | data = response_code.NOT_FOUND 80 | return response_result_process(data, xml=xml) 81 | request_data = req.request_process(request, xml, modelEnum.user_group.value) 82 | if isinstance(request_data, bool): 83 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 84 | return response_result_process(request_data, xml=xml) 85 | if not request_data: 86 | data = response_code.REQUEST_PARAM_MISSED 87 | return response_result_process(data, xml=xml) 88 | fields = ['role_ids'] 89 | must = req.verify_all_param_must(request_data, fields) 90 | if must: 91 | return response_result_process(must, xml=xml) 92 | par_type = {'role_ids': list} 93 | param_type = req.verify_all_param_type(request_data, par_type) 94 | if param_type: 95 | return response_result_process(param_type, xml=xml) 96 | role_ids = str(request_data.get('role_ids')) 97 | data = user_group_singleton.remove_user_group_roles(group_id, role_ids) 98 | return response_result_process(data, xml=xml) 99 | 100 | except Exception as e: 101 | lg.error(e) 102 | error_data = response_code.DELETE_DATA_FAIL 103 | return response_result_process(error_data, xml=xml) 104 | -------------------------------------------------------------------------------- /api/user_group/interface_user_group_staff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: interface_user_group_staff.py 6 | @create date: 2019-10-27 14:59 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from flask import request 12 | from flask_restful import Resource 13 | 14 | from common.common_login_helper import login_required 15 | from common.common_model_enum import modelEnum 16 | from common.common_request_process import req 17 | from common.common_response_code import response_code 18 | from common.common_response_process import response_result_process 19 | from core.user_group_singleton import user_group_singleton 20 | 21 | from utils.api_version_verify import api_version 22 | from utils.log_helper import lg 23 | 24 | 25 | class interfaceUserGroupStaff(Resource): 26 | @api_version 27 | @login_required 28 | def get(self, version, group_id=None): 29 | xml = request.args.get('format') 30 | try: 31 | if group_id is None: 32 | data = response_code.NOT_FOUND 33 | return response_result_process(data, xml=xml) 34 | 35 | request_data = req.request_process(request, xml, modelEnum.user_group.value) 36 | if isinstance(request_data, bool): 37 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 38 | return response_result_process(request_data, xml=xml) 39 | if not request_data: 40 | data = response_code.REQUEST_PARAM_MISSED 41 | return response_result_process(data, xml=xml) 42 | fields = ['current_page', 'page_size'] 43 | must = req.verify_all_param_must(request_data, fields) 44 | if must: 45 | return response_result_process(must, xml=xml) 46 | par_type = {'page_size': int, 'current_page': int} 47 | param_type = req.verify_all_param_type(request_data, par_type) 48 | if param_type: 49 | return response_result_process(param_type, xml=xml) 50 | 51 | current_page, page_size = int(request_data.get('current_page')), int(request_data.get('page_size')) 52 | data = user_group_singleton.get_users_by_group_id(group_id, current_page, page_size) 53 | body = modelEnum.department.value.get('body') 54 | return response_result_process(data, xml_structure_str=body, xml=xml) 55 | except Exception as e: 56 | lg.error(e) 57 | error_data = response_code.GET_DATA_FAIL 58 | return response_result_process(error_data, xml=xml) 59 | 60 | @api_version 61 | @login_required 62 | def post(self, version, group_id=None): 63 | xml = request.args.get('format') 64 | try: 65 | if group_id is None: 66 | data = response_code.NOT_FOUND 67 | return response_result_process(data, xml=xml) 68 | request_data = req.request_process(request, xml, modelEnum.user_group.value) 69 | if isinstance(request_data, bool): 70 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 71 | return response_result_process(request_data, xml=xml) 72 | if not request_data: 73 | data = response_code.REQUEST_PARAM_MISSED 74 | return response_result_process(data, xml=xml) 75 | fields = ['user_ids'] 76 | must = req.verify_all_param_must(request_data, fields) 77 | if must: 78 | return response_result_process(must, xml=xml) 79 | par_type = {'user_ids': list} 80 | param_type = req.verify_all_param_type(request_data, par_type) 81 | if param_type: 82 | return response_result_process(param_type, xml=xml) 83 | user_ids = str(request_data.get('user_ids')) 84 | data = user_group_singleton.add_user_to_group(group_id, user_ids) 85 | return response_result_process(data, xml=xml) 86 | except Exception as e: 87 | lg.error(e) 88 | error_data = response_code.ADD_DATA_FAIL 89 | return response_result_process(error_data, xml=xml) 90 | 91 | @api_version 92 | @login_required 93 | def delete(self, version, group_id=None): 94 | xml = request.args.get('format') 95 | try: 96 | if group_id is None: 97 | data = response_code.NOT_FOUND 98 | return response_result_process(data, xml=xml) 99 | request_data = req.request_process(request, xml, modelEnum.user_group.value) 100 | if isinstance(request_data, bool): 101 | request_data = response_code.REQUEST_PARAM_FORMAT_ERROR 102 | return response_result_process(request_data, xml=xml) 103 | if not request_data: 104 | data = response_code.REQUEST_PARAM_MISSED 105 | return response_result_process(data, xml=xml) 106 | fields = ['user_ids'] 107 | must = req.verify_all_param_must(request_data, fields) 108 | if must: 109 | return response_result_process(must, xml=xml) 110 | par_type = {'user_ids': list} 111 | param_type = req.verify_all_param_type(request_data, par_type) 112 | if param_type: 113 | return response_result_process(param_type, xml=xml) 114 | user_ids = str(request_data.get('user_ids')) 115 | data = user_group_singleton.remove_user_from_group(group_id, user_ids) 116 | return response_result_process(data, xml=xml) 117 | 118 | except Exception as e: 119 | lg.error(e) 120 | error_data = response_code.DELETE_DATA_FAIL 121 | return response_result_process(error_data, xml=xml) 122 | -------------------------------------------------------------------------------- /common/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 13:27 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /common/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/common/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /common/__pycache__/common_api_version.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/common/__pycache__/common_api_version.cpython-36.pyc -------------------------------------------------------------------------------- /common/__pycache__/common_log.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/common/__pycache__/common_log.cpython-36.pyc -------------------------------------------------------------------------------- /common/__pycache__/common_login_helper.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/common/__pycache__/common_login_helper.cpython-36.pyc -------------------------------------------------------------------------------- /common/__pycache__/common_model_enum.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/common/__pycache__/common_model_enum.cpython-36.pyc -------------------------------------------------------------------------------- /common/__pycache__/common_request_process.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/common/__pycache__/common_request_process.cpython-36.pyc -------------------------------------------------------------------------------- /common/__pycache__/common_response_code.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/common/__pycache__/common_response_code.cpython-36.pyc -------------------------------------------------------------------------------- /common/__pycache__/common_response_log.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/common/__pycache__/common_response_log.cpython-36.pyc -------------------------------------------------------------------------------- /common/__pycache__/common_response_process.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/common/__pycache__/common_response_process.cpython-36.pyc -------------------------------------------------------------------------------- /common/__pycache__/common_time.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/common/__pycache__/common_time.cpython-36.pyc -------------------------------------------------------------------------------- /common/common_api_version.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: common_api_version.py 6 | @create date: 2019-10-27 13:41 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from enum import Enum, unique 12 | 13 | 14 | @unique 15 | class apiVersion(Enum): 16 | """ 17 | api 版本枚举 18 | """ 19 | version1 = 'v1' 20 | version2 = 'v2' 21 | -------------------------------------------------------------------------------- /common/common_log.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: common_log.py 6 | @create date: 2019-10-27 14:40 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | 13 | 14 | from functools import wraps 15 | from flask import request, g, jsonify 16 | 17 | from db.logger.db_log_mgr import db_log 18 | from utils.fun_name_to_enum import functionName 19 | from utils.status_code import response_code 20 | 21 | 22 | def operation_log(description=''): 23 | """ 24 | 操作日志记录 25 | :param description: 26 | :return: 27 | """ 28 | def _log(fun): 29 | @wraps(fun) 30 | def wrapper(*args, **kwargs): 31 | response = fun() 32 | ip_address = request.remote_addr 33 | user_key = g.user_key 34 | if user_key==None: 35 | return jsonify(response_code.LOGIN_TIMEOUT.value) 36 | model = getattr(functionName, description).value 37 | if response.json.get('code') == 200: 38 | ip_address = request.remote_addr 39 | level = 0 40 | des = model + functionName.success.value 41 | user_key = g.user_key 42 | db_log.add_operation_log(user_key, ip_address, level, des) 43 | else: 44 | level = 1 45 | des = model + functionName.fail.value 46 | db_log.add_operation_log(user_key, ip_address, level, des) 47 | return response 48 | return wrapper 49 | return _log 50 | -------------------------------------------------------------------------------- /common/common_login_helper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: common_login_helper.py 6 | @create date: 2019-10-27 14:49 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | from functools import wraps 13 | from os import abort 14 | from flask import request, g 15 | 16 | from utils.auth_helper import Auth 17 | 18 | 19 | def login_required(func): 20 | @wraps(func) 21 | def wrapper(*args, **kwargs): 22 | user_key = Auth.identify(request) 23 | if user_key > 0: 24 | g.user_key = user_key 25 | ###token验证,服务于restful 26 | return func(*args, **kwargs) 27 | else: 28 | abort(401) 29 | 30 | return wrapper 31 | 32 | 33 | ###权限验证装饰器 34 | def login_super(func): 35 | @wraps(func) 36 | def wrapper(): 37 | if g.user_key != 1: 38 | abort(403) 39 | return func() 40 | 41 | return wrapper 42 | -------------------------------------------------------------------------------- /common/common_model_enum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: common_model_enum.py 6 | @create date: 2019-10-27 14:39 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | from enum import Enum, unique 13 | 14 | 15 | @unique 16 | class modelEnum(Enum): 17 | """ 18 | 请求模块枚举类 19 | """ 20 | 21 | user = {'root': 'users', 'body': 'user'} 22 | department = {'root': 'departments', 'body': 'department'} 23 | role = {'root': 'roles', 'body': 'role'} 24 | user_group = {'root': 'user_groups', 'body': 'user_group'} 25 | login = {'root': 'logins', 'body': 'login'} 26 | permission = {'root': 'permissions', 'body': 'permission'} 27 | role_permission = {'root': 'role_permissions', 'body': 'role_permission'} 28 | -------------------------------------------------------------------------------- /common/common_request_process.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: common_request_process.py 6 | @create date: 2019-10-27 14:08 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description:请求处理 10 | """ 11 | 12 | import json 13 | from json import JSONDecodeError 14 | 15 | from common.common_api_version import apiVersion 16 | from common.common_response_code import response_code 17 | from common.common_response_log import ResponseLog 18 | from common.common_response_process import response_result_process 19 | from utils.log_helper import lg 20 | from utils.xml_json_process import xml_to_json, is_none 21 | 22 | 23 | class requestProcess(object): 24 | """ 25 | 请求处理 26 | """ 27 | 28 | def _xml_request(self, request, model_json=None): 29 | """ 30 | 处理xml请求参数为json格式 31 | :param data: 请求 32 | :return: 33 | """ 34 | try: 35 | data = request.data 36 | temp = data.decode('utf-8') 37 | if temp == '': 38 | return {} 39 | try: 40 | param_temp = xml_to_json(temp) 41 | except Exception as e: 42 | return response_code.REQUEST_PARAM_FORMAT_ERROR 43 | param = json.loads(param_temp) 44 | 45 | root = model_json.get('root') 46 | body = model_json.get('body') 47 | 48 | root_data = param.get(root) 49 | request_param = None 50 | if root_data: 51 | body_data = root_data.get(body) 52 | if body_data: 53 | if isinstance(body_data,list): 54 | request_param = is_none(root_data) 55 | else: 56 | request_param = is_none(body_data) 57 | if root_data is None: 58 | s_body_data = param.get(body) 59 | if s_body_data: 60 | if isinstance(is_none(s_body_data), dict): 61 | request_param = s_body_data 62 | 63 | if isinstance(request_param, list) or request_param is None: 64 | return False 65 | return request_param 66 | except Exception as e: 67 | lg.error(e) 68 | return False 69 | 70 | def _json_request(self, request): 71 | """ 72 | 处理json请求参数问题 73 | :param request: 请求 74 | :return: 75 | """ 76 | try: 77 | request_data = request.data 78 | req_str = request_data.decode() 79 | if req_str == '': 80 | return {} 81 | data = json.loads(req_str) 82 | if isinstance(data, list): 83 | return False 84 | return data 85 | except JSONDecodeError as e: 86 | lg.error(e) 87 | return False 88 | 89 | def verify_one_param_type(self, param_name, value, type=None): 90 | """ 91 | 验证某个参数的类型 92 | :param param_name: 验证的参数名称 93 | :param value: 验证的参数的值 94 | :param type: 验证的参数的类型 95 | :return: 96 | """ 97 | try: 98 | if type == float: 99 | v = None 100 | if isinstance(value,str): 101 | v = eval(value) 102 | if isinstance(value,int): 103 | v = value 104 | if isinstance(value,float): 105 | v = value 106 | if isinstance(v, float): 107 | pass 108 | else: 109 | code = response_code.BAD_REQUEST 110 | code['msg'] = ResponseLog.wrong_param_type(param_name, type.__name__) 111 | return code 112 | if type == int: 113 | v = None 114 | if isinstance(value, str): 115 | v = eval(value) 116 | if isinstance(value, float): 117 | v = value 118 | if isinstance(value, int): 119 | v = value 120 | if isinstance(v, int): 121 | pass 122 | else: 123 | code = response_code.BAD_REQUEST 124 | code['msg'] = ResponseLog.wrong_param_type(param_name, type.__name__) 125 | return code 126 | if type == str: 127 | if isinstance(value, str): 128 | pass 129 | else: 130 | code = response_code.BAD_REQUEST 131 | code['msg'] = ResponseLog.wrong_param_type(param_name, type.__name__) 132 | return code 133 | 134 | if type == list: 135 | if isinstance(value, list): 136 | pass 137 | else: 138 | code = response_code.BAD_REQUEST 139 | code['msg'] = ResponseLog.wrong_param_type(param_name, type.__name__) 140 | return code 141 | if type == dict: 142 | if isinstance(value, dict): 143 | pass 144 | else: 145 | code = response_code.BAD_REQUEST 146 | code['msg'] = ResponseLog.wrong_param_type(param_name, type.__name__) 147 | return code 148 | except Exception as e: 149 | lg.error(e) 150 | code = response_code.BAD_REQUEST 151 | code['msg'] = ResponseLog.wrong_param_type(param_name, type.__name__) 152 | return code 153 | 154 | def verify_one_param_must(self, request_data: dict, param): 155 | """ 156 | 验证某个参数是否必填 157 | :param data: 请求的数据 158 | :param param: 本验证的字段 159 | :return: 160 | """ 161 | if request_data.get(param) is None: 162 | code = response_code.BAD_REQUEST 163 | code['msg'] = ResponseLog.wrong_param_must(param) 164 | return code 165 | else: 166 | pass 167 | 168 | def verify_param_page(self, data, param): 169 | """ 170 | 验证是否有分页信息 171 | :param data: 验证的请求数据 172 | :param param: 是否有page字段 173 | :return: 174 | """ 175 | page_data = data.get(param) 176 | if page_data.get('page_size') is not None: 177 | if page_data.get('current_page') is None: 178 | code = response_code.BAD_REQUEST 179 | code['msg'] = ResponseLog.wrong_param_must('current_page') 180 | return code 181 | if page_data.get('current_page') is not None: 182 | if page_data.get('page_size') is None: 183 | code = response_code.BAD_REQUEST 184 | code['msg'] = ResponseLog.wrong_param_must('page_size') 185 | return code 186 | 187 | def request_process(self, request, xml=None, model_json=None): 188 | """ 189 | 请求参数获取 190 | :param request: 请求 191 | :param xml: 请求响应类型 是否是xml 默认是json 192 | :return: 193 | """ 194 | if xml is None: 195 | return self._json_request(request) 196 | if xml == 'xml': 197 | return self._xml_request(request, model_json) 198 | 199 | def verify_all_param_must(self, request_data: dict, fields: list): 200 | """ 201 | 批量验证是否是必传参数 202 | :param request_data: 请求的参数数据 203 | :param fields: ['a','b'] 204 | :return: 205 | """ 206 | for i in fields: 207 | must = self.verify_one_param_must(request_data, i) 208 | if must: 209 | return must 210 | else: 211 | pass 212 | 213 | def verify_all_param_type(self, request_data: dict, fields: dict): 214 | """ 215 | 批量验证参数的类型 216 | :param request_data: 请求的参数数据 217 | :param fields: {'a':str,'b':int} 218 | :return: 219 | """ 220 | 221 | for k, v in request_data.items(): 222 | param_type = self.verify_one_param_type(k, v, fields.get(k)) 223 | if param_type: 224 | return param_type 225 | else: 226 | pass 227 | 228 | def verify_version(self, version, xml=None): 229 | """ 230 | API版本验证 231 | :param version: 版本信息 232 | :param xml: 是否是xml 233 | :return: 234 | """ 235 | if version == apiVersion.version1.value: 236 | return True, True 237 | else: # 版本信息不存在给的提示 238 | result = response_code.REQUEST_VERSION_ISEXISTENCE 239 | return False, response_result_process(result, xml=xml) 240 | 241 | 242 | req = requestProcess() 243 | -------------------------------------------------------------------------------- /common/common_response_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: common_response_code.py 6 | @create date: 2019-10-27 14:10 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from enum import Enum, unique 12 | 13 | 14 | @unique 15 | class ErrorCodeEnum(Enum): 16 | SUCCESS = 200 17 | LOGIN_IS_FAIL = 1001 18 | PASS_WORD_INFO_NOT_FILL = 1002 19 | TWO_PASS_WORD_DIFFERENT = 1003 20 | OLD_PASS_WORD_IS_NOT_FAIL = 1004 21 | LOGIN_FAIL = 1005 22 | PASS_WORD_RESET_FAIL = 1006 23 | USER_NOT_EXIST = 1007 24 | IMPORT_CSV_FAIL = 1008 25 | IMPORT_CSV_SUCCESS = 1009 26 | RECORD_EXIST = 1010 27 | ADD_DATA_FAIL = 1011 28 | UPDATE_DATA_FAIL = 1012 29 | DELETE_DATA_FAIL = 1013 30 | GET_DATA_FAIL = 1014 31 | REQUEST_VERSION_ISEXISTENCE = 1015 32 | ALREADY_HANDLED = 1016 33 | DATA_IS_NOT_EXIST = 1017 34 | REQUEST_PARAM_MISSED = 1018 35 | EQUEST_PARAM_FORMAT_ERROR = 1019 36 | OPENTSDB_ERROR = 1020 37 | DATA_BASE_ERROR = 1021 38 | NOT_FOUND = 404 39 | BAD_REQUEST = 400 40 | FORBIDDEND = 403 41 | WRONGVALUE = 1022 42 | CHECK_EXIST_ERROR = 1023 43 | EXCEPTION_DB = 1024 44 | 45 | 46 | class responseCode(object): 47 | 48 | @property 49 | def SUCCESS(self): 50 | return {'code': 200, 'msg': '请求成功'} 51 | 52 | @property 53 | def LOGIN_IS_FAIL(self): 54 | return {'code': 1001, 'msg': '用户名或者密码错误'} 55 | 56 | @property 57 | def PASS_WORD_INFO_NOT_FILL(self): 58 | return {'code': 1002, 'msg': '密码信息填写完整'} 59 | 60 | @property 61 | def TWO_PASS_WORD_DIFFERENT(self): 62 | return {'code': 1003, 'msg': '两次密码不一致'} 63 | 64 | @property 65 | def OLD_PASS_WORD_IS_NOT_FAIL(self): 66 | return {'code': 1004, 'msg': '旧密码不正确'} 67 | 68 | @property 69 | def LOGIN_FAIL(self): 70 | return {'code': 1005, 'msg': '登录失败请联系管理员'} 71 | 72 | @property 73 | def PASS_WORD_RESET_FAIL(self): 74 | return {'code': 1006, 'msg': '密码重置失败'} 75 | 76 | @property 77 | def USER_NOT_EXIST(self): 78 | return {'code': 1007, 'msg': '用户不存在'} 79 | 80 | @property 81 | def IMPORT_CSV_FAIL(self): 82 | return {'code': 1008, 'msg': '导入数据失败'} 83 | 84 | @property 85 | def IMPORT_CSV_SUCCESS(self): 86 | return {'code': 1009, 'msg': '导入数据成功'} 87 | 88 | @property 89 | def RECORD_EXIST(self): 90 | return {'code': 1010, 'msg': '记录已存在'} 91 | 92 | @property 93 | def ADD_DATA_FAIL(self): 94 | return {'code': 1011, 'msg': '添加数据失败'} 95 | 96 | @property 97 | def UPDATE_DATA_FAIL(self): 98 | return {'code': 1012, 'msg': '修改数据失败'} 99 | 100 | @property 101 | def DELETE_DATA_FAIL(self): 102 | return {'code': 1013, 'msg': '删除数据失败'} 103 | 104 | @property 105 | def GET_DATA_FAIL(self): 106 | return {'code': 1014, 'msg': '获取数据失败'} 107 | 108 | @property 109 | def REQUEST_VERSION_ISEXISTENCE(self): 110 | return {'code': 1015, 'msg': '请求的版本不存在'} 111 | 112 | @property 113 | def ALREADY_HANDLED(self): 114 | return {'code': 1016, 'msg': '参数类型错误'} 115 | 116 | @property 117 | def DATA_IS_NOT_EXIST(self): 118 | return {'code': 1017, 'msg': '数据不存在'} 119 | 120 | @property 121 | def REQUEST_PARAM_MISSED(self): 122 | return {'code': 1018, 'msg': '请求参数缺失'} 123 | 124 | @property 125 | def REQUEST_PARAM_FORMAT_ERROR(self): 126 | return {'code': 1019, 'msg': '请求参数格式错误'} 127 | 128 | @property 129 | def OPENTSDB_ERROR(self): 130 | return {'code': 1020, 'msg': 'opentsdb服务器错误'} 131 | 132 | @property 133 | def DATA_BASE_ERROR(self): 134 | return {'code': 1021, 'msg': "数据库连接失败"} 135 | 136 | @property 137 | def NOT_FOUND(self): 138 | return {'code': 404, 'msg': 'HTTP 404 Not Found'} 139 | 140 | @property 141 | def BAD_REQUEST(self): 142 | return {'code': 400, 'msg': 'HTTP 400 Bad Request'} 143 | 144 | @property 145 | def FORBIDDEND(self): 146 | return {'code': 403, 'msg': 'HTTP 403 Forbidden'} 147 | 148 | @property 149 | def WRONGVALUE(self): 150 | return {'code': 1022, 'msg': '参数值超出规定范围'} 151 | 152 | @property 153 | def CHECK_EXIST_ERROR(self): 154 | return {'code': 1023, 'msg': '验证数据错误'} 155 | 156 | @property 157 | def EXCEPTION_DB(self): 158 | return {'code': 1024, 'msg': '数据库操作异常'} 159 | 160 | def get_struct_by_error_code(self, error_code): 161 | if error_code == ErrorCodeEnum.SUCCESS: 162 | return self.SUCCESS 163 | if error_code == ErrorCodeEnum.LOGIN_IS_FAIL: 164 | return self.LOGIN_IS_FAIL 165 | if error_code == ErrorCodeEnum.PASS_WORD_INFO_NOT_FILL: 166 | return self.PASS_WORD_INFO_NOT_FILL 167 | if error_code == ErrorCodeEnum.TWO_PASS_WORD_DIFFERENT: 168 | return self.TWO_PASS_WORD_DIFFERENT 169 | if error_code == ErrorCodeEnum.OLD_PASS_WORD_IS_NOT_FAIL: 170 | return self.OLD_PASS_WORD_IS_NOT_FAIL 171 | if error_code == ErrorCodeEnum.LOGIN_FAIL: 172 | return self.LOGIN_FAIL 173 | if error_code == ErrorCodeEnum.PASS_WORD_RESET_FAIL: 174 | return self.PASS_WORD_RESET_FAIL 175 | if error_code == ErrorCodeEnum.USER_NOT_EXIST: 176 | return self.PASS_WORD_RESET_FAIL 177 | if error_code == ErrorCodeEnum.IMPORT_CSV_FAIL: 178 | return self.IMPORT_CSV_FAIL 179 | if error_code == ErrorCodeEnum.IMPORT_CSV_SUCCESS: 180 | return self.IMPORT_CSV_SUCCESS 181 | if error_code == ErrorCodeEnum.RECORD_EXIST: 182 | return self.RECORD_EXIST 183 | if error_code == ErrorCodeEnum.ADD_DATA_FAIL: 184 | return self.ADD_DATA_FAIL 185 | if error_code == ErrorCodeEnum.UPDATE_DATA_FAIL: 186 | return self.UPDATE_DATA_FAIL 187 | if error_code == ErrorCodeEnum.DELETE_DATA_FAIL: 188 | return self.DELETE_DATA_FAIL 189 | if error_code == ErrorCodeEnum.GET_DATA_FAIL: 190 | return self.DELETE_DATA_FAIL 191 | if error_code == ErrorCodeEnum.REQUEST_VERSION_ISEXISTENCE: 192 | return self.REQUEST_VERSION_ISEXISTENCE 193 | if error_code == ErrorCodeEnum.ALREADY_HANDLED: 194 | return self.ALREADY_HANDLED 195 | if error_code == ErrorCodeEnum.DATA_IS_NOT_EXIST: 196 | return self.DATA_IS_NOT_EXIST 197 | if error_code == ErrorCodeEnum.REQUEST_PARAM_MISSED: 198 | return self.REQUEST_PARAM_MISSED 199 | if error_code == ErrorCodeEnum.REQUEST_PARAM_FORMAT_ERROR: 200 | return self.REQUEST_PARAM_FORMAT_ERROR 201 | if error_code == ErrorCodeEnum.OPENTSDB_ERROR: 202 | return self.OPENTSDB_ERROR 203 | if error_code == ErrorCodeEnum.DATA_BASE_ERROR: 204 | return self.DATA_BASE_ERROR 205 | if error_code == ErrorCodeEnum.NOT_FOUND: 206 | return self.NOT_FOUND 207 | if error_code == ErrorCodeEnum.BAD_REQUEST: 208 | return self.BAD_REQUEST 209 | if error_code == ErrorCodeEnum.FORBIDDEND: 210 | return self.FORBIDDEND 211 | if error_code == ErrorCodeEnum.WRONGVALUE: 212 | return self.WRONGVALUE 213 | if error_code == ErrorCodeEnum.CHECK_EXIST_ERROR: 214 | return self.CHECK_EXIST_ERROR 215 | if error_code == ErrorCodeEnum.EXCEPTION_DB: 216 | return self.EXCEPTION_DB 217 | 218 | 219 | response_code = responseCode() 220 | -------------------------------------------------------------------------------- /common/common_response_log.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: common_response_log.py 6 | @create date: 2019-10-27 14:11 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description:响应日志处理 10 | """ 11 | 12 | class ResponseLog: 13 | """ 14 | 响应提示信息公共类 15 | """ 16 | 17 | @staticmethod 18 | def null_value(param): 19 | """ 20 | 参数值为空时,提示信息 21 | :param param: 22 | :return: 23 | """ 24 | return "param '%s' is null ." % (param) 25 | 26 | @staticmethod 27 | def wrong_value(param, value): 28 | """ 29 | 参数值无效时,提示信息 30 | :param param: 31 | :param value: 32 | :return: 33 | """ 34 | return "param '%s' improper value %s." % (param, value) 35 | 36 | @staticmethod 37 | def record_exist(unique_key, value): 38 | """ 39 | 参数值已经存在时,提示信息 40 | :param unique_key: 41 | :param value: 42 | :return: 43 | """ 44 | return "unique key '(%s,%s)' is exist." % (unique_key, value) 45 | 46 | @staticmethod 47 | def delete_record_in_use(code, value): 48 | """ 49 | 删除的数据在使用时,提示信息 50 | :param code: 51 | :param value: 52 | :return: 53 | """ 54 | return "delete record '%s:%s' is in use." % (code, value) 55 | 56 | @staticmethod 57 | def wrong_time_format(key, value): 58 | """ 59 | 时间格式错误,提示信息 60 | :param key: 字段名称 61 | :param value: 时间戳 62 | :return: 63 | """ 64 | return "improper time format: param '%s:[%s]'." % (key, value) 65 | 66 | @staticmethod 67 | def wrong_param_type(key, value): 68 | """ 69 | 参数类型错误提示消息 70 | :param key: 参数名称 71 | :param value: 参数类型 72 | :return: 73 | """ 74 | return "The argument '%s must be %s'." % (key, value) 75 | 76 | @staticmethod 77 | def wrong_param_must(key): 78 | """ 79 | 验证参数是否必填 80 | :param key: 81 | :return: 82 | """ 83 | return "The argument '" + key + "' is missed." 84 | 85 | @staticmethod 86 | def database_exception(error_code=None): 87 | """ 88 | 数据库操作异常,提示信息 89 | :return: 90 | """ 91 | if error_code: 92 | if error_code == 1022: 93 | msg = "Failure of database connection." 94 | elif error_code == 1024: 95 | msg = "Database operation exception." 96 | else: 97 | msg = "" 98 | return msg 99 | else: 100 | return "" 101 | 102 | @staticmethod 103 | def operation_success(data_name=None, operation_name=None): 104 | """ 105 | 添加数据成功,提示消息 106 | :param data_name: 107 | :param operation_name: 108 | :return: 109 | """ 110 | return "%s data %s success." % (data_name, operation_name) 111 | 112 | @staticmethod 113 | def record_not_exist(data, value): 114 | """ 115 | 数据不存在,提示消息 116 | :param data: 117 | :param value: 118 | :return: 119 | """ 120 | return "Data '(%s,%s)' is not exist." % (data, value) 121 | 122 | @staticmethod 123 | def mission_db_exist(sat_code): 124 | """ 125 | 与卫星代号同名的任务数据库存在,提示消息 126 | :param sat_code: 127 | :return: 128 | """ 129 | return "Mission db with this '%s' name already exists" % (sat_code) 130 | 131 | @staticmethod 132 | def relation_not_exist(v1, v2): 133 | """ 134 | 数据关联关系不存在,提示消息 135 | :param data: 136 | :param value: 137 | :return: 138 | """ 139 | return "Relationship between '(%s,%s)' is not exist." % (v1, v2) 140 | -------------------------------------------------------------------------------- /common/common_response_process.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: common_response_process.py 6 | @create date: 2019-10-27 14:38 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | from flask import jsonify, Response 13 | 14 | 15 | from utils.xml_json_process import json_to_xml 16 | 17 | 18 | def response_json(data): 19 | """ 20 | json响应处理 21 | :param data: json数据 22 | :return: 23 | """ 24 | return jsonify(data) 25 | 26 | def response_xml(data,root=None): 27 | """ 28 | xml响应处理 29 | :param data: json数据 30 | :param root: xml数据的根 31 | :return: 32 | """ 33 | if root is not None: 34 | json_str = {"response":data} 35 | data['data'] = {root:data.get('data')} 36 | else: 37 | json_str = {"response": data} 38 | info = json_to_xml(json_str) 39 | return Response(info, mimetype="text/xml") 40 | 41 | 42 | def response_result_process(data,xml_structure_str=None,xml=None): 43 | """ 44 | 响应数据处理 45 | :param data: 响应数据 46 | :param xml_structure_str: 响应为xml结构的时候 有数据结构的时候需要传,无数据结构的时候就不需要传 47 | :param xml: 是否是xml响应 48 | :return: 49 | """ 50 | if xml is None and xml_structure_str is not None: 51 | return response_json(data) 52 | elif xml is None and xml_structure_str is None: 53 | return response_json(data) 54 | elif xml is not None and xml_structure_str is None: 55 | return response_xml(data) 56 | else: 57 | # return response_xml(data, xmlEnum.__getattr__(xml_structure_str).value) 58 | return response_xml(data, xml_structure_str) 59 | 60 | -------------------------------------------------------------------------------- /common/common_time.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: common_time.py 6 | @create date: 2019-10-27 14:46 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from datetime import datetime 12 | 13 | from functools import wraps 14 | import time 15 | 16 | 17 | def get_max_time(): 18 | return datetime.strptime("2100-01-01 01:01:01", "%Y-%m-%d %H:%M:%S") 19 | 20 | 21 | def string_to_date(string): 22 | """ 23 | #把字符串转成date 24 | :param string: 25 | :return: 26 | """ 27 | return datetime.strptime(string, "%Y-%m-%d") 28 | 29 | 30 | def string_to_datetime(string): 31 | """ 32 | #把字符串转成datetime 33 | :param string: 34 | :return: 35 | """ 36 | return datetime.strptime(string, "%Y-%m-%d %H:%M:%S") 37 | 38 | 39 | def date_to_time(timestring): 40 | """ 41 | date转时间戳 42 | :param timestring: 43 | :return: 44 | """ 45 | return time.mktime(time.strptime(timestring, '%Y-%m-%d')) 46 | 47 | 48 | def datetime_to_time(timestring): 49 | """ 50 | datetime转时间戳 51 | :param timestring: 52 | :return: 53 | """ 54 | return time.mktime(time.strptime(timestring, '%Y-%m-%d %H:%M:%S')) 55 | 56 | 57 | def get_system_datetime(): 58 | """ 59 | 获取系统当前时间 60 | :return: 61 | """ 62 | sys_time = time.time() 63 | result_time = int(sys_time * 1000) 64 | return result_time 65 | 66 | 67 | def get_system_datetime_str(): 68 | """ 69 | 获取系统当前时间 70 | :return: 71 | """ 72 | str_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) 73 | return str_time 74 | 75 | 76 | # 把时间戳转成字符串形式 77 | def time_to_datetime(stamp): 78 | """ 79 | 时间戳转datetime 80 | :param stamp: 81 | :return: 82 | """ 83 | time_stamp = int(stamp / 1000) 84 | return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_stamp)) 85 | 86 | 87 | #####计算函数耗时装饰圈 88 | def fun_time(func): 89 | @wraps(func) 90 | def wrapper(*args, **kargs): 91 | start_time = time.time() 92 | tempfun = func(*args, **kargs) 93 | end_time = time.time() 94 | real_time = end_time - start_time 95 | print("function name=%s,args=%s,kargs=%s real time is %s" % (func.__name__, args, kargs, real_time)) 96 | return tempfun 97 | 98 | return wrapper 99 | -------------------------------------------------------------------------------- /config.ini: -------------------------------------------------------------------------------- 1 | # 项目启动的配置 2 | [IPCONFIG] 3 | host = 0.0.0.0 4 | port = 8099 5 | debug = True 6 | 7 | # 项目数据库配置 8 | [DB] 9 | type = mysql 10 | user = root 11 | pwd = 123456 12 | host = 127.0.0.1 13 | port = 3306 14 | name = user_api 15 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | ****************************************************************************** 5 | * Copyright (C) 2016~2019 成都原子数据科技有限公司 6 | * 版权所有。 7 | ****************************************************************************** 8 | @file_name: config.py 9 | @author:lzl 10 | @create date: 2019/10/21 0021 11:13 11 | @description: 12 | @update date: 13 | @file url: 14 | @git path: 15 | """ 16 | 17 | import configparser 18 | 19 | 20 | class Configuration(): 21 | """ 22 | 读取数据库配置文件中的的用户信息,密码信息,主机信息,端口信息,数据库名称信息 23 | config_path: 是配置文件的路径 24 | """ 25 | COPYRIGHT = '版权所有 ©2018-2019 成都原子数据科技有限公司.' 26 | EMAIL = 'surport@atomdatatech.com' 27 | 28 | def __init__(self, config_file_path='./config.ini'): 29 | try: 30 | self.config_file_path = config_file_path 31 | self.conf = configparser.ConfigParser() 32 | self.conf.read(config_file_path) 33 | except Exception as e: 34 | # 文件不存在或者读取失败 35 | print(str(e)) 36 | 37 | def write_file(self): 38 | """ 39 | 保存对配置文件的修改 40 | :return: 41 | """ 42 | self.conf.write(open(self.config_file_path, 'r+')) 43 | 44 | def get_version(self): 45 | """ 46 | 获取版本信息 47 | :return: 48 | """ 49 | return self.conf.get('Version', 'version') 50 | 51 | def get_build(self): 52 | """ 53 | 获取build信息 54 | :return: 55 | """ 56 | return self.conf.get('Version', 'build') 57 | 58 | @staticmethod 59 | def get_company_email(self): 60 | """ 61 | 获取公司邮箱 62 | :return: 63 | """ 64 | return Configuration.EMAIL 65 | 66 | @staticmethod 67 | def get_copyright(self): 68 | """ 69 | 获取版权信息 70 | :return: 71 | """ 72 | return Configuration.COPYRIGHT 73 | 74 | def get_database_name(self, database_section='DB'): 75 | """ 76 | 获取数据库的名称 77 | :param database_section:配置文档区域名称 如IPCONFIG、DB1 78 | :return: 79 | """ 80 | if self.conf.has_section(database_section): 81 | return self.conf.get(database_section, 'name') 82 | return None 83 | 84 | def get_option(self, section, option): 85 | """ 86 | 获取配置文件选项 87 | :param section: 88 | :param option: 89 | :return: 90 | """ 91 | return self.conf.get(section, option) 92 | 93 | def set_option(self, section, option, value): 94 | """ 95 | 设置配置文件选项 96 | :param section:配置文档区域名称 如IPCONFIG、DB1 97 | :param option:配置文档区域中选项名称,如name、host 98 | :param value: 选项的值 99 | :return: 100 | """ 101 | # 修改选项 102 | self.conf.set(section, option, value) 103 | # 保存修改 104 | self.write_file() 105 | 106 | def get_database_configuration(self, database_section): 107 | """ 108 | 获取数据库连接详细信息 109 | :param database_section:配置文档区域名称 如IPCONFIG、DB1 110 | :return: 111 | """ 112 | return { 113 | 'name': self.conf.get(database_section, 'name'), 114 | 'type':self.conf.get(database_section, 'type'), 115 | 'host':self.conf.get(database_section, 'host'), 116 | 'port':self.conf.get(database_section, 'port'), 117 | 'user':self.conf.get(database_section, 'user'), 118 | 'pwd': self.conf.get(database_section, 'pwd') 119 | } 120 | 121 | def get_start_config(self, section='IPCONFIG'): 122 | """ 123 | 获取启动配置 124 | :param role_section: 125 | :return: 126 | """ 127 | 128 | host = self.conf.get(section, 'host') 129 | port = self.conf.get(section, 'port') 130 | debug = self.conf.get(section, 'debug') 131 | 132 | return host, port, debug 133 | 134 | 135 | configuration = Configuration() 136 | 137 | 138 | class Config(object): 139 | DEBUG = False 140 | TESTING = False 141 | SECRET_KEY = 'USER-API' 142 | ###flask-session 143 | SESSION_TYPE = 'null' 144 | SESSION_KEY_PREFIX = "session:" 145 | ########如果设置为True的话,session的生命为 permanent_session_lifetime 秒(默认是31天) 146 | ########如果设置为Flase的话,那么当用户关闭浏览器时,session便被删除了。permanent_session_lifetime也会生效 147 | SESSION_PERMANENT = False 148 | PERMANENT_SESSION_LIFETIME = 60 * 60 * 24 * 31 149 | 150 | @staticmethod 151 | def init_app(app): 152 | pass 153 | 154 | 155 | class DevelopmentConfig(Config): 156 | DEBUG = True 157 | DB_CONFIG = {'host': '192.168.1.60', 'port': 3306, 'user': 'devuser', 'password': 'root', 'db': 'data', 158 | 'connect_timeout': 300, 'read_timeout': 300, 'write_timeout': 300, 159 | 'charset': 'utf8'} 160 | pass 161 | 162 | 163 | class TestingConfig(Config): 164 | TESTING = False 165 | DB_CONFIG = {'host': '192.168.1.60', 'port': 3306, 'user': 'devuser', 'password': 'root', 'db': 'data', 166 | 'connect_timeout': 300, 'read_timeout': 300, 'write_timeout': 300, 167 | 'charset': 'utf8'} 168 | pass 169 | 170 | 171 | class ProductionConfig(Config): 172 | DEBUG = False 173 | DB_CONFIG = {'host': '192.168.1.60', 'port': 3306, 'user': 'devuser', 'password': 'root', 'db': 'data', 174 | 'connect_timeout': 300, 'read_timeout': 300, 'write_timeout': 300, 175 | 'charset': 'utf8'} 176 | pass 177 | 178 | 179 | config = { 180 | 'development': DevelopmentConfig, 181 | 'testing': TestingConfig, 182 | 'production': ProductionConfig, 183 | 'default': DevelopmentConfig 184 | } 185 | -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 13:26 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /core/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/core/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /core/__pycache__/department_singleton.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/core/__pycache__/department_singleton.cpython-36.pyc -------------------------------------------------------------------------------- /core/__pycache__/role_permission_singleton.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/core/__pycache__/role_permission_singleton.cpython-36.pyc -------------------------------------------------------------------------------- /core/__pycache__/user_group_singleton.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/core/__pycache__/user_group_singleton.cpython-36.pyc -------------------------------------------------------------------------------- /core/__pycache__/user_singleton.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/core/__pycache__/user_singleton.cpython-36.pyc -------------------------------------------------------------------------------- /core/department_singleton.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: department_singleton.py 6 | @create date: 2019-10-27 15:01 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from db.department.db_department_mgr import db_department_mgr 12 | 13 | __all__ = {"departmentSingleton"} 14 | 15 | 16 | class departmentSingleton(): 17 | 18 | def get_department(self): 19 | """ 20 | 获取所有的部门信息 21 | :return: 22 | """ 23 | return db_department_mgr.get_all_department() 24 | 25 | def add_department(self, dpt_name, dpt_p_id): 26 | """ 27 | 添加部门 28 | :param dpt_name: 部门名称 29 | :param dpt_p_id: 上级部门id 30 | :return: 31 | """ 32 | return db_department_mgr.add_department(dpt_name, dpt_p_id) 33 | 34 | def update_department(self, dpt_id, dpt_name, p_id): 35 | """ 36 | 修改部门 37 | :param dpt_id: 部门ID 38 | :param dpt_name: 部门名称 39 | :return: 40 | """ 41 | return db_department_mgr.update_department(dpt_id, dpt_name, p_id) 42 | 43 | def delete_department(self, dpt_id): 44 | """ 45 | 删除部门 46 | :param dpt_id: 部门ID 47 | :return: 48 | """ 49 | return db_department_mgr.delete_department(dpt_id) 50 | 51 | def get_dpt_user_info_by_id(self, dpt_id, current_page, page_size): 52 | """ 53 | 获取部门下的员工信息 54 | :param dpt_id: 55 | :param current_page: 56 | :param page_size: 57 | :return: 58 | """ 59 | return db_department_mgr.get_dpt_user_info_by_id(dpt_id, current_page, page_size) 60 | 61 | def department_add_staff(self, dpt_id, user_ids): 62 | """ 63 | 给部门下面添加员工 64 | :param dpt_id: 65 | :param user_ids: 66 | :return: 67 | """ 68 | return db_department_mgr.department_add_staff(dpt_id, user_ids) 69 | 70 | def delete_department_staff(self, dpt_id, user_ids): 71 | """ 72 | 删除部门下的员工信息 73 | :param dpt_id: 74 | :param user_ids: 75 | :return: 76 | """ 77 | return db_department_mgr.delete_department_staff(dpt_id, user_ids) 78 | 79 | def update_department_staff(self, dpt_id, user_ids): 80 | """ 81 | 删除部门下的员工信息 82 | :param dpt_id: 83 | :param user_ids: 84 | :return: 85 | """ 86 | return db_department_mgr.update_department_staff(dpt_id, user_ids) 87 | 88 | 89 | department_singleton = departmentSingleton() 90 | -------------------------------------------------------------------------------- /core/role_permission_singleton.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: role_permission_singleton.py 6 | @create date: 2019-10-27 15:02 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from db.role.db_role_permission_mgr import db_role_permission 12 | 13 | __all__ = {"rolePermissionSingleton"} 14 | 15 | 16 | class rolePermissionSingleton: 17 | """ 18 | """ 19 | 20 | def get_user_permission_info(self): 21 | """ 22 | 获取所有的权限信息 23 | :return: 24 | """ 25 | return db_role_permission.get_user_permission_info() 26 | 27 | def get_data_permission_info(self): 28 | """ 29 | 获取所有的权限信息 30 | :return: 31 | """ 32 | return db_role_permission.get_data_permission_info() 33 | 34 | def get_all_roles(self): 35 | """ 36 | 获取所有的角色信息 37 | :return: 38 | """ 39 | return db_role_permission.get_all_roles() 40 | 41 | def get_pages_roles(self, current_page, page_size, search_data): 42 | """ 43 | 获取所有的角色信息 44 | :return: 45 | """ 46 | return db_role_permission.get_pages_roles(current_page, page_size, search_data) 47 | 48 | def add_role(self, role_name, note_info): 49 | """ 50 | 添加角色 51 | :param role_name: 角色名称 52 | :param note_info: 备注信息 53 | :return: 54 | """ 55 | return db_role_permission.add_role(role_name, note_info) 56 | 57 | def update_role(self, role_id, role_name, note_info): 58 | """ 59 | 修改角色 60 | :param role_id: 角色ID 61 | :param role_name: 角色名称 62 | :param note_info: 备注信息 63 | :return: 64 | """ 65 | return db_role_permission.update_role(role_id, role_name, note_info) 66 | 67 | def delete_role(self, role_id): 68 | """ 69 | 删除角色 70 | :param role_id: 71 | :return: 72 | """ 73 | return db_role_permission.delete_role(role_id) 74 | 75 | def add_role_permission(self, role_id, per_keys): 76 | """ 77 | 给角色添加权限 78 | :param role_id: 角色id 79 | :param per_keys: 权限列表 80 | :return: 81 | """ 82 | return db_role_permission.add_role_permission(role_id, per_keys) 83 | 84 | def get_role_permission_info(self, role_id): 85 | """ 86 | 根据角色ID获取权限列表 87 | :param role_id: 角色ID 88 | :return: 89 | """ 90 | return db_role_permission.get_role_permission_info(role_id) 91 | 92 | def add_grafana_permission(self, param): 93 | """ 94 | 95 | :param param: 96 | :return: 97 | """ 98 | return db_role_permission.add_grafana_permission(param) 99 | 100 | def get_grafana_permission(self, user_id): 101 | """ 102 | 获取grafana权限 103 | :param param: 104 | :return: 105 | """ 106 | return db_role_permission.get_grafana_permission(user_id) 107 | 108 | 109 | role_permission_singleton = rolePermissionSingleton() 110 | -------------------------------------------------------------------------------- /core/user_group_singleton.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: user_group_singleton.py 6 | @create date: 2019-10-27 15:03 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from db.user_group.db_group_mgr import db_group_mgr 12 | 13 | __all__ = ["UserGroupSingleton"] 14 | 15 | 16 | class UserGroupSingleton: 17 | """ 18 | """ 19 | 20 | def add_user_group(self, group_name, group_desc, role_ids): 21 | """ 22 | 添加用户组 23 | :return: 24 | """ 25 | return db_group_mgr.add_group(group_name, group_desc, role_ids) 26 | 27 | def update_user_group(self, group_json): 28 | """ 29 | 编辑更新用户组 30 | :return: 31 | """ 32 | return db_group_mgr.upd_group(group_json) 33 | 34 | def delete_user_group(self, group_id, role_ids): 35 | """ 36 | 通过用户组删除用户组,并将该用户组下得所有用户移除用户组 37 | :param id: 38 | :return: 39 | """ 40 | return db_group_mgr.del_group(group_id, role_ids) 41 | 42 | def remove_user_from_group(self, group_id, user_ids): 43 | """ 44 | 从用户组移除用户 45 | :param id: 46 | :return: 47 | """ 48 | return db_group_mgr.remove_group_users(group_id, user_ids) 49 | 50 | def add_user_to_group(self, group_id, user_ids): 51 | """ 52 | 添加用户到用户组 53 | :param group_id: 54 | :param user_ids: 55 | :return: 56 | """ 57 | return db_group_mgr.add_user_to_group(group_id, user_ids) 58 | 59 | def get_groups_list(self, current_page, page_size, search_name): 60 | """ 61 | 获取所有组列表 62 | :return: 63 | """ 64 | return db_group_mgr.get_group_list(current_page, page_size, search_name) 65 | 66 | def get_users_by_group_id(self, group_id, current_page, page_size): 67 | """ 68 | 获取用户组下得所有用户 69 | :return: 70 | """ 71 | return db_group_mgr.get_user_by_group_id(group_id, current_page, page_size) 72 | 73 | def get_user_group_roles(self, group_id): 74 | """ 75 | 获取用户组的角色信息 76 | :param group_id: 77 | :return: 78 | """ 79 | return db_group_mgr.get_user_group_roles(group_id) 80 | 81 | def add_user_group_roles(self, group_id, role_ids): 82 | """ 83 | 添加用户组角色 84 | :param group_id: 85 | :param role_ids: 86 | :return: 87 | """ 88 | return db_group_mgr.add_user_group_roles(group_id, role_ids) 89 | 90 | def remove_user_group_roles(self, group_id, role_ids): 91 | """ 92 | 删除用户组角色 93 | :param group_id: 94 | :param role_ids: 95 | :return: 96 | """ 97 | return db_group_mgr.remove_user_group_roles(group_id, role_ids) 98 | 99 | 100 | user_group_singleton = UserGroupSingleton() 101 | -------------------------------------------------------------------------------- /core/user_singleton.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: user_singleton.py 6 | @create date: 2019-10-27 15:03 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | from db.user.db_user_mgr import user_mgr 13 | 14 | __all__ = {"UserSingleton"} 15 | 16 | 17 | class UserSingleton: 18 | """" 19 | """ 20 | 21 | def get_users_info(self, page, page_num, search_data=None): 22 | """ 23 | 获取所有用户信息 24 | :return:返回用户信息json 25 | """ 26 | 27 | return user_mgr.get_user_list(page, page_num, search_data) 28 | 29 | def get_user_info_by_id(self, id): 30 | """ 31 | 通过用户ID获取用户信息 32 | :param id: 用户id 33 | :return: 返回当前用户JSON 34 | """ 35 | return user_mgr.get_user_by_id_(id) 36 | 37 | def get_user_role_by_id(self, id): 38 | """ 39 | 通过ID获取用户角色 40 | :param id:用户ID 41 | :return:返回用户权限JSON 42 | """ 43 | 44 | def delete_user_by_id(self): 45 | """ 46 | 通过用户ID删除用户 47 | :return:返回成功失败 48 | """ 49 | 50 | def set_default_password_by_id(self, id): 51 | """ 52 | 通过用户ID设置用户得默认密码 53 | :param id: 54 | :return: 55 | """ 56 | 57 | def add_user(self, user_info): 58 | """ 59 | 添加用户 60 | :param user_info: 61 | :return: 62 | """ 63 | 64 | return user_mgr.add_user(user_info) 65 | 66 | def update_user(self, user_info): 67 | """ 68 | 更新用户 69 | :param userinfo: 70 | :return: 71 | """ 72 | return user_mgr.upd_user(user_info) 73 | 74 | def user_login(self, username, password): 75 | """ 76 | 用户登录验证,如果正确返回用户ID,如果不正确返回0 77 | :param username: 用户名 78 | :param password: 用户密码 79 | :return: 正确返回用户ID,如果不正确返回0 80 | """ 81 | 82 | def reset_password(self, user_id): 83 | """ 84 | 重置密码 85 | :param user_id: 86 | :return: 87 | """ 88 | return user_mgr.pwd_reset(user_id) 89 | 90 | def update_user_password(self, user_id, old_pwd, new_pwd): 91 | """ 92 | 修改用户密码 93 | :return: 94 | """ 95 | return user_mgr.pwd_modify(user_id, old_pwd, new_pwd) 96 | 97 | def update_header_user_info(self, ser_info): 98 | """ 99 | 更新用户指定的信息 100 | :param ser_info: 101 | :return: 102 | """ 103 | return user_mgr.upd_user_partial(ser_info) 104 | 105 | def get_all_users(self): 106 | """ 107 | 获取所有的用户信息 108 | :return: 109 | """ 110 | return user_mgr.get_all_user() 111 | 112 | def delete_user(self, user_ids): 113 | """ 114 | 删除用户 115 | :param user_id: 116 | :return: 117 | """ 118 | return user_mgr.del_user(user_ids) 119 | 120 | 121 | user_singleton = UserSingleton() 122 | -------------------------------------------------------------------------------- /db/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 13:26 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /db/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /db/__pycache__/base.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/__pycache__/base.cpython-36.pyc -------------------------------------------------------------------------------- /db/__pycache__/connection_pool.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/__pycache__/connection_pool.cpython-36.pyc -------------------------------------------------------------------------------- /db/base.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: base.py 6 | @create date: 2019-10-27 14:23 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description:数据库操作基础类 10 | """ 11 | 12 | 13 | class DbBase(object): 14 | """ 数据库操作基础类""" 15 | 16 | def select_exec(self, conn, sql): 17 | """ 18 | 查询执行 19 | :param conn: 20 | :param sql: 21 | :return: 22 | """ 23 | try: 24 | conn.cur.execute(sql) 25 | conn.conn.commit() 26 | return conn.cur.rowcount 27 | except Exception as ex: 28 | conn.conn.rollback() 29 | raise ex 30 | 31 | def updete_exec(self, conn, sql): 32 | try: 33 | conn.cur.execute(sql) 34 | conn.conn.commit() 35 | return conn.cur.rowcount 36 | except Exception as ex: 37 | conn.conn.rollback() 38 | raise ex 39 | 40 | def delete_exec(self, conn, sql): 41 | try: 42 | conn.cur.execute(sql) 43 | conn.conn.commit() 44 | return conn.cur.rowcount 45 | except Exception as ex: 46 | conn.conn.rollback() 47 | raise ex 48 | 49 | def insert_exec(self, conn, sql): 50 | try: 51 | conn.cur.execute(sql) 52 | conn.conn.commit() 53 | return conn.cur.rowcount 54 | except Exception as ex: 55 | conn.conn.rollback() 56 | raise ex 57 | 58 | def execute_sql_return_count(self, conn, sql, args=None): 59 | """ 60 | 增删改,返回受影响的行数 61 | :param sql: insert into tb_user(FuserName, Fpwd) values( % s, % s) 62 | :param args: tuple, list 63 | :return: 64 | """ 65 | 66 | try: 67 | conn.cur.execute(sql, args) 68 | conn.conn.commit() 69 | return conn.cur.rowcount 70 | except Exception as ex: 71 | conn.conn.rollback() 72 | raise ex 73 | 74 | def execute_many_data(self, conn, sql, data): 75 | """ 76 | 批量插入数据 77 | :param sql: 为insert语句 78 | :param data: 为list 格式为[[每一条数据],[]] 79 | :return: 80 | """ 81 | try: 82 | conn.cur.executemany(sql, data) 83 | conn.conn.commit() 84 | return conn.cur.rowcount 85 | except Exception as ex: 86 | conn.conn.rollback() 87 | raise ex 88 | 89 | def execute_many_sql_return_count(self, conn, sql, loop_args=None): 90 | """ 91 | 批量添加,返回受影响的行数 92 | :param sql: insert into tb_user(FuserName, Fpwd) values( % s, % s) 93 | :param args: loop(args) 94 | :return: 95 | """ 96 | try: 97 | conn.cur.executemany(sql, loop_args) 98 | conn.conn.commit() 99 | return conn.cur.rowcount 100 | except Exception as ex: 101 | conn.conn.rollback() 102 | raise ex 103 | 104 | def execute_update_sql(self, conn, sql): 105 | """ 106 | 更新数据 107 | :param sql: 108 | :return: 109 | """ 110 | try: 111 | conn.cur.execute(sql) 112 | conn.conn.commit() 113 | except: 114 | conn.conn.rollback() 115 | 116 | def execute_del_data(self, conn, sql): 117 | """ 118 | 删除数据 119 | :param conn: 120 | :param sql: 121 | :return: 122 | """ 123 | try: 124 | conn.cur.execute(sql) 125 | conn.conn.commit() 126 | except Exception as e: 127 | conn.conn.rollback() 128 | 129 | def execute_fetch_one(self, conn, sql, args=None): 130 | """循环执行查询语句,返回查询数据 131 | :param sql: select user,pass from tb7 where user=%s and pass=%s 132 | :param loop_args: tuple, list 133 | :return: dict 134 | """ 135 | try: 136 | conn.cur.execute(sql, args) 137 | result = conn.cur.fetchone() 138 | if result: 139 | return result 140 | # return dict(result) 141 | else: 142 | return {} 143 | except Exception as ex: 144 | raise ex 145 | 146 | def execute_fetch_all(self, conn, sql, args=None): 147 | """循环执行查询语句,返回查询数据 148 | :param sql: select user,pass from tb7 where user=%s and pass=%s 149 | :param loop_args: tuple, list 4444 150 | :return: list[dict] 151 | """ 152 | # 请使用db_session连接数据库 153 | try: 154 | conn.cur.execute(sql, args) 155 | result = conn.cur.fetchall() 156 | if result: 157 | return result 158 | else: 159 | return [] 160 | except Exception as ex: 161 | raise ex 162 | 163 | def excuteLoopFetchAll(self, conn, keys, loop_sql, loop_args): 164 | """循环执行查询语句,更具keys返回查询集合 165 | :param keys: tuple, list 166 | :param sql: loop(select user,pass from tb7 where user=%s and pass=%s) 167 | :param loop_args: 二维数组 168 | :return: dict[list[dict]] 169 | """ 170 | try: 171 | result = {} 172 | for key, sql, args in zip(keys, loop_sql, loop_args): 173 | if args: 174 | count = conn.cur.execute(sql, args) 175 | if count > 0: 176 | data = conn.cur.fetchall() 177 | result[key] = [dict(x) for x in data] 178 | else: 179 | result[key] = [] 180 | return result 181 | except Exception as ex: 182 | raise ex 183 | 184 | def execute_fetch_pages(self, conn, sql_count, sql, page_index, page_size, args=None): 185 | """ 186 | 分页查询语句 187 | :param conn: 188 | :param sql_count: 189 | :param sql: 190 | :param page_index: 191 | :param page_size: 192 | :param args: 193 | :return: 194 | """ 195 | try: 196 | conn.cur.execute(sql_count, args) 197 | total_count = conn.cur.fetchone().get('count(*)') 198 | conn.cur.execute(sql, args) 199 | result_data = conn.cur.fetchall() 200 | if len(result_data) == 0: 201 | result_data = [] 202 | page_list_json = {"page_size": page_size, "page_index": page_index, "total_count": total_count, 203 | "total_page": 1, "data_list": result_data} 204 | if total_count % page_size == 0: 205 | total_page = total_count / page_size 206 | else: 207 | total_page = math.ceil(total_count / page_size) 208 | page_list_json["total_page"] = total_page 209 | return page_list_json 210 | except Exception as ex: 211 | raise ex 212 | 213 | def create_insert_sql(self, db_name, table_name, fields, tuple): 214 | """ 215 | 插入语句sql组装 216 | :param fields: 要插入的字段 217 | :param tuple: 要插入的数据 218 | :param table_name: 被插入的表的名称 219 | :param db_name: 被插入数据的数据库名称 220 | :return: 221 | """ 222 | sql = 'insert into %s.%s %s values %s' % (db_name, table_name, fields, tuple) 223 | 224 | return sql 225 | 226 | def create_update_sql(self, db_name, table_name, fields, tuple, condition): 227 | """ 228 | 修改数据的sql 229 | :param db_name: 数据库名称 230 | :param table_name: 数据表名称 231 | :param fields: 需要修改的字段列表 232 | :param tuple: 需要修改字段对应的值 233 | :param condition: 以什么条件去修改 234 | :return: 235 | """ 236 | sql = "update %s.%s set " % (db_name, table_name) 237 | for index, filed in enumerate(fields): 238 | if filed != fields[-1]: 239 | if isinstance(tuple[index], str): 240 | sql += filed + "=" + "'" + str(tuple[index]) + "'" + "," 241 | else: 242 | sql += filed + "=" + str(tuple[index]) + "," 243 | else: 244 | if isinstance(tuple[index], str): 245 | sql += filed + "=" + "'" + str(tuple[index]) + "'" + " " 246 | else: 247 | sql += filed + "=" + str(tuple[index]) + " " 248 | sql += "where " + condition 249 | return sql 250 | 251 | def create_delete_sql(self, db_name, table_name, condition): 252 | """ 253 | 删除数据的sql 254 | :param db_name: 255 | :param table_name: 256 | :param condition: 257 | :return: 258 | """ 259 | sql = "delete from %s.%s where %s" % (db_name, table_name, condition) 260 | return sql 261 | 262 | def create_get_page_sql(self, db_name, table_name, fields, start_page, page_size, condition=None): 263 | """ 264 | 分页sql语句 265 | :param db_name: 266 | :param table_name: 267 | :param fields: 268 | :param start_page: 269 | :param page_size: 270 | :param condition: 271 | :return: 查询sql和计数sql 272 | """ 273 | sql_count = "select count(*) from %s.%s" % (db_name, table_name) 274 | sql = "select %s from %s.%s" % (fields, db_name, table_name) 275 | if (condition == None) or (condition == "") or (condition == " "): 276 | sql += " limit %s,%s" % (start_page, page_size) 277 | sql_count = sql_count 278 | else: 279 | sql += " where " + condition + " limit %s,%s" % (start_page, page_size) 280 | sql_count += " where " + condition 281 | 282 | # print(sql_count) 283 | # print(sql) 284 | return sql_count, sql 285 | 286 | def create_select_sql(self, db_name, table_name, fields, condition=None): 287 | """ 288 | 获取某个字段的查询语句 289 | :param db_name: 290 | :param table_name: 291 | :param fields: 292 | :param condition: 293 | :return: sql 294 | """ 295 | 296 | sql = "select %s from %s.%s" % (fields, db_name, table_name) 297 | if condition == None: 298 | sql = sql 299 | else: 300 | sql += " where " + condition 301 | return sql 302 | 303 | def create_get_relation_sql(self, db_name=None, table_name=None, fields=None, relations=None, condition=None): 304 | """ 305 | 创建关联查询sql语句 306 | :param db_name: 307 | :param table_name: 308 | :param fields: 309 | :param relations: 310 | :param condition: 311 | :return: 312 | """ 313 | if db_name: 314 | sql = "select %s from %s.%s" % (fields, db_name, table_name) 315 | if relations: 316 | for relation in relations: 317 | sql += " left join " + db_name + "." + relation["table_name"] + " on " + relation["join_condition"] 318 | if condition is None: 319 | sql = sql 320 | else: 321 | sql += " where " + condition 322 | else: 323 | sql = "select %s from %s" % (fields, table_name) 324 | if relations: 325 | for relation in relations: 326 | sql += " left join " + relation["table_name"] + " on " + relation["join_condition"] 327 | if condition is None: 328 | sql = sql 329 | else: 330 | sql += " where " + condition 331 | 332 | return sql 333 | 334 | def create_get_relation_page_sql(self, db_name, table_name, fields, relations, start_num, page_size, 335 | condition=None): 336 | """ 337 | 分页,多表关联查询sql语句 338 | :param db_name: 339 | :param table_name: 340 | :param fields: 341 | :param relations:关联关系 342 | :param start_page: 343 | :param page_size: 344 | :param condition: 345 | :return: 查询sql和计数sql 346 | """ 347 | sql_count = "select count(*) from %s.%s" % (db_name, table_name) 348 | sql = "select %s from %s.%s" % (fields, db_name, table_name) 349 | if relations: 350 | for relation in relations: 351 | sql += " left join " + db_name + "." + relation["table_name"] + " on " + relation["join_condition"] 352 | if condition == None: 353 | sql += " limit %s,%s" % (start_num, page_size) 354 | 355 | sql_count = sql_count 356 | else: 357 | sql += " where " + condition + " limit %s,%s" % (start_num, page_size) 358 | sql_count += " where " + condition 359 | 360 | return sql_count, sql 361 | 362 | def create_batch_insert_sql(self, db_name, table_name, insert_data_list): 363 | """ 364 | 生成批量插入数据的sql 365 | :param db_name: 366 | :param table_name: 367 | :param insert_data_list: 368 | :return: sql和对应的插入数据 369 | 例如: 370 | sql: 'insert into db_name.table_name (c_id,c_no) values (%s,%s)' 371 | 数据: [[1, 2], [2, 3]] 372 | """ 373 | insert_data = [] 374 | sql = """insert into %s.%s (""" % (db_name, table_name) 375 | if insert_data_list: 376 | for s in insert_data_list: 377 | insert_data.append(list(s.values())) 378 | 379 | fields = list(insert_data_list[0].keys()) 380 | index = 0 381 | # 添加 sql 前面的的字段 382 | for i in fields: 383 | if index == len(fields) - 1: 384 | sql += '%s' % i 385 | else: 386 | sql += '%s,' % i 387 | index += 1 388 | sql += ') values (' 389 | # 添加sql values后面的字段 390 | flag = 0 391 | for _ in fields: 392 | if flag == len(fields) - 1: 393 | sql += '%s' 394 | else: 395 | sql += '%s,' 396 | flag += 1 397 | 398 | sql += ')' 399 | else: 400 | sql += ')' 401 | insert_data = [] 402 | 403 | return sql, insert_data 404 | 405 | def create_vague_condition_sql(self, search_data): 406 | """ 407 | 生成模糊查询搜索条件 408 | :param search_data: 409 | 例如: 410 | search_data = {'c_name':2,'c_no':2} 411 | search_data = json.dumps(search_data) 412 | :return: 组合好的条件 413 | 例如: cmd_name like '%2%' and cmd_no like '%2%' 414 | """ 415 | search_data_dict = json.loads(search_data) 416 | index = 0 417 | condition = ' ' 418 | if len(search_data_dict) == 0: 419 | return "" 420 | for k, v in search_data_dict.items(): 421 | if index == len(search_data_dict) - 1: 422 | condition += str(k) + " like '%" + str(v) + "%'" 423 | else: 424 | condition += str(k) + " like '%" + str(v) + "%'" + " and " 425 | index += 1 426 | return condition 427 | 428 | def insert_sql(self, db_name, table_name, data_dict): 429 | """ 430 | 创建插入语句 431 | :param db_name: 数据库名 432 | :param table_name: 表名 433 | :param json_object: 字典数据 434 | :return: sql 435 | """ 436 | insert_data = [] 437 | fields = "(" 438 | flag = 1 439 | for key, value in data_dict.items(): 440 | if flag == len(data_dict): 441 | fields += key 442 | else: 443 | fields += key + "," 444 | insert_data.append(value) 445 | flag += 1 446 | fields += ")" 447 | if len(insert_data) == 1: 448 | insert_data = str(tuple(insert_data)) 449 | insert_data = insert_data.replace(',', '') 450 | else: 451 | insert_data = str(tuple(insert_data)) 452 | sql = 'insert into %s.%s %s values %s' % (db_name, table_name, fields, insert_data) 453 | 454 | return sql 455 | 456 | def update_sql(self, db_name, table_name, data_dict, condition): 457 | """ 458 | 修改数据的sql 459 | :param db_name: 数据库名称 460 | :param table_name: 数据表名称 461 | :param json_object: 字典数据 462 | :param condition: 以什么条件去修改 463 | 例如: 'S_KEY=6 and S_NO = 1001' 464 | :return: sql 465 | """ 466 | sql = "update %s.%s set " % (db_name, table_name) 467 | flag = 1 468 | for key, value in data_dict.items(): 469 | if flag == len(data_dict): 470 | if isinstance(value, str): 471 | sql += key + " = " + "'" + value + "'" 472 | else: 473 | sql += key + " = " + str(value) 474 | else: 475 | if isinstance(value, str): 476 | sql += key + " = " + "'" + value + "'" + "," 477 | else: 478 | sql += key + " = " + str(value) + "," 479 | flag += 1 480 | 481 | sql += " where " + condition 482 | 483 | return sql 484 | -------------------------------------------------------------------------------- /db/connection_pool.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: connection_pool.py 6 | @create date: 2019-10-27 14:29 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | import pymysql 13 | from DBUtils.PooledDB import PooledDB 14 | from config import configuration 15 | 16 | 17 | class MysqlConn(object): 18 | """ 19 | MySql线程池 20 | """ 21 | __my_pool = None 22 | 23 | ###以何种方式返回数据集 24 | TUPLE_CURSOR_MODE = pymysql.cursors.Cursor 25 | DICT_DICTCURSOR_MODE = pymysql.cursors.DictCursor 26 | TUPLE_SSCURSOR_MODE = pymysql.cursors.SSCursor 27 | DICT_SSDICTCURSOR_MODE = pymysql.cursors.SSDictCursor 28 | 29 | def __init__(self, database_name='DB', cur_type=pymysql.cursors.DictCursor): 30 | self.conn = MysqlConn.get_connection(database_name) 31 | self.cur = self.conn.cursor(cursor=cur_type) 32 | 33 | @staticmethod 34 | def get_connection(database_name): 35 | """ 36 | 获取数据库连接 37 | :return: 38 | """ 39 | database = configuration.get_database_configuration(database_name) 40 | host = database.get('host') 41 | port = int(database.get('port')) 42 | user = database.get('user') 43 | password = database.get('pwd') 44 | if MysqlConn.__my_pool is None: 45 | MysqlConn.__my_pool = PooledDB(creator=pymysql, mincached=1, maxcached=10, maxconnections=100, 46 | blocking=True, 47 | host=host, port=port, user=user, passwd=password, 48 | charset='utf8') 49 | return MysqlConn.__my_pool.connection() 50 | 51 | def close(self): 52 | """ 53 | 释放当前连接 54 | :return: 55 | """ 56 | self.conn.close() 57 | self.cur.close() 58 | -------------------------------------------------------------------------------- /db/department/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 14:44 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /db/department/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/department/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /db/department/__pycache__/db_department_mgr.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/department/__pycache__/db_department_mgr.cpython-36.pyc -------------------------------------------------------------------------------- /db/department/db_department_mgr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: db_department_mgr.py 6 | @create date: 2019-10-27 15:05 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | from config import configuration 13 | from db.base import DbBase 14 | from db.connection_pool import MysqlConn 15 | 16 | from db.user.db_user_mgr import user_mgr 17 | 18 | from utils.status_code import response_code 19 | from utils.log_helper import lg 20 | 21 | 22 | class DbDepartmentMgr(DbBase): 23 | def get_all_department(self): 24 | """ 25 | 获取所有的部门信息 26 | :return: 27 | """ 28 | db_conn = MysqlConn() 29 | try: 30 | db_name = configuration.get_database_name() 31 | table_name = 'department' 32 | fields = 'dpt_id,dpt_name,p_id' 33 | sql = self.create_select_sql(db_name, table_name, fields) 34 | result = self.execute_fetch_all(db_conn, sql) 35 | data = response_code.SUCCESS 36 | data['data'] = result 37 | return data 38 | except Exception as e: 39 | lg.error(e) 40 | return response_code.GET_DATA_FAIL 41 | finally: 42 | db_conn.close() 43 | 44 | def add_department(self, dpt_name, dpt_p_id): 45 | """ 46 | 添加部门 47 | :param dpt_name: 部门名称 48 | :param dpt_p_id: 上级部门id 49 | :return: 50 | """ 51 | db_conn = MysqlConn() 52 | try: 53 | db_name = configuration.get_database_name() 54 | table_name = 'department' 55 | filed = 'dpt_name' 56 | condition = "dpt_name = '%s'" % dpt_name 57 | system_name_sql = DbBase.create_select_sql(self, db_name, table_name, filed, condition) 58 | res = DbBase.execute_fetch_one(self, db_conn, system_name_sql) 59 | if res: 60 | return response_code.RECORD_EXIST 61 | else: 62 | fields = '(dpt_name, p_id)' 63 | pla_data = (dpt_name, dpt_p_id) 64 | sql = DbBase.create_insert_sql(self, db_name, table_name, fields, pla_data) 65 | DbBase.execute_sql_return_count(self, db_conn, sql) 66 | return response_code.SUCCESS 67 | except Exception as e: 68 | lg.error(e) 69 | return response_code.ADD_DATA_FAIL 70 | finally: 71 | db_conn.close() 72 | 73 | def update_department(self, dpt_id, dpt_name, p_id): 74 | """ 75 | 修改部门 76 | :param dpt_id: 部门ID 77 | :param dpt_name: 部门名称 78 | :return: 79 | """ 80 | db_conn = MysqlConn() 81 | try: 82 | db_name = configuration.get_database_name() 83 | table_name = 'department' 84 | filed = 'dpt_name' 85 | condition = "dpt_id <> %s and dpt_name = '%s'" % (dpt_id, dpt_name) 86 | old_sql = DbBase.create_select_sql(self, db_name, table_name, filed, condition) 87 | old_pla_name_data = DbBase.execute_fetch_one(self, db_conn, old_sql) 88 | if old_pla_name_data: 89 | return response_code.RECORD_EXIST 90 | else: 91 | fields = ['dpt_id', 'dpt_name', 'p_id'] 92 | pla_data = [dpt_id, dpt_name, p_id] 93 | update_condition = 'dpt_id = %s' % str(dpt_id) 94 | update_sql = DbBase.create_update_sql(self, db_name, table_name, fields, pla_data, update_condition) 95 | DbBase.execute_update_sql(self, db_conn, update_sql) 96 | return response_code.SUCCESS 97 | except Exception as e: 98 | lg.error(e) 99 | return response_code.UPDATE_DATA_FAIL 100 | finally: 101 | db_conn.close() 102 | 103 | def delete_department(self, dpt_id): 104 | """ 105 | 删除部门 106 | :param dpt_id: 107 | :return: 108 | """ 109 | db_conn = MysqlConn() 110 | try: 111 | db_name = configuration.get_database_name() 112 | table_name = "department" 113 | user_dpt_table = "users_department" 114 | filed = 'dpt_id' 115 | condition = "dpt_id = %s " % dpt_id 116 | old_sql = self.create_select_sql(db_name, user_dpt_table, filed, condition) 117 | # 获取用户和部门管理表的数据 118 | old_dpt_data = self.execute_fetch_one(db_conn, old_sql) 119 | if old_dpt_data: 120 | condition = "dpt_id=%s" % old_dpt_data.get('dpt_id') 121 | del_association_sql = self.create_delete_sql(db_name, user_dpt_table, condition) 122 | # 删除用户和部门关联表的数据 123 | self.execute_del_data(db_conn, del_association_sql) 124 | # 删除部门数据 125 | condition = "dpt_id=%s" % dpt_id 126 | sql = self.create_delete_sql(db_name, table_name, condition) 127 | self.execute_del_data(db_conn, sql) 128 | return response_code.SUCCESS 129 | except Exception as e: 130 | lg.error(e) 131 | return response_code.DELETE_DATA_FAIL 132 | finally: 133 | db_conn.close() 134 | 135 | def get_dpt_user_info_by_id(self, dpt_id, current_page, page_size): 136 | """ 137 | 获取部门下的员工信息 138 | :param dpt_id: 139 | :param current_page: 140 | :param page_size: 141 | :return: 142 | """ 143 | db_conn = MysqlConn() 144 | try: 145 | start_page = str((current_page - 1) * page_size) 146 | db_name = configuration.get_database_name() 147 | table_name = 'users_department' 148 | fields = 'user_id' 149 | condition = 'dpt_id=%s' % dpt_id 150 | sql_count, sql = self.create_get_page_sql(db_name, table_name, fields, start_page, page_size, condition) 151 | result = self.execute_fetch_pages(db_conn, sql_count, sql, current_page, page_size) 152 | data_list = result.get('data_list') 153 | if data_list: 154 | user_data = tuple([user.get('user_id') for user in data_list]) 155 | user_data_list = user_mgr.get_user_by_ids(user_data) 156 | else: 157 | user_data_list = [] 158 | data = response_code.SUCCESS 159 | data['data'] = user_data_list 160 | data['total'] = result.get('total_count') 161 | return data 162 | except Exception as e: 163 | lg.error(e) 164 | return response_code.GET_DATA_FAIL 165 | finally: 166 | db_conn.close() 167 | 168 | def department_add_staff(self, dpt_id, user_ids): 169 | """ 170 | 给部门下面添加员工 171 | :param dpt_id: 部门ID 172 | :param user_ids: 员工ID 173 | :return: 174 | """ 175 | db_conn = MysqlConn() 176 | try: 177 | db_name = configuration.get_database_name() 178 | table_name = 'users_department' 179 | for user_id in eval(user_ids): 180 | condition = "user_id =%s and dpt_id=%s" % (user_id, dpt_id) 181 | is_exist_sql = self.create_select_sql(db_name, table_name, "*", condition) 182 | res = self.execute_fetch_one(db_conn, is_exist_sql) 183 | if res: 184 | continue 185 | fields = '(user_id,dpt_id)' 186 | value_tuple = (user_id, dpt_id) 187 | insert_user_sql = self.create_insert_sql(db_name, table_name, fields, value_tuple) 188 | self.insert_exec(db_conn, insert_user_sql) 189 | return response_code.SUCCESS 190 | except Exception as e: 191 | lg.error(e) 192 | return response_code.ADD_DATA_FAIL 193 | finally: 194 | db_conn.close() 195 | 196 | def delete_department_staff(self, dpt_id, user_ids): 197 | """ 198 | 删除部门下的员工信息 199 | :param dpt_id: 部门ID 200 | :param user_ids: 201 | :return: 202 | """ 203 | db_conn = MysqlConn() 204 | try: 205 | db_name = configuration.get_database_name() 206 | table_name = 'users_department' 207 | for user_id in eval(user_ids): 208 | condition = "user_id=%s and dpt_id = %s" % (user_id, dpt_id) 209 | sql = self.create_delete_sql(db_name, table_name, condition) 210 | # 删除部门员工 211 | self.execute_del_data(db_conn, sql) 212 | return response_code.SUCCESS 213 | except Exception as e: 214 | lg.error(e) 215 | return response_code.DELETE_DATA_FAIL 216 | finally: 217 | db_conn.close() 218 | 219 | def update_department_staff(self, dpt_id, user_ids): 220 | """ 221 | 给部门下面添加员工 222 | :param dpt_id: 部门ID 223 | :param user_ids: 员工ID 224 | :return: 225 | """ 226 | db_conn = MysqlConn() 227 | try: 228 | db_name = configuration.get_database_name() 229 | table_name = 'users_department' 230 | filed = 'dpt_id' 231 | condition = "dpt_id = %s " % dpt_id 232 | old_sql = self.create_select_sql(db_name, table_name, filed, condition) 233 | # 获取用户和部门管理表的数据 234 | old_dpt_data = self.execute_fetch_one(db_conn, old_sql) 235 | if old_dpt_data: 236 | condition = "dpt_id=%s" % old_dpt_data.get('dpt_id') 237 | del_association_sql = self.create_delete_sql(db_name, table_name, condition) 238 | # 删除旧的用户和部门关联表的数据 239 | self.execute_del_data(db_conn, del_association_sql) 240 | # 添加新的员工 241 | for user_id in eval(user_ids): 242 | fields = '(dpt_id,user_id)' 243 | insert_data = (dpt_id, user_id) 244 | sql = DbBase.create_insert_sql(self, db_name, table_name, fields, insert_data) 245 | DbBase.execute_sql_return_count(self, db_conn, sql) 246 | return response_code.SUCCESS 247 | except Exception as e: 248 | lg.error(e) 249 | return response_code.ADD_DATA_FAIL 250 | finally: 251 | db_conn.close() 252 | 253 | 254 | db_department_mgr = DbDepartmentMgr() 255 | -------------------------------------------------------------------------------- /db/logger/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 14:44 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /db/logger/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/logger/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /db/logger/__pycache__/db_log_mgr.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/logger/__pycache__/db_log_mgr.cpython-36.pyc -------------------------------------------------------------------------------- /db/logger/db_log_mgr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: db_log_mgr.py 6 | @create date: 2019-10-27 14:45 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | import json 12 | 13 | from common.common_time import get_system_datetime 14 | from config import configuration 15 | from db.base import DbBase 16 | from db.connection_pool import MysqlConn 17 | 18 | from utils.log_helper import lg 19 | from utils.status_code import response_code 20 | 21 | 22 | class DbLogMgr(DbBase): 23 | """ 24 | 日志相关数据库表操作类 25 | """ 26 | 27 | def get_pages_operation_log(self, current_page, page_size, search_data, time_scope): 28 | """ 29 | 获取日志信息 30 | :param current_page: 31 | :param page_size: 32 | :param search_data: 33 | :param time_scope: 34 | :return: 35 | """ 36 | db_conn = MysqlConn() 37 | try: 38 | start_page = str((current_page - 1) * page_size) 39 | db_name = configuration.get_database_name() 40 | table_name = 'system_oper_log' 41 | fields = 'log_key, (select name from %s.users where id = user_key) as user_name,user_key,ip_address,level,description,time_create' % db_name 42 | 43 | condition = '' 44 | # 给定了查询字段 45 | if len(json.loads(search_data)) > 0: 46 | condition = self.create_vague_condition_sql(search_data) 47 | # 给定了查询时间类型 48 | if time_scope: 49 | time_scope = eval(time_scope) 50 | start_time = time_scope[0] 51 | end_time = time_scope[1] 52 | if condition: 53 | condition += ' and time_create between ' + str(start_time) + ' and ' + str(end_time) 54 | else: 55 | condition += 'time_create between ' + str(start_time) + ' and ' + str(end_time) 56 | condition += ' order by time_create desc' 57 | sql_count, sql = self.create_get_page_sql(db_name, table_name, fields, start_page, page_size, condition) 58 | result = self.execute_fetch_pages(db_conn, sql_count, sql, current_page, page_size) 59 | data = response_code.SUCCESS 60 | data['data'] = result.get('data_list') 61 | data['total'] = result.get('total_count') 62 | return data 63 | except Exception as e: 64 | lg.error(e) 65 | return response_code.GET_DATA_FAIL 66 | finally: 67 | db_conn.close() 68 | 69 | def add_operation_log(self, user_key, ip_address, level, description): 70 | """ 71 | 添加操作日志 72 | :param user_key: 73 | :param ip_address: 74 | :param level: 75 | :param description: 76 | :return: 77 | """ 78 | db_conn = MysqlConn() 79 | time_create = get_system_datetime() 80 | db_name = configuration.get_database_name() 81 | table_name = 'system_oper_log' 82 | fields = '(user_key,ip_address,level,description,time_create)' 83 | pla_data = (user_key, ip_address, level, description, time_create) 84 | sql = DbBase.create_insert_sql(self, db_name, table_name, fields, pla_data) 85 | DbBase.execute_sql_return_count(self, db_conn, sql) 86 | db_conn.close() 87 | 88 | def get_pages_system_log(self, current_page, page_size, search_data, time_scope): 89 | """ 90 | 分页查询系统日志 91 | :param current_page: 92 | :param page_size: 93 | :param search_data: 94 | :param time_scope: 95 | :return: 96 | """ 97 | db_conn = MysqlConn() 98 | try: 99 | start_page = str((current_page - 1) * page_size) 100 | db_name = configuration.get_database_name() 101 | table_name = 'system_log' 102 | fields = 'log_key,title,source,ip_address,level,status,' \ 103 | 'opinion,opinion_user,opinion_time,time_create,description' 104 | condition = '' 105 | # 给定了查询字段 106 | if len(json.loads(search_data)) > 0: 107 | condition = self.create_vague_condition_sql(search_data) 108 | # 给定了查询时间类型 109 | if time_scope: 110 | time_scope = eval(time_scope) 111 | start_time = time_scope[0] 112 | end_time = time_scope[1] 113 | if condition: 114 | condition += ' and TIME_CREATE between ' + str(start_time) + ' and ' + str(end_time) 115 | else: 116 | condition += 'TIME_CREATE between ' + str(start_time) + ' and ' + str(end_time) 117 | sql_count, sql = self.create_get_page_sql(db_name, table_name, fields, start_page, page_size, condition) 118 | # 执行查询 119 | result = self.execute_fetch_pages(db_conn, sql_count, sql, current_page, page_size) 120 | data = response_code.SUCCESS 121 | data['data'] = result.get('data_list') 122 | data['total'] = result.get('total_count') 123 | return data 124 | except Exception as e: 125 | lg.error(e) 126 | return response_code.GET_DATA_FAIL 127 | finally: 128 | db_conn.close() 129 | 130 | def update_system_log(self, log_key, opinion, opinion_user, status): 131 | """ 132 | 处理后,修改日志信息 133 | :param log_key:日志id 134 | :param opinion:处理意见 135 | :param opinion_user:处理人 136 | :param status:状态 137 | :return: 138 | """ 139 | db_conn = MysqlConn() 140 | try: 141 | db_name = configuration.get_database_name() 142 | table_name = 'system_log' 143 | condition = "log_key=%s" % log_key 144 | # 查看状态是否已经更新 145 | sql = self.create_select_sql(db_name, table_name, 'status', condition) 146 | log = self.execute_fetch_one(db_conn, sql) 147 | if log.get('status') == 2: 148 | return response_code.ALREADY_HANDLED 149 | # 更新日志信息 150 | opinion_time = get_system_datetime() 151 | update_group_fields = ['opinion', 'opinion_user', 'status', 'opinion_time'] 152 | update_group_fields_value = [opinion, opinion_user, status, opinion_time] 153 | update_group_sql = self.create_update_sql(db_name, table_name, update_group_fields, 154 | update_group_fields_value, 155 | condition) 156 | self.updete_exec(db_conn, update_group_sql) 157 | return response_code.SUCCESS 158 | except Exception as e: 159 | lg.error(e) 160 | return response_code.UPDATE_DATA_FAIL 161 | finally: 162 | db_conn.close() 163 | 164 | def get_pages_message(self, user_id, current_page, page_size, search_data): 165 | """ 166 | 分页查询系统消息 167 | :param user_id: 168 | :param current_page: 169 | :param page_size: 170 | :param search_data: 171 | :return: 172 | """ 173 | db_conn = MysqlConn() 174 | try: 175 | start_page = str((current_page - 1) * page_size) 176 | db_name = configuration.get_database_name() 177 | table_name = 'inform_message' 178 | fields = 'id,title,content,create_time,status' 179 | condition = "user_id=%s" % user_id 180 | # 给定了查询字段 181 | if search_data: 182 | condition += ' and ' + self.create_vague_condition_sql(search_data) 183 | sql_count, sql = self.create_get_page_sql(db_name, table_name, fields, start_page, page_size, condition) 184 | # 执行查询 185 | result = self.execute_fetch_pages(db_conn, sql_count, sql, current_page, page_size) 186 | print(sql) 187 | data = response_code.SUCCESS 188 | data['data'] = result.get('data_list') 189 | data['total'] = result.get('total_count') 190 | return data 191 | except Exception as e: 192 | lg.error(e) 193 | return response_code.GET_DATA_FAIL 194 | finally: 195 | db_conn.close() 196 | 197 | def update_message_status(self, id_list): 198 | """ 199 | 修改系统消息状态 200 | :param message_id: 201 | :return: 202 | """ 203 | db_conn = MysqlConn() 204 | try: 205 | 206 | db_name = configuration.get_database_name() 207 | table_name = 'inform_message' 208 | for message_id in eval(id_list): 209 | condition = "id=%s" % message_id 210 | # 更新系统信息 211 | update_fields = ['state'] 212 | update_fields_value = [1] 213 | update_sql = self.create_update_sql(db_name, table_name, update_fields, update_fields_value, condition) 214 | 215 | self.updete_exec(db_conn, update_sql) 216 | return response_code.SUCCESS 217 | except Exception as e: 218 | lg.error(e) 219 | return response_code.UPDATE_DATA_FAIL 220 | finally: 221 | db_conn.close() 222 | 223 | def get_message_count(self, creator): 224 | db_conn = MysqlConn() 225 | try: 226 | db_name = configuration.get_database_name() 227 | table_name = 'inform_message' 228 | data = response_code.SUCCESS 229 | fields = 'id,title,content,create_time,state' 230 | condition = " state = 0" 231 | # 给定了查询字段 232 | sql_count, sql = self.create_get_page_sql(db_name, table_name, fields, 0, 9000000, condition) 233 | # 执行查询 234 | result = self.execute_fetch_pages(db_conn, sql_count, sql, 1, 9000000) 235 | data['data'] = result 236 | 237 | return data 238 | except Exception as e: 239 | lg.error(e) 240 | return response_code.GET_DATA_FAIL 241 | finally: 242 | db_conn.close() 243 | 244 | 245 | db_log = DbLogMgr() 246 | -------------------------------------------------------------------------------- /db/role/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 14:44 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /db/role/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/role/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /db/role/__pycache__/db_role_permission_mgr.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/role/__pycache__/db_role_permission_mgr.cpython-36.pyc -------------------------------------------------------------------------------- /db/user/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 14:44 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /db/user/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/user/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /db/user/__pycache__/db_user_mgr.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/user/__pycache__/db_user_mgr.cpython-36.pyc -------------------------------------------------------------------------------- /db/user_group/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 14:44 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /db/user_group/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/user_group/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /db/user_group/__pycache__/db_group_mgr.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/db/user_group/__pycache__/db_group_mgr.cpython-36.pyc -------------------------------------------------------------------------------- /db/user_group/db_group_mgr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: db_group_mgr.py 6 | @create date: 2019-10-27 15:09 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from common.common_time import get_system_datetime 12 | from config import configuration 13 | from db.base import DbBase 14 | from db.connection_pool import MysqlConn 15 | 16 | from db.user.db_user_mgr import user_mgr 17 | from utils.log_helper import lg 18 | from utils.status_code import response_code 19 | 20 | 21 | class DBGroupMgr(DbBase): 22 | """ 23 | 用户组管理类 24 | """ 25 | 26 | def get_group_list(self, current_page, page_size, search_name): 27 | """ 28 | 分页查询用户组信息 29 | :param current_page: 30 | :param page_size: 31 | :param search_name: 32 | :return: 33 | """ 34 | conn = MysqlConn() 35 | try: 36 | db_name = configuration.get_database_name() 37 | start_num = (current_page - 1) * page_size 38 | # 添加查询条件 39 | condition = None 40 | if search_name: 41 | search_condition = search_name 42 | for key in search_condition.keys(): 43 | condition = key + ' like "%' + search_condition[key] + '%"' 44 | user_group_fields = 'id,name,description,create_time' 45 | sql_count, sql = self.create_get_page_sql(db_name, 'user_group', user_group_fields, start_num, page_size, 46 | condition=condition) 47 | groups_result = self.execute_fetch_pages(conn, sql_count, sql, current_page, page_size) 48 | for group in groups_result["data_list"]: 49 | # 用户组角色查询 50 | group_id = group.get('id') 51 | role_relations = [ 52 | {"table_name": "user_group_role", "join_condition": "user_group_role.role_id=role.id"}] 53 | condition = "user_group_role.group_id=" + str(group_id) 54 | role_query_sql = self.create_get_relation_sql(db_name, "role", "id,name", role_relations, 55 | condition=condition) 56 | roles = self.execute_fetch_all(conn, role_query_sql) 57 | role_name_str = '' 58 | role_ids = [] 59 | if len(roles) == 0: 60 | pass 61 | elif len(roles) == 1: 62 | role_name_str = roles[0]["name"] 63 | role_ids.append(roles[0]["id"]) 64 | else: 65 | for role in roles: 66 | role_name_str += role["name"] + '|' 67 | role_ids.append(role["id"]) 68 | group["roles"] = role_name_str.rstrip('|') 69 | group["role_ids"] = role_ids 70 | # 返回 71 | data = response_code.SUCCESS 72 | data["data"] = groups_result.get('data_list') 73 | data["total"] = groups_result.get('total_count') 74 | return data 75 | except Exception as e: 76 | lg.error(e) 77 | return response_code.GET_DATA_FAIL 78 | finally: 79 | 80 | conn.close() 81 | 82 | def get_all_groups(self): 83 | """ 84 | 获取所有用户组 85 | :return: 86 | """ 87 | db_conn = MysqlConn() 88 | try: 89 | db_name = configuration.get_database_name() 90 | table_name = 'user_group' 91 | fields = 'id,name,description as desc,create_time' 92 | sql = self.create_select_sql(db_name, table_name, fields) 93 | result = self.execute_fetch_all(db_conn, sql) 94 | data = response_code.SUCCESS 95 | data['data'] = result 96 | return data 97 | except Exception as e: 98 | lg.error(e) 99 | return response_code.GET_DATA_FAIL 100 | finally: 101 | db_conn.close() 102 | 103 | def get_user_group_by_name(self, group_name): 104 | """ 105 | 通过名称查询用户组信息 106 | :param group_name: 107 | :return: 108 | """ 109 | conn = MysqlConn() 110 | try: 111 | condition = 'name="%s"' % group_name 112 | db_name = configuration.get_database_name() 113 | sql = self.create_select_sql(db_name, 'user_group', 'id', condition=condition) 114 | return self.execute_fetch_one(conn, sql) 115 | except Exception as e: 116 | lg.error(e) 117 | return response_code.GET_DATA_FAIL 118 | finally: 119 | conn.close() 120 | 121 | def add_group(self, group_name, group_desc, role_ids): 122 | """ 123 | 添加用户组 124 | :param group_name: 125 | :param group_desc: 126 | :return: 127 | """ 128 | db_conn = MysqlConn() 129 | try: 130 | db_name = configuration.get_database_name() 131 | table_name = 'user_group' 132 | filed = 'name' 133 | condition = "name = '%s'" % group_name 134 | is_exist_sql = self.create_select_sql(db_name, table_name, filed, condition) 135 | res = self.execute_fetch_one(db_conn, is_exist_sql) 136 | if res: 137 | return response_code.RECORD_EXIST 138 | fields = '(name,description,create_time)' 139 | create_time = get_system_datetime() 140 | value_tuple = (group_name, group_desc, create_time) 141 | insert_user_sql = self.create_insert_sql(db_name, table_name, fields, value_tuple) 142 | self.insert_exec(db_conn, insert_user_sql) 143 | # 查询新添加的用户组 144 | new_group = self.get_user_group_by_name(group_name) 145 | new_group_id = new_group.get('id') 146 | # 添加用户组的角色 147 | group_role_fields = '(group_id,role_id)' 148 | for role_id in eval(str(role_ids)): 149 | group_role_value_tuple = (new_group_id, role_id) 150 | insert_user_sql = self.create_insert_sql(db_name, "user_group_role", group_role_fields, 151 | group_role_value_tuple) 152 | self.insert_exec(db_conn, insert_user_sql) 153 | return response_code.SUCCESS 154 | except Exception as e: 155 | lg.error(e) 156 | return response_code.ADD_DATA_FAIL 157 | finally: 158 | db_conn.close() 159 | 160 | def del_group(self, group_id, role_ids): 161 | """ 162 | 删除用户组 163 | :param group_id: 164 | :return: 165 | """ 166 | db_conn = MysqlConn() 167 | try: 168 | db_name = configuration.get_database_name() 169 | # 关闭外键检测 170 | # db_conn.cur.execute('SET FOREIGN_KEY_CHECKS = 0;') 171 | # db_conn.conn.commit() 172 | # 删除用户组角色 173 | for role_id in eval(str(role_ids)): 174 | condition = "group_id=%s and role_id=%s" % (group_id, role_id) 175 | delete_group_role_sql = self.create_delete_sql(db_name, "user_group_role", condition) 176 | self.delete_exec(db_conn, delete_group_role_sql) 177 | # 删除用户组下所有用户 178 | condition = "group_id=%s" % group_id 179 | delete_group_user_sql = self.create_delete_sql(db_name, "user_user_group", condition) 180 | self.delete_exec(db_conn, delete_group_user_sql) 181 | # 删除用户组主表信息 182 | table_name = 'user_group' 183 | condition = "id=%s" % group_id 184 | delete_group_sql = self.create_delete_sql(db_name, table_name, condition) 185 | self.delete_exec(db_conn, delete_group_sql) 186 | 187 | # 开起外键检测 188 | # db_conn.cur.execute('SET FOREIGN_KEY_CHECKS = 1;') 189 | # db_conn.conn.commit() 190 | return response_code.SUCCESS 191 | except Exception as e: 192 | lg.error(e) 193 | return response_code.DELETE_DATA_FAIL 194 | finally: 195 | db_conn.close() 196 | 197 | def upd_group(self, group_json): 198 | """ 199 | 更新用户组 200 | :param group_json: 201 | :return: 202 | """ 203 | db_conn = MysqlConn() 204 | try: 205 | db_name = configuration.get_database_name() 206 | # 解析参数成dict 207 | group = group_json 208 | table_name = 'user_group' 209 | condition = "id=%s" % group.get('id') 210 | # 更新用户基本信息 211 | update_group_fields = ['name', 'description'] 212 | update_group_fields_value = [group.get('name'), group.get('desc')] 213 | update_group_sql = self.create_update_sql(db_name, table_name, update_group_fields, 214 | update_group_fields_value, 215 | condition) 216 | self.updete_exec(db_conn, update_group_sql) 217 | # 删除用户组原有角色 218 | condition = "group_id=%s" % group.get('id') 219 | delete_group_role_sql = self.create_delete_sql(db_name, "user_group_role", condition) 220 | self.delete_exec(db_conn, delete_group_role_sql) 221 | 222 | # 添加用户组的角色 223 | group_role_fields = '(group_id,role_id)' 224 | for role_id in eval(str(group.get('role_ids'))): 225 | group_role_value_tuple = (group.get('id'), role_id) 226 | insert_group_role_sql = self.create_insert_sql(db_name, "user_group_role", group_role_fields, 227 | group_role_value_tuple) 228 | self.insert_exec(db_conn, insert_group_role_sql) 229 | return response_code.SUCCESS 230 | except Exception as e: 231 | lg.error(e) 232 | return response_code.UPDATE_DATA_FAIL 233 | finally: 234 | db_conn.close() 235 | 236 | def add_user_to_group(self, group_id, user_ids): 237 | """ 238 | 添加用户到用户组 239 | :param group_id:用户组id 240 | :param user_ids:用户id列表 241 | :return: 242 | """ 243 | db_conn = MysqlConn() 244 | try: 245 | db_name = configuration.get_database_name() 246 | table_name = 'user_user_group' 247 | for user_id in eval(user_ids): 248 | condition = "user_id =%s and group_id=%s" % (user_id, group_id) 249 | is_exist_sql = self.create_select_sql(db_name, table_name, "*", condition) 250 | res = self.execute_fetch_one(db_conn, is_exist_sql) 251 | if res: 252 | continue 253 | fields = '(user_id,group_id)' 254 | value_tuple = (user_id, group_id) 255 | insert_user_sql = self.create_insert_sql(db_name, table_name, fields, value_tuple) 256 | self.insert_exec(db_conn, insert_user_sql) 257 | return response_code.SUCCESS 258 | except Exception as e: 259 | lg.error(e) 260 | return response_code.ADD_DATA_FAIL 261 | finally: 262 | db_conn.close() 263 | 264 | def remove_group_users(self, group_id, user_ids): 265 | """ 266 | 移除用户组内的用户 267 | :param group_id: 268 | :param user_ids: 269 | :return: 270 | """ 271 | db_conn = MysqlConn() 272 | try: 273 | db_name = configuration.get_database_name() 274 | table_name = 'user_user_group' 275 | for user_id in eval(user_ids): 276 | condition = "user_id =%s and group_id=%s" % (user_id, group_id) 277 | is_exist_sql = self.create_select_sql(db_name, table_name, "*", condition) 278 | res = self.execute_fetch_one(db_conn, is_exist_sql) 279 | if res: 280 | del_user_sql = self.create_delete_sql(db_name, table_name, condition) 281 | self.delete_exec(db_conn, del_user_sql) 282 | return response_code.SUCCESS 283 | except Exception as e: 284 | lg.error(e) 285 | return response_code.DELETE_DATA_FAIL 286 | finally: 287 | db_conn.close() 288 | 289 | def get_user_by_group_id(self, group_id, current_page, page_size): 290 | """ 291 | 查询用户组下所有用户 292 | :param group_id: 293 | :param current_page: 294 | :param page_size: 295 | :return: 296 | """ 297 | db_conn = MysqlConn() 298 | try: 299 | start_num = str((current_page - 1) * page_size) 300 | db_name = configuration.get_database_name() 301 | table_name = 'user_user_group' 302 | fields = 'user_id' 303 | condition = 'group_id=%s' % group_id 304 | sql_count, sql = self.create_get_page_sql(db_name, table_name, fields, start_num, page_size, condition) 305 | result = self.execute_fetch_pages(db_conn, sql_count, sql, current_page, page_size) 306 | data_list = result.get('data_list') 307 | 308 | if data_list: 309 | user_data = tuple([user.get('user_id') for user in data_list]) 310 | user_data_list = user_mgr.get_user_by_ids(user_data) 311 | else: 312 | user_data_list = [] 313 | 314 | # user_data = tuple([user.get('user_id') for user in data]) 315 | # user_data_list = user_mgr.get_user_by_ids(user_data) 316 | data = response_code.SUCCESS 317 | data['data'] = user_data_list 318 | data['total'] = result.get('total_count') 319 | return data 320 | except Exception as e: 321 | lg.error(e) 322 | return response_code.GET_DATA_FAIL 323 | finally: 324 | db_conn.close() 325 | 326 | def get_user_group_roles(self, group_id): 327 | """ 328 | 获取用户组的角色信息 329 | :param group_id: 330 | :return: 331 | """ 332 | db_conn = MysqlConn() 333 | try: 334 | db_name = configuration.get_database_name() 335 | table_name = 'user_group_role' 336 | fields = 'role_id' 337 | condition = 'group_id=%s' % group_id 338 | sql = self.create_select_sql(db_name, table_name, fields, condition=condition) 339 | result = self.execute_fetch_all(db_conn, sql) 340 | if result: 341 | role_ids = tuple([role.get('role_id') for role in result]) 342 | if len(role_ids) == 1: 343 | role_condition = 'id=%s' % role_ids[0] 344 | else: 345 | role_condition = 'id in %s' % str(role_ids) 346 | sql = self.create_select_sql(db_name, 'role', '*', condition=role_condition) 347 | role_result = self.execute_fetch_all(db_conn, sql) 348 | data = response_code.SUCCESS 349 | data['data'] = role_result 350 | else: 351 | data = response_code.SUCCESS 352 | data['data'] = [] 353 | return data 354 | except Exception as e: 355 | lg.error(e) 356 | return response_code.GET_DATA_FAIL 357 | finally: 358 | db_conn.close() 359 | 360 | def add_user_group_roles(self, group_id, role_ids): 361 | """ 362 | 添加用户组角色 363 | :param group_id: 364 | :param role_ids: 365 | :return: 366 | """ 367 | db_conn = MysqlConn() 368 | try: 369 | db_name = configuration.get_database_name() 370 | table_name = 'user_group_role' 371 | for role_id in eval(role_ids): 372 | condition = "role_id =%s and group_id=%s" % (role_id, group_id) 373 | is_exist_sql = self.create_select_sql(db_name, table_name, "*", condition) 374 | res = self.execute_fetch_one(db_conn, is_exist_sql) 375 | if res: 376 | continue 377 | fields = '(role_id,group_id)' 378 | value_tuple = (role_id, group_id) 379 | insert_user_sql = self.create_insert_sql(db_name, table_name, fields, value_tuple) 380 | self.insert_exec(db_conn, insert_user_sql) 381 | return response_code.SUCCESS 382 | except Exception as e: 383 | lg.error(e) 384 | return response_code.ADD_DATA_FAIL 385 | finally: 386 | db_conn.close() 387 | 388 | def remove_user_group_roles(self, group_id, role_ids): 389 | """ 390 | 移除用户组的角色 391 | :param group_id: 392 | :param role_ids: 393 | :return: 394 | """ 395 | db_conn = MysqlConn() 396 | try: 397 | db_name = configuration.get_database_name() 398 | table_name = 'user_group_role' 399 | for role_id in eval(role_ids): 400 | condition = "role_id =%s and group_id=%s" % (role_id, group_id) 401 | is_exist_sql = self.create_select_sql(db_name, table_name, "*", condition) 402 | res = self.execute_fetch_one(db_conn, is_exist_sql) 403 | if res: 404 | del_user_sql = self.create_delete_sql(db_name, table_name, condition) 405 | self.delete_exec(db_conn, del_user_sql) 406 | return response_code.SUCCESS 407 | except Exception as e: 408 | lg.error(e) 409 | return response_code.DELETE_DATA_FAIL 410 | finally: 411 | db_conn.close() 412 | 413 | 414 | db_group_mgr = DBGroupMgr() 415 | -------------------------------------------------------------------------------- /dbsql/user_api.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Navicat Premium Data Transfer 3 | 4 | Source Server : localhost_3306 5 | Source Server Type : MySQL 6 | Source Server Version : 50725 7 | Source Host : localhost:3306 8 | Source Schema : user_api 9 | 10 | Target Server Type : MySQL 11 | Target Server Version : 50725 12 | File Encoding : 65001 13 | 14 | Date: 27/10/2019 17:05:47 15 | */ 16 | 17 | SET NAMES utf8mb4; 18 | SET FOREIGN_KEY_CHECKS = 0; 19 | 20 | -- ---------------------------- 21 | -- Table structure for department 22 | -- ---------------------------- 23 | DROP TABLE IF EXISTS `department`; 24 | CREATE TABLE `department` ( 25 | `DPT_ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', 26 | `DPT_NAME` varchar(64) DEFAULT NULL COMMENT '部门名称', 27 | `SORT` int(11) DEFAULT NULL COMMENT '排序', 28 | `P_ID` int(11) DEFAULT '0' COMMENT '父ID', 29 | PRIMARY KEY (`DPT_ID`) USING BTREE, 30 | KEY `p_id` (`P_ID`) USING BTREE, 31 | CONSTRAINT `department_ibfk_1` FOREIGN KEY (`P_ID`) REFERENCES `department` (`DPT_ID`) 32 | ) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 33 | 34 | -- ---------------------------- 35 | -- Records of department 36 | -- ---------------------------- 37 | BEGIN; 38 | INSERT INTO `department` VALUES (1, 'XXX有限公司', 1, NULL); 39 | COMMIT; 40 | 41 | -- ---------------------------- 42 | -- Table structure for inform_message 43 | -- ---------------------------- 44 | DROP TABLE IF EXISTS `inform_message`; 45 | CREATE TABLE `inform_message` ( 46 | `ID` int(11) NOT NULL AUTO_INCREMENT, 47 | `TITLE` varchar(128) DEFAULT NULL COMMENT '标题', 48 | `CREATE_TIME` double DEFAULT NULL COMMENT '创建时间', 49 | `STATE` int(11) DEFAULT NULL COMMENT '消息状态 0:未读;1:已读', 50 | `CONTENT` varchar(256) DEFAULT NULL COMMENT '描述信息', 51 | `TASK_GROUPS` varchar(64) DEFAULT NULL, 52 | `CREATOR` int(11) DEFAULT NULL, 53 | PRIMARY KEY (`ID`) USING BTREE 54 | ) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 55 | 56 | -- ---------------------------- 57 | -- Table structure for menu 58 | -- ---------------------------- 59 | DROP TABLE IF EXISTS `menu`; 60 | CREATE TABLE `menu` ( 61 | `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', 62 | `NAME` varchar(128) DEFAULT '' COMMENT '菜单名称', 63 | `URL` varchar(128) DEFAULT '' COMMENT 'URL', 64 | `ICON` varchar(128) DEFAULT '' COMMENT '菜单图标', 65 | `SORT` varchar(11) DEFAULT '' COMMENT '排序', 66 | `P_ID` int(11) DEFAULT NULL COMMENT '父ID', 67 | `IS_ROUTER` int(11) DEFAULT NULL COMMENT '是否有路由', 68 | `ROUTER_PARENT` varchar(128) DEFAULT '' COMMENT '父路由', 69 | PRIMARY KEY (`ID`) USING BTREE 70 | ) ENGINE=InnoDB AUTO_INCREMENT=89 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 71 | 72 | -- ---------------------------- 73 | -- Table structure for operation 74 | -- ---------------------------- 75 | DROP TABLE IF EXISTS `operation`; 76 | CREATE TABLE `operation` ( 77 | `OPER_ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', 78 | `OPER_TITLE` varchar(255) DEFAULT NULL, 79 | `OPER_NAME` varchar(128) DEFAULT NULL COMMENT '操作名称', 80 | `URL` varchar(128) DEFAULT NULL COMMENT 'URL', 81 | `URLI` varchar(128) DEFAULT NULL COMMENT '类型', 82 | `SORT` int(11) DEFAULT NULL COMMENT '排序', 83 | `PARENT_ID` int(11) DEFAULT NULL COMMENT '父ID', 84 | PRIMARY KEY (`OPER_ID`) USING BTREE 85 | ) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 86 | 87 | -- ---------------------------- 88 | -- Table structure for operation_permission 89 | -- ---------------------------- 90 | DROP TABLE IF EXISTS `operation_permission`; 91 | CREATE TABLE `operation_permission` ( 92 | `OPER_ID` int(11) NOT NULL, 93 | `PERMISSION_ID` int(11) DEFAULT NULL, 94 | PRIMARY KEY (`OPER_ID`) USING BTREE 95 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 96 | 97 | -- ---------------------------- 98 | -- Table structure for permission 99 | -- ---------------------------- 100 | DROP TABLE IF EXISTS `permission`; 101 | CREATE TABLE `permission` ( 102 | `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', 103 | `NAME` varchar(128) DEFAULT NULL COMMENT '权限名称', 104 | `CREATE_TIME` double DEFAULT NULL COMMENT '创建时间', 105 | `P_ID` int(11) DEFAULT NULL COMMENT '权限父ID', 106 | `PERMISSION_TYPE` tinyint(1) DEFAULT '0' COMMENT '权限类型\r\n0:代表普通权限;1:代表数据权限,3,代表grafana权限', 107 | `GRAFANA_ID` int(11) NOT NULL DEFAULT '0' COMMENT '特殊给grafana权限使用的', 108 | PRIMARY KEY (`ID`) USING BTREE 109 | ) ENGINE=InnoDB AUTO_INCREMENT=97 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 110 | 111 | -- ---------------------------- 112 | -- Table structure for permission_menu 113 | -- ---------------------------- 114 | DROP TABLE IF EXISTS `permission_menu`; 115 | CREATE TABLE `permission_menu` ( 116 | `PERMISSION_ID` int(11) DEFAULT NULL COMMENT '权限ID', 117 | `MEUN_ID` int(11) DEFAULT NULL COMMENT '菜单ID', 118 | KEY `permission_id` (`PERMISSION_ID`) USING BTREE, 119 | KEY `meun_id` (`MEUN_ID`) USING BTREE, 120 | CONSTRAINT `permission_menu_ibfk_1` FOREIGN KEY (`PERMISSION_ID`) REFERENCES `permission` (`ID`), 121 | CONSTRAINT `permission_menu_ibfk_2` FOREIGN KEY (`MEUN_ID`) REFERENCES `menu` (`ID`) 122 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 123 | 124 | -- ---------------------------- 125 | -- Table structure for role 126 | -- ---------------------------- 127 | DROP TABLE IF EXISTS `role`; 128 | CREATE TABLE `role` ( 129 | `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', 130 | `NAME` varchar(64) DEFAULT NULL COMMENT '角色名称', 131 | `CREATE_TIME` double DEFAULT NULL COMMENT '创建时间', 132 | `NOTE_INFO` varchar(128) DEFAULT NULL COMMENT '备注信息', 133 | `TIME_MODIFY` double DEFAULT NULL COMMENT '修改时间', 134 | PRIMARY KEY (`ID`) USING BTREE 135 | ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 136 | 137 | -- ---------------------------- 138 | -- Records of role 139 | -- ---------------------------- 140 | BEGIN; 141 | INSERT INTO `role` VALUES (1, '管理员', 1558316800672, '这是管理员', 1571122452484); 142 | COMMIT; 143 | 144 | -- ---------------------------- 145 | -- Table structure for roles_permission 146 | -- ---------------------------- 147 | DROP TABLE IF EXISTS `roles_permission`; 148 | CREATE TABLE `roles_permission` ( 149 | `PERMISSION_ID` int(11) DEFAULT NULL COMMENT '权限ID', 150 | `ROLE_ID` int(11) DEFAULT NULL COMMENT '角色ID', 151 | KEY `permission_id` (`PERMISSION_ID`) USING BTREE, 152 | KEY `role_id` (`ROLE_ID`) USING BTREE, 153 | CONSTRAINT `roles_permission_ibfk_1` FOREIGN KEY (`PERMISSION_ID`) REFERENCES `permission` (`ID`), 154 | CONSTRAINT `roles_permission_ibfk_2` FOREIGN KEY (`ROLE_ID`) REFERENCES `role` (`ID`) 155 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 156 | 157 | -- ---------------------------- 158 | -- Table structure for system_log 159 | -- ---------------------------- 160 | DROP TABLE IF EXISTS `system_log`; 161 | CREATE TABLE `system_log` ( 162 | `LOG_KEY` int(11) NOT NULL AUTO_INCREMENT COMMENT '操作日志ID', 163 | `TITLE` varchar(255) DEFAULT NULL COMMENT '标题', 164 | `SOURCE` varchar(255) DEFAULT NULL COMMENT '源', 165 | `IP_ADDRESS` varchar(255) DEFAULT NULL COMMENT 'IP地址', 166 | `LEVEL` int(8) DEFAULT NULL COMMENT '级别\r\n0:INFO\r\n1:ERROR\r\n2:ALERT\r\n3:FATAL\r\n\r\n', 167 | `STATUS` int(8) DEFAULT NULL COMMENT '处理状态 0:未处理,1:处理中 2:已处理', 168 | `OPINION` varchar(2048) DEFAULT NULL COMMENT '处理意见', 169 | `OPINION_USER` varchar(255) DEFAULT NULL COMMENT '处理人', 170 | `OPINION_TIME` double DEFAULT NULL COMMENT '处理时间', 171 | `TIME_CREATE` double DEFAULT NULL COMMENT '时间', 172 | `DESCRIPTION` varchar(2048) DEFAULT NULL COMMENT '描述信息', 173 | PRIMARY KEY (`LOG_KEY`) USING BTREE 174 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 175 | 176 | -- ---------------------------- 177 | -- Table structure for system_oper_log 178 | -- ---------------------------- 179 | DROP TABLE IF EXISTS `system_oper_log`; 180 | CREATE TABLE `system_oper_log` ( 181 | `LOG_KEY` int(11) NOT NULL AUTO_INCREMENT COMMENT '日志ID', 182 | `USER_KEY` int(11) DEFAULT NULL COMMENT '用户ID', 183 | `IP_ADDRESS` varchar(15) DEFAULT NULL COMMENT 'IP地址', 184 | `LEVEL` int(11) NOT NULL COMMENT '日志级别\r\n0:INFO\r\n1:ERROR\r\n2:ALERT\r\n3:FATAL\r\n', 185 | `TIME_CREATE` double DEFAULT NULL COMMENT '创建时间', 186 | `DESCRIPTION` varchar(640) DEFAULT NULL COMMENT '描述', 187 | PRIMARY KEY (`LOG_KEY`) USING BTREE 188 | ) ENGINE=InnoDB AUTO_INCREMENT=87 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 189 | 190 | -- ---------------------------- 191 | -- Table structure for user_group 192 | -- ---------------------------- 193 | DROP TABLE IF EXISTS `user_group`; 194 | CREATE TABLE `user_group` ( 195 | `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', 196 | `NAME` varchar(64) DEFAULT NULL COMMENT '用户组名称', 197 | `DESCRIPTION` varchar(128) DEFAULT NULL COMMENT '用户组描述', 198 | `CREATE_TIME` double DEFAULT NULL COMMENT '创建时间', 199 | PRIMARY KEY (`ID`) USING BTREE 200 | ) ENGINE=InnoDB AUTO_INCREMENT=73 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 201 | 202 | -- ---------------------------- 203 | -- Table structure for user_group_role 204 | -- ---------------------------- 205 | DROP TABLE IF EXISTS `user_group_role`; 206 | CREATE TABLE `user_group_role` ( 207 | `GROUP_ID` int(11) DEFAULT NULL COMMENT '用户组ID', 208 | `ROLE_ID` int(11) DEFAULT NULL COMMENT '角色ID', 209 | KEY `group_id` (`GROUP_ID`) USING BTREE, 210 | KEY `role_id` (`ROLE_ID`) USING BTREE, 211 | CONSTRAINT `user_group_role_ibfk_1` FOREIGN KEY (`GROUP_ID`) REFERENCES `user_group` (`ID`), 212 | CONSTRAINT `user_group_role_ibfk_2` FOREIGN KEY (`ROLE_ID`) REFERENCES `role` (`ID`) 213 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 214 | 215 | -- ---------------------------- 216 | -- Table structure for user_roles 217 | -- ---------------------------- 218 | DROP TABLE IF EXISTS `user_roles`; 219 | CREATE TABLE `user_roles` ( 220 | `USER_ID` int(11) DEFAULT NULL COMMENT '用户ID', 221 | `ROLE_ID` int(11) DEFAULT NULL COMMENT '角色ID', 222 | KEY `user_id` (`USER_ID`) USING BTREE, 223 | KEY `role_id` (`ROLE_ID`) USING BTREE, 224 | CONSTRAINT `user_roles_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `users` (`ID`), 225 | CONSTRAINT `user_roles_ibfk_2` FOREIGN KEY (`ROLE_ID`) REFERENCES `role` (`ID`) 226 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 227 | 228 | -- ---------------------------- 229 | -- Table structure for user_user_group 230 | -- ---------------------------- 231 | DROP TABLE IF EXISTS `user_user_group`; 232 | CREATE TABLE `user_user_group` ( 233 | `USER_ID` int(11) DEFAULT NULL COMMENT '用户ID', 234 | `GROUP_ID` int(11) DEFAULT NULL COMMENT '用户组ID', 235 | KEY `user_id` (`USER_ID`) USING BTREE, 236 | KEY `group_id` (`GROUP_ID`) USING BTREE, 237 | CONSTRAINT `user_user_group_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `users` (`ID`), 238 | CONSTRAINT `user_user_group_ibfk_2` FOREIGN KEY (`GROUP_ID`) REFERENCES `user_group` (`ID`) 239 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 240 | 241 | -- ---------------------------- 242 | -- Table structure for users 243 | -- ---------------------------- 244 | DROP TABLE IF EXISTS `users`; 245 | CREATE TABLE `users` ( 246 | `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', 247 | `USER_NAME` varchar(128) DEFAULT NULL COMMENT '账号', 248 | `USER_SEX` varchar(10) DEFAULT NULL COMMENT '性别', 249 | `EMAIL` varchar(64) DEFAULT NULL COMMENT '邮箱', 250 | `PASS_WORD` varchar(256) DEFAULT NULL COMMENT '密码', 251 | `PHONE` varchar(64) DEFAULT NULL COMMENT '电话', 252 | `POSITION` varchar(64) DEFAULT NULL COMMENT '职位', 253 | `CREATE_TIME` double DEFAULT NULL COMMENT '创建时间', 254 | `NOTE_INFO` varchar(128) DEFAULT NULL COMMENT '备注信息', 255 | `LOGIN_NAME` varchar(128) DEFAULT NULL COMMENT '姓名', 256 | `ICON` varchar(255) DEFAULT NULL COMMENT '头像', 257 | PRIMARY KEY (`ID`) USING BTREE 258 | ) ENGINE=InnoDB AUTO_INCREMENT=351 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 259 | 260 | -- ---------------------------- 261 | -- Records of users 262 | -- ---------------------------- 263 | BEGIN; 264 | INSERT INTO `users` VALUES (1, 'super', '1', '124@123.com', 'pbkdf2:sha256:150000$wU6AvaKT$b84ca435628dadf615f4383e0c3c75c23aaa9dc6ba958378061f9a753968e8c0', '13212341222', '超级管理员', 1556523116000, '', '超级管理员', ''); 265 | COMMIT; 266 | 267 | -- ---------------------------- 268 | -- Table structure for users_department 269 | -- ---------------------------- 270 | DROP TABLE IF EXISTS `users_department`; 271 | CREATE TABLE `users_department` ( 272 | `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', 273 | `USER_ID` int(11) NOT NULL COMMENT '用户ID', 274 | `DPT_ID` int(11) NOT NULL COMMENT '部门ID', 275 | PRIMARY KEY (`ID`) USING BTREE, 276 | KEY `user_id` (`USER_ID`) USING BTREE, 277 | KEY `dpt_id` (`DPT_ID`) USING BTREE, 278 | CONSTRAINT `users_department_ibfk_1` FOREIGN KEY (`USER_ID`) REFERENCES `users` (`ID`), 279 | CONSTRAINT `users_department_ibfk_2` FOREIGN KEY (`DPT_ID`) REFERENCES `department` (`DPT_ID`) 280 | ) ENGINE=InnoDB AUTO_INCREMENT=898 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC; 281 | 282 | SET FOREIGN_KEY_CHECKS = 1; 283 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aniso8601==8.0.0 2 | Click==7.0 3 | DBUtils==1.3 4 | Flask==1.1.1 5 | Flask-Cors==3.0.8 6 | Flask-JWT==0.3.2 7 | Flask-RESTful==0.3.7 8 | itsdangerous==1.1.0 9 | Jinja2==2.10.3 10 | MarkupSafe==1.1.1 11 | PyJWT==1.4.2 12 | PyMySQL==0.9.3 13 | xmltodict==0.12.0 14 | -------------------------------------------------------------------------------- /start.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: start.py 6 | @create date: 2019-10-27 10:20 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | import os 13 | 14 | from api import create_app 15 | from config import configuration 16 | 17 | app = create_app(os.getenv('FLASK_CONFIG') or 'default') 18 | 19 | if __name__ == '__main__': 20 | host, port, debug = configuration.get_start_config() 21 | app.run(host=host, port=port, debug=eval(debug)) 22 | 23 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: __init__.py.py 6 | @create date: 2019-10-27 13:26 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ -------------------------------------------------------------------------------- /utils/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/utils/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/api_version_verify.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/utils/__pycache__/api_version_verify.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/auth_helper.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/utils/__pycache__/auth_helper.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/fun_name_to_enum.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/utils/__pycache__/fun_name_to_enum.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/log_helper.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/utils/__pycache__/log_helper.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/status_code.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/utils/__pycache__/status_code.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/xml_json_process.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kujirashark/user_restful_api/ac5fbd8b8e27096a90f1a8998506337fbb41324c/utils/__pycache__/xml_json_process.cpython-36.pyc -------------------------------------------------------------------------------- /utils/api_version_verify.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: api_version_verify.py 6 | @create date: 2019-10-27 14:15 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description:api版本验证 10 | """ 11 | 12 | from functools import wraps 13 | 14 | from flask import request 15 | 16 | from common.common_request_process import req 17 | 18 | 19 | def api_version(func): 20 | """ 21 | API版本验证装饰器 22 | :param func: 23 | :return: 24 | """ 25 | 26 | @wraps(func) 27 | def wrapper(*args, **kwargs): 28 | xml = request.args.get('format') 29 | # 验证api版本 30 | verify_result, version_res = req.verify_version(kwargs.get('version'), xml) 31 | if not verify_result: 32 | return version_res 33 | return func(*args, **kwargs) 34 | 35 | return wrapper 36 | -------------------------------------------------------------------------------- /utils/auth_helper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: auth_helper.py 6 | @create date: 2019-10-27 14:17 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | import json 12 | import sys 13 | 14 | import datetime 15 | import jwt 16 | import time 17 | from flask import abort 18 | from werkzeug.security import check_password_hash 19 | 20 | import api 21 | from db.user.db_user_mgr import user_mgr 22 | from utils.status_code import response_code 23 | 24 | 25 | class Auth(object): 26 | """ 27 | 权限校验、token帮助类 28 | """ 29 | 30 | def __encode_auth_token(self, user_key, login_time): 31 | """ 32 | 生成认证Token 33 | :param USER_KEY: int 34 | :param login_time: int(timestamp) 35 | :return: string 36 | """ 37 | try: 38 | ##exp: 过期时间 39 | ##nbf: 表示当前时间在nbf里的时间之前,则Token不被接受 40 | ##iss: token签发者 41 | ##aud: 接收者 42 | ##iat: 发行时间 43 | payload = { 44 | 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, seconds=10), 45 | 'iat': datetime.datetime.utcnow(), 46 | 'iss': 'ken', 47 | 'data': { 48 | 'user_key': user_key, 49 | 'login_time': login_time 50 | } 51 | } 52 | return jwt.encode( 53 | payload, 54 | api.Config.SECRET_KEY, 55 | algorithm='HS256' 56 | ) 57 | except Exception as e: 58 | return e 59 | 60 | def __decode_auth_token(self, auth_token): 61 | """ 62 | 验证Token 63 | :param auth_token: 64 | :return: integer|string 65 | """ 66 | try: 67 | ###十分钟无访问token过期 68 | # payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'), leeway=datetime.timedelta(seconds=10)) 69 | # 取消过期时间验证 70 | payload = jwt.decode(auth_token, api.Config.SECRET_KEY, options={'verify_exp': False}) 71 | if ('data' in payload and 'user_key' in payload['data']): 72 | return payload 73 | else: 74 | raise jwt.InvalidTokenError 75 | except jwt.ExpiredSignatureError: 76 | return 'Token过期' 77 | except jwt.InvalidTokenError: 78 | return '无效Token' 79 | except TypeError: 80 | return '无效Token' 81 | except: 82 | print(sys.exc_info()[1]) 83 | 84 | @classmethod 85 | def authenticate(cls, username, password): 86 | """ 87 | 用户登录,登录成功返回token,写将登录时间写入数据库;登录失败返回失败原因 88 | :param password: 89 | :return: json 90 | """ 91 | user = user_mgr.get_user_by_name(username) 92 | user_data = user.get('data') 93 | # 判断是有这个用户 94 | if (user_data is None): 95 | return response_code.LOGIN_IS_FAILD 96 | if user_data: 97 | # 验证密码 98 | if not check_password_hash(user_data.get('pass_word'), password): 99 | return response_code.LOGIN_IS_FAIL 100 | # 登录时间 101 | login_time = int(time.time()) 102 | 103 | # 生成token 104 | token = cls._Auth__encode_auth_token(cls, user_data.get('id'), login_time) 105 | user_data.pop('pass_word') 106 | dict_user = user_data 107 | dict_user['token'] = token.decode() 108 | return dict_user 109 | else: 110 | return response_code.LOGIN_IS_FAILD 111 | 112 | @classmethod 113 | def identify(cls, request): 114 | """ 115 | 用户鉴权 116 | :return: list 117 | """ 118 | auth_header = request.headers.get('Authorization') 119 | if (auth_header): 120 | auth_tokenArr = auth_header.split(" ") 121 | if (not auth_tokenArr or auth_tokenArr[0] != 'Bearer' or len(auth_tokenArr) != 2): 122 | abort(401, 'Token错误或已过期,请重新登录') 123 | else: 124 | auth_token = auth_tokenArr[1] 125 | payload = cls.__decode_auth_token(cls, auth_token) 126 | if not isinstance(payload, str): 127 | user_id = payload['data']['user_key'] 128 | userInfo = user_mgr.get_user_by_id(user_id) 129 | if (userInfo is None): 130 | abort(401, '找不到该用户信息') 131 | else: 132 | if True: 133 | return payload['data']['user_key'] 134 | else: 135 | abort(401, 'Token已更改,请重新登录获取') 136 | else: 137 | abort(401, 'Token错误或已过期,请重新登录') 138 | else: 139 | abort(401, '没有提供认证token') 140 | -------------------------------------------------------------------------------- /utils/fun_name_to_enum.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: fun_name_to_enum.py 6 | @create date: 2019-10-27 14:41 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | from enum import Enum, unique 12 | 13 | 14 | @unique 15 | class functionName(Enum): 16 | # 通用的 17 | success = '成功' 18 | fail = '失败' 19 | 20 | get_version = '获取系统版本信息' 21 | 22 | """ 23 | 用户管理 24 | """ 25 | # ===================================== 用户管理 start ======================================= 26 | login = '用户登录' 27 | logout = '退出登录' 28 | get_users = '分页获取所有用户数据' 29 | get_user_info_by_id = '获取单个用户数据' 30 | add_user = '添加用户' 31 | update_user = '修改用户' 32 | delete_user = '删除用户' 33 | reset_password = '重置密码' 34 | update_user_password = '修改用户密码' 35 | get_all_users = '获取所有用户数据' 36 | update_header_user_info = '修改基本资料' 37 | # ===================================== 用户管理 end ======================================== 38 | 39 | # ===================================== 用户组管理 start ======================================= 40 | get_user_groups = '获取所有的用户组数据' 41 | get_pages_user_group = '分页获取用户组数据' 42 | get_user_group_role_by_id = '获取用户组的角色数据' 43 | add_user_group = '添加用户组' 44 | delete_user_group = '删除用户组' 45 | update_user_group = '修改用户组' 46 | get_user_group_user_by_id = '获取用户组下面的员工数据' 47 | add_user_group_staff = '用户组增加人员' 48 | del_user_group_staff = '用户组移除人员' 49 | add_user_group_roles = '添加用户组角色' 50 | remove_user_group_roles = '删除用户组角色' 51 | 52 | # ===================================== 用户组管理 end ============================================ 53 | 54 | # ===================================== 部门管理 start =========================================== 55 | get_department = '获取所有部门数据' 56 | add_department = '添加部门' 57 | update_department = '修改部门' 58 | delete_department = '删除部门' 59 | get_dpt_user_info_by_id = '获取部门下的员工数据' 60 | department_add_staff = '部门增加人员' 61 | delete_department_staff = '移除部门人员' 62 | # ===================================== 部门管理 end ========================================== 63 | 64 | # ===================================== 角色权限管理 start ======================================= 65 | get_user_permission_info = '获取用户普通权限' 66 | get_data_permission_info = '获取用户数据权限' 67 | get_roles = '获取所有的角色数据' 68 | add_role = '添加角色' 69 | update_role = '修改角色' 70 | delete_role = '删除角色' 71 | add_role_permission = '给角色分配权限' 72 | get_role_permission_info = '获取角色的权限数据' 73 | # ===================================== 角色权限管理 end ======================================= 74 | 75 | 76 | -------------------------------------------------------------------------------- /utils/log_helper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: log_helper.py 6 | @create date: 2019-10-27 14:19 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description:调试代码日志打印 10 | """ 11 | 12 | import logging 13 | import os 14 | import logging.handlers 15 | 16 | # 1.创建1个logger: 17 | lg = logging.getLogger("Error") 18 | 19 | 20 | def init_log(): 21 | log_path = os.getcwd() + "/var/log" 22 | try: 23 | if not os.path.exists(log_path): 24 | os.makedirs(log_path) 25 | except: 26 | print("创建日志目录失败") 27 | exit(1) 28 | if len(lg.handlers) == 0: # 避免重复 29 | # 2.创建handler(负责输出,输出到屏幕streamhandler,输出到文件filehandler) 30 | filename = os.path.join(log_path, 'user_api.log') 31 | fh = logging.FileHandler(filename, mode="a", encoding="utf-8") # 默认mode 为a模式,默认编码方式为utf-8 32 | sh = logging.StreamHandler() 33 | # 3.创建formatter: 34 | formatter = logging.Formatter( 35 | fmt='%(asctime)s - %(levelname)s - Model:%(filename)s - Fun:%(funcName)s - Message:%(message)s - Line:%(lineno)d') 36 | # 4.绑定关系:①logger绑定handler 37 | lg.addHandler(fh) 38 | lg.addHandler(sh) 39 | # # ②为handler绑定formatter 40 | fh.setFormatter(formatter) 41 | sh.setFormatter(formatter) 42 | # # 5.设置日志级别(日志级别两层关卡必须都通过,日志才能正常记录) 43 | lg.setLevel(40) 44 | fh.setLevel(40) 45 | sh.setLevel(40) 46 | -------------------------------------------------------------------------------- /utils/status_code.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: status_code.py 6 | @create date: 2019-10-27 14:21 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: 10 | """ 11 | 12 | 13 | class responseCode(object): 14 | @property 15 | def SUCCESS(self): 16 | return {'code': 200, 'msg': '请求成功'} 17 | 18 | @property 19 | def LOGIN_IS_FAIL(self): 20 | return {'code': 1001, 'msg': '用户名或者密码错误'} 21 | 22 | @property 23 | def PASS_WORD_INFO_NOT_FILL(self): 24 | return {'code': 1002, 'msg': '密码信息填写完整'} 25 | 26 | @property 27 | def TWO_PASS_WORD_DIFFERENT(self): 28 | return {'code': 1003, 'msg': '两次密码不一致'} 29 | 30 | @property 31 | def OLD_PASS_WORD_IS_NOT_FAIL(self): 32 | return {'code': 1004, 'msg': '旧密码不正确'} 33 | 34 | @property 35 | def LOGIN_FAIL(self): 36 | return {'code': 1005, 'msg': '登录失败请联系管理员'} 37 | 38 | @property 39 | def PASS_WORD_RESET_FAIL(self): 40 | return {'code': 1006, 'msg': '密码重置失败'} 41 | 42 | @property 43 | def USER_NOT_EXIST(self): 44 | return {'code': 1007, 'msg': '用户不存在'} 45 | 46 | @property 47 | def IMPORT_CSV_FAIL(self): 48 | return {'code': 1008, 'msg': '导入数据失败'} 49 | 50 | @property 51 | def IMPORT_CSV_SUCCESS(self): 52 | return {'code': 1009, 'msg': '导入数据成功'} 53 | 54 | @property 55 | def RECORD_EXIST(self): 56 | return {'code': 1010, 'msg': '记录已存在'} 57 | 58 | @property 59 | def ADD_DATA_FAIL(self): 60 | return {'code': 1011, 'msg': '添加数据失败'} 61 | 62 | @property 63 | def UPDATE_DATA_FAIL(self): 64 | return {'code': 1012, 'msg': '修改数据失败'} 65 | 66 | @property 67 | def DELETE_DATA_FAIL(self): 68 | return {'code': 1013, 'msg': '删除数据失败'} 69 | 70 | @property 71 | def GET_DATA_FAIL(self): 72 | return {'code': 1014, 'msg': '获取数据失败'} 73 | 74 | @property 75 | def REQUEST_VERSION_ISEXISTENCE(self): 76 | return {'code': 1015, 'msg': '请求的版本不存在'} 77 | 78 | @property 79 | def ALREADY_HANDLED(self): 80 | return {'code': 1016, 'msg': '参数类型错误'} 81 | 82 | @property 83 | def DATA_IS_NOT_EXIST(self): 84 | return {'code': 1017, 'msg': '数据不存在'} 85 | 86 | @property 87 | def REQUEST_PARAM_MISSED(self): 88 | return {'code': 1018, 'msg': '请求参数缺失'} 89 | 90 | @property 91 | def REQUEST_PARAM_FORMAT_ERROR(self): 92 | return {'code': 1019, 'msg': '请求参数格式错误'} 93 | 94 | @property 95 | def OPENTSDB_ERROR(self): 96 | return {'code': 1020, 'msg': 'opentsdb服务器错误'} 97 | 98 | @property 99 | def DATA_BASE_ERROR(self): 100 | return {'code': 1021, 'msg': "数据库连接失败"} 101 | 102 | @property 103 | def NOT_FOUND(self): 104 | return {'code': 404, 'msg': 'HTTP 404 Not Found'} 105 | 106 | @property 107 | def BAD_REQUEST(self): 108 | return {'code': 400, 'msg': 'HTTP 400 Bad Request'} 109 | 110 | @property 111 | def FORBIDDEND(self): 112 | return {'code': 403, 'msg': 'HTTP 403 Forbidden'} 113 | 114 | @property 115 | def WRONGVALUE(self): 116 | return {'code': 1022, 'msg': '参数值超出规定范围'} 117 | 118 | @property 119 | def CHECK_EXIST_ERROR(self): 120 | return {'code': 1023, 'msg': '验证数据错误'} 121 | 122 | @property 123 | def EXCEPTION_DB(self): 124 | return {'code': 1024, 'msg': '数据库操作异常'} 125 | 126 | 127 | response_code = responseCode() 128 | -------------------------------------------------------------------------------- /utils/xml_json_process.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: UTF-8 -* 3 | """ 4 | @author:li-boss 5 | @file_name: xml_json_process.py 6 | @create date: 2019-10-27 14:22 7 | @blog https://leezhonglin.github.io 8 | @csdn https://blog.csdn.net/qq_33196814 9 | @file_description: xml和json相互转换 10 | """ 11 | 12 | import json 13 | from json import JSONDecodeError 14 | 15 | import xmltodict 16 | 17 | from common.common_response_code import response_code 18 | 19 | 20 | def xml_to_json(xml_str): 21 | """ 22 | xml转JSON 23 | :param xml_str: 24 | :return: 25 | """ 26 | # parse是的xml解析器 27 | xml_parse = xmltodict.parse(xml_str) 28 | # json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。 29 | # dumps()方法的ident=1,格式化json 30 | json_str = json.dumps(xml_parse, indent=1) 31 | return json_str 32 | 33 | 34 | def json_to_xml(json_str): 35 | """ 36 | JSON转换为xml 37 | :param json_str: 38 | :return: 39 | """ 40 | # xmltodict库的unparse()json转xml 41 | # 参数pretty 是格式化xml 42 | xml_str = xmltodict.unparse(json_str, pretty=1) 43 | return xml_str 44 | 45 | 46 | def is_none(request_param): 47 | """ 48 | 过滤参数中为None的数据 49 | :param request_param: 50 | :return: 51 | """ 52 | if isinstance(request_param, list): 53 | for index, a in enumerate(request_param): 54 | if isinstance(a, str): 55 | b = request_param.copy() 56 | if a == None: 57 | del b[index] 58 | else: 59 | c = a.copy() 60 | for k, v in c.items(): 61 | if v == None: 62 | del a[k] 63 | if isinstance(v, list): 64 | b = v.copy() 65 | for index, a in enumerate(b): 66 | if a == None: 67 | del v[index] 68 | if isinstance(request_param, dict): 69 | c = request_param.copy() 70 | for k, v in c.items(): 71 | if v == None: 72 | del request_param[k] 73 | if isinstance(v, list): 74 | b = v.copy() 75 | for index, a in enumerate(b): 76 | if a == None: 77 | del v[index] 78 | 79 | return request_param 80 | -------------------------------------------------------------------------------- /var/log/user_api.log: -------------------------------------------------------------------------------- 1 | 2019-10-27 15:48:34,018 - ERROR - Model:db_user_mgr.py - Fun:get_user_by_name - Message:(1146, "Table 'user_api.task_group' doesn't exist") - Line:318 2 | 2019-10-27 15:48:34,018 - ERROR - Model:interface_login.py - Fun:post - Message:'responseCode' object has no attribute 'LOGIN_IS_FAILD' - Line:61 3 | --------------------------------------------------------------------------------