[英]Python wrapper for pricing API
I wrote a python wrapper for a pricing API.我为定价 API 编写了一个 python 包装器。 At the end of my code I make a method calls to the API endpoints.
在我的代码末尾,我对 API 端点进行了方法调用。 There are 4 different API endpoints.
有 4 个不同的 API 端点。 When I do a test run and hit the endpoints 3 out of the 4 endpoints return a JSON response except for the third one called "test3".
当我进行测试运行并命中端点时,4 个端点中的 3 个返回 JSON 响应,第三个称为“test3”除外。 Maybe its the way I formatted the URL response in my f-string?
也许是我在 f 字符串中格式化 URL 响应的方式? I have tried to format it differently but still keep getting this error.
我试图以不同的方式对其进行格式化,但仍然不断收到此错误。
Error here: enter image description here此处出错:在此处输入图片说明
import http.client
import urllib.request, urllib.parse, urllib.error
import json
import base64
def loadJson(response):
body = response.read()
if body == "" or body is None:
print(("Empty response found with status " + str(response.status)))
return {}
else:
return json.loads(body)
class data_pricing_client:
def __init__(self, host, clientId, clientSecret):
conn = http.client.HTTPSConnection("sso.lukka.tech")
path = "/oauth2/aus1imo2fqcx5Ik4Q0h8/v1/token"
encodedData = base64.b64encode(bytes(f"{clientId}:{clientSecret}", "ISO-8859-1")).decode("ascii")
authHeader = "Basic " + encodedData
headers = {
"Authorization": authHeader,
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
}
params = urllib.parse.urlencode({
"grant_type": "client_credentials",
"scope": "pricing"
})
conn.request("POST", path, params, headers)
response = conn.getresponse()
if response.status != 200:
raise ApiErrorException(response.status, "Failed to get access token")
self.host = host
self.accessToken = loadJson(response)["access_token"]
def default_headers(self):
return {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + self.accessToken
}
def send_message(self,path):
conn = http.client.HTTPSConnection(self.host)
headers = self.default_headers()
conn.request("GET", path, None, headers)
response_json = loadJson(conn.getresponse())
conn.close()
return response_json
def get_available_sources(self):
path = "/v1/pricing/sources"
return self.send_message(path)
def get_source_details(self, sourceId):
path = f"/v1/pricing/sources/{sourceId}/prices"
return self.send_message(path)
def get_latest_prices(self, sourceId, pairCodes=None, asOf=None, variances=False):
query_params = {
"pairCodes":pairCodes,
"asOf":asOf
}
path = f"/v1/pricing/sources/{sourceId}/prices/{'/variances' if variances else ''}?{urllib.parse.urlencode({k: v for k, v in query_params.items() if v is not None})}"
print(path)
return self.send_message(path)
def get_historical_prices(self, sourceId, pairCode, from_ts=None, to_ts=None, fill=None, limit=None, variances=False):
query_params = {
"from":from_ts,
"to":to_ts,
"fill": fill,
"limit": limit
}
path = f"/v1/pricing/sources/{sourceId}/prices/pairs/{pairCode}{'/variances' if variances else ''}?{urllib.parse.urlencode({k: v for k, v in query_params.items() if v is not None})}"
print(path)
return self.send_message(path)
class ApiErrorException(Exception):
def __init__(self, status, msg):
self.msg = "Error " + str(status) + ": " + msg
def __str__(self):
return self.msg
if __name__ == '__main__':
from pricing_api_creds import lukka_pricing
c = data_pricing_client(**lukka_pricing)
test1 = c.get_available_sources()
test1 = c.send_message("/v1/pricing/sources")
print(test1)
test2 = c.get_source_details(3000)
test2 = c.send_message("/v1/pricing/sources/")
print(test2)
test3 = c.get_latest_prices(3000)
test3 = c.send_message("v1/pricing/sources/1000/prices")
print(test3)
test4 = c.get_historical_prices(1000, "XBT-USD",)
test4=c.send_message("/v1/pricing/sources/1000/prices/pairs/XBT-USD")
print(test4)
You can see that the error is thrown from the JSONDecoder.可以看到错误是从 JSONDecoder 抛出的。 Possibilities are response is corrupted or the response is not a valid Json that can be mapped.
可能是响应已损坏或响应不是可以映射的有效 Json。 Try logging the response to get an detail idea on it.
尝试记录响应以获取有关它的详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.