Part 3: Coding on Hive With Python - Writing Data to Hive

In part 3 we will write some data to the Hive blockchain while learning how to run Python code from a file and how to prompt for text input. Let’s go!

Part 1 covered how to set up a Python development environment. Part 2 taught how to install the Beem module and request data from the Hive blockchain. Parts 1 and 2 are pre-requisites for Part 3.

Writing data to a blockchain is also called broadcasting a transaction. For a transaction to be verified and accepted by the network, it needs to be signed with the correct cryptographic key. In our simple example here, we will make a request to follow a Hive blog. The ‘follow’ transaction requires the account’s private posting key.


Important: Aside on Secrets Management

We must briefly discuss secrets management because you don’t want to expose your private keys.

Hard-coding private keys into your scripts is convenient but dangerous. You might upload your script to GitHub or send it to a friend and leak the key. Anyone who finds your key can use it to control your account. If you ever find yourself in a key leak situation, change your keys immediately using PeakD or another trusted Hive wallet.


Following a Hive Blog Programmatically, using Python

Thanks to @holger80 and Beem, only a few lines of code are needed to ‘follow’ a blog.

For the below example to work, the code needs to be saved to disk as a file. Fire up a text editor and type or copy-paste these few lines of code. Save the file as follow.py somewhere convenient like your Home directory.

import beem
import getpass

name = input('enter your account name: ')
posting_key = getpass.getpass(prompt='enter your private posting key: ')

hive = beem.Hive(keys=[posting_key])
account = beem.account.Account(name, blockchain_instance=hive)

account.follow('learncode') 
print('Done! Ive followed learncode')

Explanation of Python input() function

Python’s input() function will, when the code is run, prompt the user and wait for keyboard input. This way, each time it’s run, it will ask for account information. Alternatively, we could hard-code the inputs in the script, but that’s less than ideal for key management as explained above.

Explanation of Python getpass() function

Python's getpass module and function is an extension of the input() function explained above. The main difference is it hides the input from the console as it's being typed. So by using getpass(), the private posting key won't be visible to shoulder surfers.

Explanation of Beem Hive, Account Objects and follow() Function

After collecting inputs, Beem is asked to set up a Hive object and an Account object. This is a little convoluted. The Hive object is necessary to provide our posting key. The Hive object is also provided as an input parameter when instantiating the Account object. After the Account object is set up, the wallet name and key are in the right place to be used for broadcasting transactions to the network.

The Account object’s follow() function is called. This function triggers a network request to a Hive API node including the transaction details.


Once follow.py is saved to disk we can run the code. In your terminal or CMD, cd (change directory) to where you saved the follow.py file. Then tell the Python interpreter to run the code with command: python3 follow.py. On Windows the command is slightly different: python follow.py. If the code is run successfully you should see the input prompts from the code like below:

$ python3 follow.py
enter your account name: learncode
enter your private posting key: 
Done! Ive followed learncode


Confirming Transaction Details in Hive Block Explorer

After the script is done, if all goes well, the transaction is sent to the network. A Hive block explorer can be used to verify the transaction. It should show up in the account history after 1-2 minutes on hiveblocks.com/@insert-your-account. The transaction preview will look like this:

image.png

Clicking the link in the top right reveals transaction details like below.

image.png

This view shows the Custom_JSON object that was created for us by beem under the hood. Beem sent a transaction with an operation of type 'custom_json'. The custom_json operation has an id of follow and a JSON object content for the details of the follow action. In the JSON object's what key, instead of blog the value could be ignore for mute, or empty ("what":[]) for unfollow/unmute.

custom_json operation ID ->     id      follow
JSON-formatted data      ->     json    ["follow",{"follower":"learncode","following":"learncode","what":["blog"]}]

Aside on Hive Block Explorer Tool

Hive block explorer is a super useful tool for troubleshooting all kinds of Hive transactions. For example, using this tool you can inspect and reverse-engineer custom_JSON transactions from Hive dApps and games.


Advanced: what happens if the wrong key or wrong account name is used?

If a non-existing account name is entered, beem will throw a beem.exceptions.AccountDoesNotExistsException. If an incorrect key is entered, beem will throw a beem.exceptions.MissingKeyError

Handling these exceptions improves the usability of the code. This can be done by wrapping the beem calls in try/except blocks like this.

import beem
import getpass
import sys

name = input('enter your account name: ')
posting_key = getpass.getpass(prompt='enter your private posting key: ')


hive = beem.Hive(keys=[posting_key])

try:
    account = beem.account.Account(name, blockchain_instance=hive)
except beem.exceptions.AccountDoesNotExistsException:
    print('Error! Invalid wallet name')
    sys.exit(1)

try:
    account.follow('learncode') 
except beem.exceptions.MissingKeyError:
    print('Error! Incorrect private posting key')
    sys.exit(1)


print('Done! Ive followed learncode')

Now, some friendly error messages will be shown instead of Python's verbose stack traces.

$ python3 follow.py
enter your account name: learncode
enter your private posting key: 
Error! Incorrect private posting key
$ python3 follow.py
enter your account name: learncode123123
enter your private posting key: 
Error! Invalid wallet name

Wrapping up

That's a wrap for today. In part 3 we learned how to run python code from a file, how to prompt the user for input, how to set up posting keys to use in Beem, how to use Beem to follow a Hive blog. And we saw how to use the Hive block explorer to verify transaction details. As bonus, we also discussed secrets management and how to handle beem exceptions for errors.


p.s. Thanks for reading! Please let me know if anything is unclear or incorrect. This is intended to be a living document to be improved and maintained over time.


p.p.s. This blog is brought to you by the Hive.Pizza team.


p.p.p.s. A channel for #learn-code is set up in the Hive.pizza discord for discussing these lessons and enabling success for all code learners.

H2
H3
H4
3 columns
2 columns
1 column
20 Comments
Ecency