-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go.tmpl
61 lines (51 loc) · 1.93 KB
/
client.go.tmpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
{{- define "client" -}}
{{- $typeMap := .TypeMap -}}
{{- if .Services}}
#
# Imports
#
import json
import urllib.request
from urllib.error import HTTPError
from typing import Optional, Dict
#
# Client
#
{{- range .Services}}
class {{.Name}}:
CONTENT_TYPE_JSON = {'Content-Type': 'application/json'}
def __init__(self, hostname: str):
self.hostname = hostname
self.path = '/rpc/{{.Name}}/'
def url(self, name: str) -> str:
return f"{self.hostname}{self.path}{name}"
def _send_request(self, method_name: str, args, headers: Optional[Dict[str, str]] = None):
url = self.url(method_name)
headers = headers or self.CONTENT_TYPE_JSON
body = json.dumps(args.to_dict()).encode('utf-8') # Encode to bytes
req = urllib.request.Request(url, data=body, headers=headers)
try:
with urllib.request.urlopen(req) as response:
response_data = json.loads(response.read().decode('utf-8'))
return response_data
except HTTPError as ex: # Catch only HTTPError
error_body = ex.read().decode('utf-8') # Read the response body
try:
error_data = json.loads(error_body) # Attempt to parse it as JSON
except json.JSONDecodeError:
error_data = {"error": "Unknown", "message": error_body}
# Directly raise your custom exception
raise WebrpcRequestFailedError(
message=error_data.get('msg', 'Unknown error'),
code=error_data.get('code', -1),
cause=error_data.get('cause'),
status=error_data.get('status')
)
{{- range .Methods}}
def {{.Name}}(self, args: {{.Name}}Args, headers: Optional[Dict[str, str]] = None):
response_data = self._send_request('{{.Name}}', args, headers)
return {{.Name}}Return(**response_data)
{{- end}}
{{- end}}
{{- end}}
{{- end -}}