Skip to content

Commit

Permalink
v0.1.15
Browse files Browse the repository at this point in the history
  • Loading branch information
AloneFire committed Jul 24, 2019
1 parent 6d5bf70 commit 63c182f
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 14 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ venv/
*.err
service_id
dist/
.vscode/
.vscode/
build/
10 changes: 10 additions & 0 deletions example/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion flask_hsrpc/__version__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# -*- coding: utf-8 -*-
__version__ = '0.1.14'
__version__ = '0.1.15'
36 changes: 26 additions & 10 deletions flask_hsrpc/api_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -14,27 +23,34 @@ 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)

try:
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)
Expand Down
4 changes: 2 additions & 2 deletions flask_hsrpc/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def response_factory(data=None, error=None):
"detail": None
},
"data": data
})
}), 500
else:
return jsonify({
"error": None,
Expand Down Expand Up @@ -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):
Expand Down

0 comments on commit 63c182f

Please sign in to comment.