06 / 06Intermediate
Python components
Open the PySpark folder
cd pysparkTalking to the blockchain from the client
To connect to a blockchain node, BlockchainClient relies on the NetworkSettings class. That class holds the connection parameters, including node URLs, retry intervals, and the failover strategy.
settings = NetworkSettings( node_url_pool=[os.getenv("POSTCHAIN_TEST_NODE", "http://localhost:7740")], status_poll_interval=int(os.getenv("STATUS_POLL_INTERVAL", "500")), # Opitional parameter status_poll_count=int(os.getenv("STATUS_POLL_COUNT", "5")), # Opitional parameter verbose=True, # Opitional parameter attempt_interval=int(os.getenv("ATTEMPT_INTERVAL", "5000")), # Opitional parameter attempts_per_endpoint=int(os.getenv("ATTEMPTS_PER_ENDPOINT", "3")), # Opitional parameter failover_strategy=FailoverStrategy.ABORT_ON_ERROR, # Opitional parameter unreachable_duration=int(os.getenv("UNREACHABLE_DURATION", "30000")), # Opitional parameter use_sticky_node=False, # Opitional parameter blockchain_iid=int(os.getenv("BLOCKCHAIN_IID", "0")) # Opitional parameter ) # Create blockchain client client = await BlockchainClient.create(settings)}The seed_products function creates a product in the node's database by building a blockchain transaction and sending it.
async def seed_products(client: BlockchainClient): """Example of how to create and send a transaction""" try: # Create private/public key pair private_bytes = bytes.fromhex(os.getenv("PRIV_KEY")) private_key = PrivateKey(private_bytes, raw=True) public_key = private_key.pubkey.serialize() # Create operation operation = Operation( op_name="seed_data", args=[] ) # Create transaction transaction = Transaction( operations=[operation], signers=[public_key], signatures=None, blockchain_rid=client.config.blockchain_rid ) # Sign the transaction signed_transaction = await client.sign_transaction( transaction, private_bytes ) # Send transaction and wait for confirmation receipt = await client.send_transaction( signed_transaction, do_status_polling=True ) print(f"\nTransaction status: {receipt.status}") if receipt.status == ResponseStatus.CONFIRMED: print("Transaction confirmed!") else: print(f"Transaction failed: {receipt.message}") except Exception as e: print(f"Transaction failed: {str(e)}")The get_products_paginated function fetches products from the database one page at a time.
async def get_products_paginated(client: BlockchainClient, cursor: None): """Example of how to query the blockchain""" try: return await client.query("get_products_paginated", {"page_size": 1000, "page_cursor": cursor}) except Exception as e: print(f"Query failed: {str(e)}")The following snippet shows how to run the paginated query. You call the query repeatedly in a loop and stop once the cursor is None.
products_all = [] products = await get_products_paginated(client, None) products_all = products_all + products['data'] while products['next_cursor'] != None: products = await get_products_paginated(client, products['next_cursor']) products_all = products_all + products['data']Written for this site from Chromia’s public course. Code samples are the course’s own.