diff --git a/.gitignore b/.gitignore index 57148e4..a6f6b87 100644 --- a/.gitignore +++ b/.gitignore @@ -25,4 +25,5 @@ venv/ *.err service_id dist/ -.vscode/ \ No newline at end of file +.vscode/ +build/ \ No newline at end of file diff --git a/example/demo.py b/example/demo.py index 0e0b7f8..56304d1 100644 --- a/example/demo.py +++ b/example/demo.py @@ -5,6 +5,7 @@ from flask_hsrpc.request_parser import BaseSchema, fields from flask_hsrpc.response import ErrorResponse from flask_hsrpc.__version__ import __version__ as hsrpc_version +import logging class Config(object): @@ -56,6 +57,15 @@ def log_demo(): } +@rpc.route(description="Log Demo 2") +def log_demo2(): + logger = logging.getLogger("flask.app") + logger.info("I am write log to file") + return { + "status": "ok" + } + + @rpc.route(description="Request Demo") def request_demo(): rel, err = rpc.apirequests.post("Demo", "log_demo") diff --git a/flask_hsrpc/__version__.py b/flask_hsrpc/__version__.py index 25e6daa..39d461e 100644 --- a/flask_hsrpc/__version__.py +++ b/flask_hsrpc/__version__.py @@ -1,2 +1,2 @@ # -*- coding: utf-8 -*- -__version__ = '0.1.14' +__version__ = '0.1.15' diff --git a/flask_hsrpc/api_requests.py b/flask_hsrpc/api_requests.py index f04742e..7e60336 100644 --- a/flask_hsrpc/api_requests.py +++ b/flask_hsrpc/api_requests.py @@ -3,6 +3,15 @@ from .response import ErrorResponse +class ApiRequestException(Exception): + def __init__(self, **kwargs): + self.code = kwargs.get("code") + self.message = kwargs.get("message") + self._request = kwargs.get("_request") + self.kwargs = kwargs + super().__init__(f"Hsrpc Api Request Error: {self.code} - {self.message} ({self._request})") + + class ApiRequests(object): consul = None @@ -14,13 +23,13 @@ def __init__(self, consul=None, set_default=True): def _base_request(self, method, sys_name, func_name, model_name="default", prefix="", protocol="http", **kwargs): node = self.consul.get_health_service_node_by_balance(sys_name) + uri = [prefix if prefix and prefix != "/" else ""] + if model_name and model_name != "default": + uri.append(model_name.lower()) + uri.append(func_name) if node: host = node["Service"]["Address"] port = node["Service"]["Port"] - uri = [prefix if prefix and prefix != "/" else ""] - if model_name and model_name != "default": - uri.append(model_name.lower()) - uri.append(func_name) url = "{protocol}://{host}:{port}{uri}".format(protocol=protocol, host=host, port=port, uri="/".join(uri)) resp = request(method, url, **kwargs) @@ -28,13 +37,20 @@ def _base_request(self, method, sys_name, func_name, model_name="default", prefi rel = resp.json() error = rel.get("error") if error: - error["code"] = "request error: " + error["code"] - error["message"] = f"request [{method}] - {sys_name} - {'/'.join(uri)} ({error['message']})" - return rel.get("data"), ErrorResponse.convert_by_dict(rel.get("error"), resp.status_code) - except Exception: - raise Exception("request {0}-{1}-{2} fail".format(sys_name, model_name, func_name), resp.text) + error["_request"] = f"[{method.upper()}] - {sys_name} - {host}:{port} - {'/'.join(uri)}" + return rel.get("data"), ApiRequestException(**error) + except Exception as ex: + return None, ApiRequestException(**{ + "code": "request failed", + "message": str(ex), + "_request": f"[{method.upper()}] - {sys_name} - {host}:{port} - {'/'.join(uri)}" + }) else: - raise Exception("[{0}]:not find alive system".format(sys_name)) + return None, ApiRequestException(**{ + "code": "request failed", + "message": f"[{sys_name}: not find alive system]", + "_request": f"[{method.upper()}] - {sys_name} - - {'/'.join(uri)}" + }) def get(self, sys_name, func_name, model_name="default", prefix="", protocol="http", params=None, **kwargs): return self._base_request("get", sys_name, func_name, model_name, prefix, protocol, params=params, **kwargs) diff --git a/flask_hsrpc/response.py b/flask_hsrpc/response.py index cda7992..e961d00 100644 --- a/flask_hsrpc/response.py +++ b/flask_hsrpc/response.py @@ -21,7 +21,7 @@ def response_factory(data=None, error=None): "detail": None }, "data": data - }) + }), 500 else: return jsonify({ "error": None, @@ -50,7 +50,7 @@ def convert_by_dict(err, status_code=400): return None def __str__(self): - return "ErrorResponse({},{},{}) {}".format(self.code,self.message,self.detail,self.status_code) + return "ErrorResponse({},{},{}) {}".format(self.code, self.message, self.detail, self.status_code) def page_response(data, total):