Here is the script that I would like reviewed for the following:
- Best practices and design pattern usage
- Correctness in unanticipated cases
- Better dictionary access
The script is made to store (IPFS) Interplanetary File System hash objects. If you would like to know more check out https://ipfs.io
Script:
#!/usr/bin/python
# PHT - Personal Hash Tracker
#
import json
import os
hashjson_global = "/Users/troywilson/testing/pht/hash.json"
choice = raw_input("What do you want to do? \n a)Add a new IPFS hash\n s)Seach stored hashes\n d)Delete stored hash\n >>")
if choice == 'a':
# Add a new hash.
description = raw_input('Enter hash description: ')
new_hash_val = raw_input('Enter IPFS hash: ')
new_url_val = raw_input('Enter URL: ')
entry = {new_hash_val: {'description': description, 'url': new_url_val}}
# search existing hash listings here
if new_hash_val not in data['hashlist']:
# append JSON file with new entry
data['hashlist'].update(entry) #must do update since it's a dictionary
with open(hashjson_global, 'w') as file:
json.dump(data, file, sort_keys = True, indent = 4, ensure_ascii = False)
print('IPFS Hash Added.')
pass
else:
print('Hash exist!')
elif choice == 's':
# Search the current desciptions.
searchTerm = raw_input('Enter search term: ')
with open(hashjson_global, 'r') as file:
data = json.load(file)
hashlist = data['hashlist']
# build dictionary map and search for description value
d = {v['description']: h for h, v in hashlist.items()}
print d.get(searchTerm, 'Not Found')
elif choice == 'd':
# Search the current descriptions and delete entry.
del_hash = raw_input('Hash to delete: ')
with open(hashjson_global, 'r') as file:
data = json.load(file)
del data['hashlist'][del_hash]
with open('hashjson', 'w') as file:
json.dump(data, file, sort_keys = True, indent = 4, ensure_ascii = False)
print ('Hash removed')
Example JSON file:
{
"hashlist": {
"QmVZATT8jWo6ncQM3kwBrGXBjuKfifvrE": {
"description": "Test Video",
"url": ""
},
"QmVqpEomPZU8cpNezxZHG2oc3xQi61P2n": {
"description": "Cat Photo",
"url": ""
},
"QmYdWb4CdFqWGYnPA7V12bX7hf2zxv64AG": {
"description": "test.co",
"url": ""
}
}
}%
data
is undefined if the user chooses "a" as the first choice. You are missing the reading of the data file there. \$\endgroup\$ – Graipher Feb 24 '18 at 21:19