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