Skip to content
Snippets Groups Projects
Commit bd3c686c authored by Vincent Texier's avatar Vincent Texier
Browse files

issue #56 WIP - Can choose the response type for Client.get()

parent be9c65b7
No related branches found
No related tags found
No related merge requests found
......@@ -11,6 +11,12 @@ import duniterpy.api.endpoint as endpoint
logger = logging.getLogger("duniter")
# Response type constants
RESPONSE_JSON = 'json'
RESPONSE_TEXT = 'text'
RESPONSE_AIOHTTP = 'aiohttp'
# jsonschema validator
ERROR_SCHEMA = {
"type": "object",
"properties": {
......@@ -190,12 +196,13 @@ class Client:
self.session = session
self.proxy = proxy
async def get(self, url_path: str, params: dict = None, schema: dict = None)-> any:
async def get(self, url_path: str, params: dict = None, rtype: str = RESPONSE_JSON, schema: dict = None)-> any:
"""
Get request on self.endpoint + url_path
:param url_path: Url encoded path following the endpoint
:param params: Url query string parameters dictionary
:param rtype: Response type
:param schema: Json Schema to validate response (optional, default None)
:return:
"""
......@@ -204,11 +211,20 @@ class Client:
client = API(self.endpoint.conn_handler(self.session, self.proxy), '')
# get aiohttp response
response = await client.requests_get(url_path, **params)
# if schema supplied...
if schema is not None:
return await parse_response(response, schema)
else:
# validate response
await parse_response(response, schema)
# return the chosen type
if rtype == RESPONSE_AIOHTTP:
return response
elif rtype == RESPONSE_TEXT:
return await response.text()
elif rtype == RESPONSE_JSON:
return await response.json()
async def close(self):
......
import asyncio
from duniterpy.api.client import Client
from duniterpy.api.client import Client, RESPONSE_AIOHTTP
from duniterpy.api import bma
# CONFIG #######################################
......@@ -19,10 +19,6 @@ async def main():
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
# Get the node summary infos (direct REST GET request)
response = await client.get('node/summary')
print(response)
# Get the node summary infos by dedicated method (with json schema validation)
response = await client(bma.node.summary)
print(response)
......@@ -39,6 +35,33 @@ async def main():
response = await client(bma.blockchain.block, 10)
print(response)
# jsonschema validator
summary_schema = {
"type": "object",
"properties": {
"duniter": {
"type": "object",
"properties": {
"software": {
"type": "string"
},
"version": {
"type": "string",
},
"forkWindowSize": {
"type": "number"
}
},
"required": ["software", "version"]
},
},
"required": ["duniter"]
}
# Get the node summary infos (direct REST GET request)
response = await client.get('node/summary', rtype=RESPONSE_AIOHTTP, schema=summary_schema)
print(response)
# Close client aiohttp session
await client.close()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment