commit 40a03907819f444905c070ec45efb9c289149962
parent 321360a62c6a0a80bc4c6b15912cf62deeeb8227
Author: Paco Esteban <paco@e1e0.net>
Date: Sat, 30 Oct 2021 20:00:57 +0200
add json output for part info
Diffstat:
2 files changed, 27 insertions(+), 6 deletions(-)
diff --git a/partsdb/helpers.py b/partsdb/helpers.py
@@ -81,7 +81,14 @@ def _list_json(parts):
print(json.dumps({'parts': p}))
-def print_part(p, history):
+def print_part(p, history, output='full'):
+ if output == 'full':
+ _part_ascii(p, history)
+ if output == 'json':
+ _part_json(p, history)
+
+
+def _part_ascii(p, history):
print(f"PN: {p['pn']}\tManufacturer: {p['manufacturer']}")
print(f"Category: {p['cat']}\tType: {p['part_type']}"
f"\tFootprint: {p['footprint']}")
@@ -106,6 +113,17 @@ def print_part(p, history):
f"{h['mcomment']}")
+def _part_json(part, history):
+ part = dict(zip(part.keys(), part))
+ # remove bytes data if present. For now is useless in this output.
+ del part['datasheet']
+ del part['image']
+
+ part['history'] = [dict(zip(h.keys(), h)) for h in history]
+
+ print(json.dumps({'part': part}))
+
+
def _sanitize_value(value):
if value is None:
return "-"
diff --git a/partsdb/partsdb.py b/partsdb/partsdb.py
@@ -144,10 +144,10 @@ def search_part(search_term, output):
helpers.print_parts_list(parts, output)
-def get_part(part_id):
+def get_part(part_id, output):
part = db.get_part(part_id)
history = db.get_part_history(part_id)
- helpers.print_part(part, history)
+ helpers.print_part(part, history, output)
def open_image(part_id):
@@ -245,6 +245,9 @@ def main():
help="Open datasheet if available.")
ap_get.add_argument("-i", dest='image', action='store_true',
help="Open image if available.")
+ ap_get.add_argument("-o", dest='output',
+ choices=['full', 'json'], default='full',
+ help="Short output")
# delete
ap_delete = asp.add_parser("delete", help="Delete a part")
ap_delete.add_argument("part_id", help="Part Id", type=int)
@@ -271,10 +274,10 @@ def main():
elif args.command == 'search':
search_part(args.search_term, args.output)
elif args.command == 'get':
- get_part(args.part_id)
- if args.datasheet:
+ get_part(args.part_id, args.output)
+ if args.datasheet and args.output != 'json':
open_datasheet(args.part_id)
- if args.image:
+ if args.image and args.output != 'json':
open_image(args.part_id)
elif args.command == 'delete':
delete_part(args.part_id)