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

[enh] #140 remove asyncio and aiohttp in examples

except for the request_data_async.py example
parent 61b31970
No related branches found
No related tags found
No related merge requests found
This commit is part of merge request !118. Comments created here will be created in the context of that merge request.
...@@ -15,13 +15,8 @@ You should have received a copy of the GNU General Public License ...@@ -15,13 +15,8 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import asyncio
import json import json
import sys import sys
from _socket import gaierror
import aiohttp
import jsonschema import jsonschema
from jsonschema import ValidationError from jsonschema import ValidationError
...@@ -42,7 +37,7 @@ CURRENCY = "g1-test" ...@@ -42,7 +37,7 @@ CURRENCY = "g1-test"
################################################ ################################################
async def main(): def main():
""" """
Main code Main code
""" """
...@@ -63,7 +58,7 @@ async def main(): ...@@ -63,7 +58,7 @@ async def main():
# Create Client from endpoint string in Duniter format # Create Client from endpoint string in Duniter format
try: try:
ws2p_endpoint = await generate_ws2p_endpoint(BMAS_ENDPOINT) ws2p_endpoint = generate_ws2p_endpoint(BMAS_ENDPOINT)
except ValueError as e: except ValueError as e:
print(e) print(e)
return return
...@@ -71,7 +66,7 @@ async def main(): ...@@ -71,7 +66,7 @@ async def main():
try: try:
# Create a Web Socket connection # Create a Web Socket connection
ws = await client.connect_ws() ws = client.connect_ws()
print("Successfully connected to the web socket endpoint") print("Successfully connected to the web socket endpoint")
...@@ -79,7 +74,7 @@ async def main(): ...@@ -79,7 +74,7 @@ async def main():
try: try:
# Resolve handshake # Resolve handshake
print("Handshake...") print("Handshake...")
await handshake(ws, signing_key, CURRENCY) handshake(ws, signing_key, CURRENCY)
except ValidationError as exception: except ValidationError as exception:
print(exception.message) print(exception.message)
print("HANDSHAKE FAILED !") print("HANDSHAKE FAILED !")
...@@ -92,22 +87,13 @@ async def main(): ...@@ -92,22 +87,13 @@ async def main():
while loop: while loop:
print("Waiting message...") print("Waiting message...")
# Wait and capture next message # Wait and capture next message
data = await ws.receive_json() data = ws.receive_json()
print("Message received:") print("Message received:")
print(json.dumps(data, indent=2)) print(json.dumps(data, indent=2))
# Close session
await client.close()
except (aiohttp.WSServerHandshakeError, ValueError) as e:
print("Websocket handshake {0} : {1}".format(type(e).__name__, str(e)))
except (aiohttp.ClientError, gaierror, TimeoutError) as e:
print("{0} : {1}".format(str(e), ws2p_endpoint.inline()))
except jsonschema.ValidationError as e: except jsonschema.ValidationError as e:
print("{:}:{:}".format(str(e.__class__.__name__), str(e))) print("{:}:{:}".format(str(e.__class__.__name__), str(e)))
await client.close()
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. if __name__ == "__main__":
# ( https://docs.python.org/3/library/asyncio.html ) main()
asyncio.get_event_loop().run_until_complete(main())
...@@ -15,7 +15,6 @@ You should have received a copy of the GNU General Public License ...@@ -15,7 +15,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import asyncio
from duniterpy.api.client import Client, RESPONSE_HTTP from duniterpy.api.client import Client, RESPONSE_HTTP
from duniterpy.api import bma from duniterpy.api import bma
...@@ -30,7 +29,7 @@ BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443" ...@@ -30,7 +29,7 @@ BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443"
################################################ ################################################
async def main(): def main():
""" """
Main code (synchronous requests) Main code (synchronous requests)
""" """
...@@ -39,22 +38,22 @@ async def main(): ...@@ -39,22 +38,22 @@ async def main():
# Get the node summary infos by dedicated method (with json schema validation) # Get the node summary infos by dedicated method (with json schema validation)
print("\nCall bma.node.summary:") print("\nCall bma.node.summary:")
response = await client(bma.node.summary) response = client(bma.node.summary)
print(response) print(response)
# Get the money parameters located in the first block # Get the money parameters located in the first block
print("\nCall bma.blockchain.parameters:") print("\nCall bma.blockchain.parameters:")
response = await client(bma.blockchain.parameters) response = client(bma.blockchain.parameters)
print(response) print(response)
# Get the current block # Get the current block
print("\nCall bma.blockchain.current:") print("\nCall bma.blockchain.current:")
response = await client(bma.blockchain.current) response = client(bma.blockchain.current)
print(response) print(response)
# Get the block number 10 # Get the block number 10
print("\nCall bma.blockchain.block(10):") print("\nCall bma.blockchain.block(10):")
response = await client(bma.blockchain.block, 10) response = client(bma.blockchain.block, 10)
print(response) print(response)
# jsonschema validator # jsonschema validator
...@@ -76,15 +75,9 @@ async def main(): ...@@ -76,15 +75,9 @@ async def main():
# Get the node summary infos (direct REST GET request) # Get the node summary infos (direct REST GET request)
print("\nCall direct get on node/summary") print("\nCall direct get on node/summary")
response = await client.get( response = client.get("node/summary", rtype=RESPONSE_HTTP, schema=summary_schema)
"node/summary", rtype=RESPONSE_HTTP, schema=summary_schema
)
print(response) print(response)
# Close client aiohttp session
await client.close()
if __name__ == "__main__":
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. main()
# ( https://docs.python.org/3/library/asyncio.html )
asyncio.get_event_loop().run_until_complete(main())
...@@ -35,6 +35,10 @@ async def print_response(request): ...@@ -35,6 +35,10 @@ async def print_response(request):
print(await request) print(await request)
async def coroutine(function, *args, **kwargs):
return function(*args, **kwargs)
async def main(): async def main():
""" """
Main code (asynchronous requests) Main code (asynchronous requests)
...@@ -52,12 +56,12 @@ async def main(): ...@@ -52,12 +56,12 @@ async def main():
# Get the node summary infos by dedicated method (with json schema validation) # Get the node summary infos by dedicated method (with json schema validation)
print("\nCall bma.node.summary:") print("\nCall bma.node.summary:")
task = asyncio.ensure_future(client(bma.node.summary)) task = asyncio.ensure_future(coroutine(client, bma.node.summary))
tasks.append(task) tasks.append(task)
# Get the money parameters located in the first block # Get the money parameters located in the first block
print("\nCall bma.blockchain.parameters:") print("\nCall bma.blockchain.parameters:")
task = asyncio.ensure_future(client(bma.blockchain.parameters)) task = asyncio.ensure_future(coroutine(client, bma.blockchain.parameters))
tasks.append(task) tasks.append(task)
responses = await asyncio.gather(*tasks) responses = await asyncio.gather(*tasks)
...@@ -65,9 +69,6 @@ async def main(): ...@@ -65,9 +69,6 @@ async def main():
print("\nResponses:") print("\nResponses:")
print(responses) print(responses)
# Close client aiohttp session
await client.close()
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. # Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data.
# ( https://docs.python.org/3/library/asyncio.html ) # ( https://docs.python.org/3/library/asyncio.html )
......
...@@ -15,8 +15,6 @@ You should have received a copy of the GNU General Public License ...@@ -15,8 +15,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import asyncio
from duniterpy.api.client import Client from duniterpy.api.client import Client
# Duniter4j ES API documentation: https://git.duniter.org/clients/java/duniter4j/blob/master/src/site/markdown/ES_API.md # Duniter4j ES API documentation: https://git.duniter.org/clients/java/duniter4j/blob/master/src/site/markdown/ES_API.md
...@@ -34,7 +32,7 @@ ES_USER_ENDPOINT = "ES_USER_API g1-test.data.duniter.fr 443" ...@@ -34,7 +32,7 @@ ES_USER_ENDPOINT = "ES_USER_API g1-test.data.duniter.fr 443"
################################################ ################################################
async def main(): def main():
""" """
Main code (synchronous requests) Main code (synchronous requests)
""" """
...@@ -43,19 +41,16 @@ async def main(): ...@@ -43,19 +41,16 @@ async def main():
# Get the current node (direct REST GET request) # Get the current node (direct REST GET request)
print("\nGET g1-test/block/current/_source:") print("\nGET g1-test/block/current/_source:")
response = await client.get("g1-test/block/current/_source") response = client.get("g1-test/block/current/_source")
print(response) print(response)
# Get the node number 2 with only selected fields (direct REST GET request) # Get the node number 2 with only selected fields (direct REST GET request)
print("\nGET g1-test/block/2/_source:") print("\nGET g1-test/block/2/_source:")
response = await client.get( response = client.get(
"g1-test/block/2/_source", {"_source": "number,hash,dividend,membersCount"} "g1-test/block/2/_source", {"_source": "number,hash,dividend,membersCount"}
) )
print(response) print(response)
# Close client aiohttp session
await client.close()
# Create Client from endpoint string in Duniter format # Create Client from endpoint string in Duniter format
client = Client(ES_USER_ENDPOINT) client = Client(ES_USER_ENDPOINT)
...@@ -64,13 +59,9 @@ async def main(): ...@@ -64,13 +59,9 @@ async def main():
# Get the profil of a public key (direct REST GET request) # Get the profil of a public key (direct REST GET request)
print("\nGET user/profile/{0}/_source:".format(pubkey)) print("\nGET user/profile/{0}/_source:".format(pubkey))
response = await client.get("user/profile/{0}/_source".format(pubkey.strip(" \n"))) response = client.get("user/profile/{0}/_source".format(pubkey.strip(" \n")))
print(response) print(response)
# Close client aiohttp session
await client.close()
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. if __name__ == "__main__":
# ( https://docs.python.org/3/library/asyncio.html ) main()
asyncio.get_event_loop().run_until_complete(main())
...@@ -16,13 +16,13 @@ GVA_ENDPOINT = "GVA S g1.librelois.fr 443 gva" ...@@ -16,13 +16,13 @@ GVA_ENDPOINT = "GVA S g1.librelois.fr 443 gva"
################################################ ################################################
async def main(): def main():
client = Client(GVA_ENDPOINT) client = Client(GVA_ENDPOINT)
# get query to get schema from api # get query to get schema from api
query = get_introspection_query(False) query = get_introspection_query(False)
# get schema from api # get schema from api
response = await client.query(query) response = client.query(query)
# convert response dict to schema # convert response dict to schema
schema = build_client_schema(response["data"]) schema = build_client_schema(response["data"])
...@@ -48,16 +48,12 @@ async def main(): ...@@ -48,16 +48,12 @@ async def main():
sys.exit(1) sys.exit(1)
# send valid query to api # send valid query to api
response = await client.query(query) response = client.query(query)
if isinstance(response, str): if isinstance(response, str):
print(response) print(response)
else: else:
print(json.dumps(response, indent=2)) print(json.dumps(response, indent=2))
# Close client aiohttp session
await client.close()
if __name__ == "__main__":
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. main()
# ( https://docs.python.org/3/library/asyncio.html )
asyncio.get_event_loop().run_until_complete(main())
...@@ -15,11 +15,8 @@ You should have received a copy of the GNU General Public License ...@@ -15,11 +15,8 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import asyncio
import json import json
from _socket import gaierror
import aiohttp
import jsonschema import jsonschema
from duniterpy.api import bma from duniterpy.api import bma
...@@ -36,7 +33,7 @@ BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443" ...@@ -36,7 +33,7 @@ BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443"
################################################ ################################################
async def main(): def main():
""" """
Main code Main code
""" """
...@@ -44,8 +41,8 @@ async def main(): ...@@ -44,8 +41,8 @@ async def main():
client = Client(BMAS_ENDPOINT) client = Client(BMAS_ENDPOINT)
try: try:
# Create Web Socket connection on block path (async method) # Create Web Socket connection on block path (method)
ws = await client(bma.ws.block) # Type: WSConnection ws = client(bma.ws.block) # Type: WSConnection
print("Connected successfully to web socket block path") print("Connected successfully to web socket block path")
...@@ -54,23 +51,14 @@ async def main(): ...@@ -54,23 +51,14 @@ async def main():
while loop: while loop:
print("Waiting message...") print("Waiting message...")
# Wait and capture next message # Wait and capture next message
data = await ws.receive_json() data = ws.receive_json()
jsonschema.validate(data, bma.ws.WS_BLOCK_SCHEMA) jsonschema.validate(data, bma.ws.WS_BLOCK_SCHEMA)
print("Message received:") print("Message received:")
print(json.dumps(data, indent=2)) print(json.dumps(data, indent=2))
# Close session
await client.close()
except (aiohttp.WSServerHandshakeError, ValueError) as e:
print("Websocket block {0} : {1}".format(type(e).__name__, str(e)))
except (aiohttp.ClientError, gaierror, TimeoutError) as e:
print("{0} : {1}".format(str(e), BMAS_ENDPOINT))
except jsonschema.ValidationError as e: except jsonschema.ValidationError as e:
print("{:}:{:}".format(str(e.__class__.__name__), str(e))) print("{:}:{:}".format(str(e.__class__.__name__), str(e)))
await client.close()
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. if __name__ == "__main__":
# ( https://docs.python.org/3/library/asyncio.html ) main()
asyncio.get_event_loop().run_until_complete(main())
...@@ -15,14 +15,10 @@ You should have received a copy of the GNU General Public License ...@@ -15,14 +15,10 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import asyncio
import json import json
import time import time
import sys import sys
from _socket import gaierror
import aiohttp
import jsonschema import jsonschema
from jsonschema import ValidationError from jsonschema import ValidationError
from typing import Any from typing import Any
...@@ -46,7 +42,7 @@ CURRENCY = "g1-test" ...@@ -46,7 +42,7 @@ CURRENCY = "g1-test"
################################################ ################################################
async def send(ws: WSConnection, request: str, request_id: str, schema: dict) -> Any: def send(ws: WSConnection, request: str, request_id: str, schema: dict) -> Any:
""" """
Send a WS2P request Send a WS2P request
...@@ -57,14 +53,14 @@ async def send(ws: WSConnection, request: str, request_id: str, schema: dict) -> ...@@ -57,14 +53,14 @@ async def send(ws: WSConnection, request: str, request_id: str, schema: dict) ->
:param schema: Validation schema :param schema: Validation schema
""" """
# Send request # Send request
await ws.send_str(request) ws.send_str(request)
# Wait response with request id # Wait response with request id
response = await ws.receive_json() response = ws.receive_json()
while "resId" not in response or ( while "resId" not in response or (
"resId" in response and response["resId"] != request_id "resId" in response and response["resId"] != request_id
): ):
response = await ws.receive_json() response = ws.receive_json()
time.sleep(1) time.sleep(1)
try: try:
# Check response format # Check response format
...@@ -83,7 +79,7 @@ async def send(ws: WSConnection, request: str, request_id: str, schema: dict) -> ...@@ -83,7 +79,7 @@ async def send(ws: WSConnection, request: str, request_id: str, schema: dict) ->
return response return response
async def main(): def main():
""" """
Main code Main code
""" """
...@@ -104,7 +100,7 @@ async def main(): ...@@ -104,7 +100,7 @@ async def main():
# Create Client from endpoint string in Duniter format # Create Client from endpoint string in Duniter format
try: try:
ws2p_endpoint = await generate_ws2p_endpoint(BMAS_ENDPOINT) ws2p_endpoint = generate_ws2p_endpoint(BMAS_ENDPOINT)
except ValueError as e: except ValueError as e:
print(e) print(e)
return return
...@@ -112,13 +108,13 @@ async def main(): ...@@ -112,13 +108,13 @@ async def main():
try: try:
# Create a Web Socket connection # Create a Web Socket connection
ws = await client.connect_ws() ws = client.connect_ws()
print("Successfully connected to the web socket endpoint") print("Successfully connected to the web socket endpoint")
# HANDSHAKE ####################################################### # HANDSHAKE #######################################################
try: try:
await handshake(ws, signing_key, CURRENCY) handshake(ws, signing_key, CURRENCY)
except ValidationError as exception: except ValidationError as exception:
print(exception.message) print(exception.message)
print("HANDSHAKE FAILED !") print("HANDSHAKE FAILED !")
...@@ -127,7 +123,7 @@ async def main(): ...@@ -127,7 +123,7 @@ async def main():
# Send ws2p request # Send ws2p request
print("Send getCurrent() request") print("Send getCurrent() request")
request_id = get_ws2p_challenge()[:8] request_id = get_ws2p_challenge()[:8]
response = await send( response = send(
ws, ws,
requests.get_current(request_id), requests.get_current(request_id),
request_id, request_id,
...@@ -138,7 +134,7 @@ async def main(): ...@@ -138,7 +134,7 @@ async def main():
# Send ws2p request # Send ws2p request
print("Send getBlock(30000) request") print("Send getBlock(30000) request")
request_id = get_ws2p_challenge()[:8] request_id = get_ws2p_challenge()[:8]
response = await send( response = send(
ws, ws,
requests.get_block(request_id, 30000), requests.get_block(request_id, 30000),
request_id, request_id,
...@@ -149,7 +145,7 @@ async def main(): ...@@ -149,7 +145,7 @@ async def main():
# Send ws2p request # Send ws2p request
print("Send getBlocks(30000, 2) request") print("Send getBlocks(30000, 2) request")
request_id = get_ws2p_challenge()[:8] request_id = get_ws2p_challenge()[:8]
response = await send( response = send(
ws, ws,
requests.get_blocks(request_id, 30000, 2), requests.get_blocks(request_id, 30000, 2),
request_id, request_id,
...@@ -160,7 +156,7 @@ async def main(): ...@@ -160,7 +156,7 @@ async def main():
# Send ws2p request # Send ws2p request
print("Send getRequirementsPending(3) request") print("Send getRequirementsPending(3) request")
request_id = get_ws2p_challenge()[:8] request_id = get_ws2p_challenge()[:8]
response = await send( response = send(
ws, ws,
requests.get_requirements_pending(request_id, 3), requests.get_requirements_pending(request_id, 3),
request_id, request_id,
...@@ -168,18 +164,9 @@ async def main(): ...@@ -168,18 +164,9 @@ async def main():
) )
print("Response: " + json.dumps(response, indent=2)) print("Response: " + json.dumps(response, indent=2))
# Close session
await client.close()
except (aiohttp.WSServerHandshakeError, ValueError) as e:
print("Websocket handshake {0} : {1}".format(type(e).__name__, str(e)))
except (aiohttp.ClientError, gaierror, TimeoutError) as e:
print("{0} : {1}".format(str(e), ws2p_endpoint.inline()))
except jsonschema.ValidationError as e: except jsonschema.ValidationError as e:
print("{:}:{:}".format(str(e.__class__.__name__), str(e))) print("{:}:{:}".format(str(e.__class__.__name__), str(e)))
await client.close()
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. if __name__ == "__main__":
# ( https://docs.python.org/3/library/asyncio.html ) main()
asyncio.get_event_loop().run_until_complete(main())
...@@ -15,7 +15,6 @@ You should have received a copy of the GNU General Public License ...@@ -15,7 +15,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import asyncio
import getpass import getpass
import os import os
import sys import sys
...@@ -56,7 +55,7 @@ PROTOCOL_VERSION = 10 ...@@ -56,7 +55,7 @@ PROTOCOL_VERSION = 10
################################################ ################################################
async def get_identity_document( def get_identity_document(
client: Client, current_block: dict, pubkey: str client: Client, current_block: dict, pubkey: str
) -> Optional[Identity]: ) -> Optional[Identity]:
""" """
...@@ -69,7 +68,7 @@ async def get_identity_document( ...@@ -69,7 +68,7 @@ async def get_identity_document(
:rtype: Identity :rtype: Identity
""" """
# Here we request for the path wot/lookup/pubkey # Here we request for the path wot/lookup/pubkey
lookup_data = await client(bma.wot.lookup, pubkey) lookup_data = client(bma.wot.lookup, pubkey)
identity = None identity = None
# parse results # parse results
...@@ -115,7 +114,7 @@ def get_signed_raw_revocation_document( ...@@ -115,7 +114,7 @@ def get_signed_raw_revocation_document(
return revocation.signed_raw() return revocation.signed_raw()
async def main(): def main():
""" """
Main code Main code
""" """
...@@ -123,7 +122,7 @@ async def main(): ...@@ -123,7 +122,7 @@ async def main():
client = Client(BMAS_ENDPOINT) client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection # Get the node summary infos to test the connection
response = await client(bma.node.summary) response = client(bma.node.summary)
print(response) print(response)
# prompt hidden user entry # prompt hidden user entry
...@@ -144,14 +143,13 @@ async def main(): ...@@ -144,14 +143,13 @@ async def main():
sys.exit(0) sys.exit(0)
# capture current block to get currency name # capture current block to get currency name
current_block = await client(bma.blockchain.current) current_block = client(bma.blockchain.current)
# create our Identity document to sign the Certification document # create our Identity document to sign the Certification document
identity = await get_identity_document(client, current_block, pubkey) identity = get_identity_document(client, current_block, pubkey)
if identity is None: if identity is None:
print("Identity not found for pubkey {0}".format(pubkey)) print("Identity not found for pubkey {0}".format(pubkey))
# Close client aiohttp session # Close client aiohttp session
await client.close()
sys.exit(1) sys.exit(1)
# get the revoke document # get the revoke document
...@@ -167,10 +165,6 @@ async def main(): ...@@ -167,10 +165,6 @@ async def main():
# document saved # document saved
print("Revocation document saved in %s" % REVOCATION_DOCUMENT_FILE_PATH) print("Revocation document saved in %s" % REVOCATION_DOCUMENT_FILE_PATH)
# Close client aiohttp session
await client.close()
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. if __name__ == "__main__":
# ( https://docs.python.org/3/library/asyncio.html ) main()
asyncio.get_event_loop().run_until_complete(main())
...@@ -16,7 +16,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. ...@@ -16,7 +16,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import sys import sys
import asyncio
import getpass import getpass
from typing import Optional from typing import Optional
...@@ -36,7 +35,7 @@ BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443" ...@@ -36,7 +35,7 @@ BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443"
################################################ ################################################
async def get_identity_document( def get_identity_document(
client: Client, current_block: dict, pubkey: str client: Client, current_block: dict, pubkey: str
) -> Optional[Identity]: ) -> Optional[Identity]:
""" """
...@@ -49,7 +48,7 @@ async def get_identity_document( ...@@ -49,7 +48,7 @@ async def get_identity_document(
:rtype: Identity :rtype: Identity
""" """
# Here we request for the path wot/lookup/pubkey # Here we request for the path wot/lookup/pubkey
lookup_data = await client(bma.wot.lookup, pubkey) lookup_data = client(bma.wot.lookup, pubkey)
identity = None identity = None
# parse results # parse results
...@@ -99,7 +98,7 @@ def get_certification_document( ...@@ -99,7 +98,7 @@ def get_certification_document(
) )
async def main(): def main():
""" """
Main code Main code
""" """
...@@ -107,7 +106,7 @@ async def main(): ...@@ -107,7 +106,7 @@ async def main():
client = Client(BMAS_ENDPOINT) client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection # Get the node summary infos to test the connection
response = await client(bma.node.summary) response = client(bma.node.summary)
print(response) print(response)
# prompt hidden user entry # prompt hidden user entry
...@@ -124,14 +123,13 @@ async def main(): ...@@ -124,14 +123,13 @@ async def main():
pubkey_to = input("Enter certified pubkey: ") pubkey_to = input("Enter certified pubkey: ")
# capture current block to get version and currency and blockstamp # capture current block to get version and currency and blockstamp
current_block = await client(bma.blockchain.current) current_block = client(bma.blockchain.current)
# create our Identity document to sign the Certification document # create our Identity document to sign the Certification document
identity = await get_identity_document(client, current_block, pubkey_to) identity = get_identity_document(client, current_block, pubkey_to)
if identity is None: if identity is None:
print("Identity not found for pubkey {0}".format(pubkey_to)) print("Identity not found for pubkey {0}".format(pubkey_to))
# Close client aiohttp session # Close client aiohttp session
await client.close()
sys.exit(1) sys.exit(1)
# send the Certification document to the node # send the Certification document to the node
...@@ -141,17 +139,13 @@ async def main(): ...@@ -141,17 +139,13 @@ async def main():
certification.sign([key]) certification.sign([key])
# Here we request for the path wot/certify # Here we request for the path wot/certify
response = await client(bma.wot.certify, certification.signed_raw()) response = client(bma.wot.certify, certification.signed_raw())
if response.status == 200: if response.status == 200:
print(await response.text()) print(response.read())
else: else:
print("Error while publishing certification: {0}".format(await response.text())) print("Error while publishing certification: {0}".format(response.read()))
# Close client aiohttp session
await client.close()
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. if __name__ == "__main__":
# ( https://docs.python.org/3/library/asyncio.html ) main()
asyncio.get_event_loop().run_until_complete(main())
...@@ -15,7 +15,6 @@ You should have received a copy of the GNU General Public License ...@@ -15,7 +15,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import asyncio
import getpass import getpass
from duniterpy.api import bma from duniterpy.api import bma
...@@ -68,7 +67,7 @@ def get_identity_document( ...@@ -68,7 +67,7 @@ def get_identity_document(
return identity return identity
async def main(): def main():
""" """
Main code Main code
""" """
...@@ -76,11 +75,11 @@ async def main(): ...@@ -76,11 +75,11 @@ async def main():
client = Client(BMAS_ENDPOINT) client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection # Get the node summary infos to test the connection
response = await client(bma.node.summary) response = client(bma.node.summary)
print(response) print(response)
# capture current block to get version and currency and blockstamp # capture current block to get version and currency and blockstamp
current_block = await client(bma.blockchain.current) current_block = client(bma.blockchain.current)
# prompt entry # prompt entry
uid = input("Enter your Unique IDentifier (pseudonym): ") uid = input("Enter your Unique IDentifier (pseudonym): ")
...@@ -98,16 +97,12 @@ async def main(): ...@@ -98,16 +97,12 @@ async def main():
identity = get_identity_document(current_block, uid, key) identity = get_identity_document(current_block, uid, key)
# send the identity signed raw document to the node # send the identity signed raw document to the node
response = await client(bma.wot.add, identity.signed_raw()) response = client(bma.wot.add, identity.signed_raw())
if response.status == 200: if response.status == 200:
print(await response.text()) print(response.read())
else: else:
print("Error while publishing identity : {0}".format(await response.text())) print("Error while publishing identity : {0}".format(response.read()))
# Close client aiohttp session
await client.close()
if __name__ == "__main__":
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. main()
# ( https://docs.python.org/3/library/asyncio.html )
asyncio.get_event_loop().run_until_complete(main())
...@@ -15,7 +15,6 @@ You should have received a copy of the GNU General Public License ...@@ -15,7 +15,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import asyncio
import getpass import getpass
from duniterpy.api import bma from duniterpy.api import bma
...@@ -75,7 +74,7 @@ def get_membership_document( ...@@ -75,7 +74,7 @@ def get_membership_document(
return membership return membership
async def main(): def main():
""" """
Main code Main code
""" """
...@@ -83,11 +82,11 @@ async def main(): ...@@ -83,11 +82,11 @@ async def main():
client = Client(BMAS_ENDPOINT) client = Client(BMAS_ENDPOINT)
# Get the node summary infos by dedicated method (with json schema validation) # Get the node summary infos by dedicated method (with json schema validation)
response = await client(bma.node.summary) response = client(bma.node.summary)
print(response) print(response)
# capture current block to get version and currency and blockstamp # capture current block to get version and currency and blockstamp
current_block = await client(bma.blockchain.current) current_block = client(bma.blockchain.current)
# prompt hidden user entry # prompt hidden user entry
salt = getpass.getpass("Enter your passphrase (salt): ") salt = getpass.getpass("Enter your passphrase (salt): ")
...@@ -100,24 +99,20 @@ async def main(): ...@@ -100,24 +99,20 @@ async def main():
# Look for identities on the network, take the first result since the # Look for identities on the network, take the first result since the
# lookup was done with a pubkey, which should correspond to the first identity # lookup was done with a pubkey, which should correspond to the first identity
identities = await client(bma.wot.lookup, key.pubkey) identities = client(bma.wot.lookup, key.pubkey)
identity = identities["results"][0] identity = identities["results"][0]
# create a membership demand document # create a membership demand document
membership = get_membership_document("IN", current_block, identity, key) membership = get_membership_document("IN", current_block, identity, key)
# send the membership signed raw document to the node # send the membership signed raw document to the node
response = await client(bma.blockchain.membership, membership.signed_raw()) response = client(bma.blockchain.membership, membership.signed_raw())
if response.status == 200: if response.status == 200:
print(await response.text()) print(response.text())
else: else:
print("Error while publishing membership : {0}".format(await response.text())) print("Error while publishing membership : {0}".format(response.text()))
# Close client aiohttp session
await client.close()
if __name__ == "__main__":
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. main()
# ( https://docs.python.org/3/library/asyncio.html )
asyncio.get_event_loop().run_until_complete(main())
...@@ -16,7 +16,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. ...@@ -16,7 +16,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import sys import sys
import asyncio
import getpass import getpass
from duniterpy.api import bma from duniterpy.api import bma
...@@ -106,7 +105,7 @@ def get_transaction_document( ...@@ -106,7 +105,7 @@ def get_transaction_document(
return transaction return transaction
async def main(): def main():
""" """
Main code Main code
""" """
...@@ -114,7 +113,7 @@ async def main(): ...@@ -114,7 +113,7 @@ async def main():
client = Client(BMAS_ENDPOINT) client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection # Get the node summary infos to test the connection
response = await client(bma.node.summary) response = client(bma.node.summary)
print(response) print(response)
# prompt hidden user entry # prompt hidden user entry
...@@ -131,10 +130,10 @@ async def main(): ...@@ -131,10 +130,10 @@ async def main():
pubkey_to = input("Enter recipient pubkey: ") pubkey_to = input("Enter recipient pubkey: ")
# capture current block to get version and currency and blockstamp # capture current block to get version and currency and blockstamp
current_block = await client(bma.blockchain.current) current_block = client(bma.blockchain.current)
# capture sources of account # capture sources of account
response = await client(bma.tx.sources, pubkey_from) response = client(bma.tx.sources, pubkey_from)
if len(response["sources"]) == 0: if len(response["sources"]) == 0:
print("no sources found for account %s" % pubkey_to) print("no sources found for account %s" % pubkey_to)
...@@ -152,17 +151,13 @@ async def main(): ...@@ -152,17 +151,13 @@ async def main():
transaction.sign([key]) transaction.sign([key])
# send the Transaction document to the node # send the Transaction document to the node
response = await client(bma.tx.process, transaction.signed_raw()) response = client(bma.tx.process, transaction.signed_raw())
if response.status == 200: if response.status == 200:
print(await response.text()) print(response.read())
else: else:
print("Error while publishing transaction: {0}".format(await response.text())) print("Error while publishing transaction: {0}".format(response.read()))
# Close client aiohttp session
await client.close()
if __name__ == "__main__":
# Latest duniter-python-api is asynchronous and you have to use asyncio, an asyncio loop and a "as" on the data. main()
# ( https://docs.python.org/3/library/asyncio.html )
asyncio.get_event_loop().run_until_complete(main())
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment