-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_albums_by_artist.py
executable file
·65 lines (55 loc) · 1.64 KB
/
list_albums_by_artist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#! /usr/bin/env python3
# list_album_by_artist.py
# provides a simplified album listing
import textwrap
import click
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from tabulate import tabulate
from models import Album, Artist, Base, Genre
PROGNAME = "list_albums_by_artist"
VERSION = "0.2.0"
# 0.2.0
# uses tabulate to display data, cjk-textwrap for CJK chars
@click.command()
@click.version_option(version=VERSION, prog_name=PROGNAME)
@click.argument("artist")
def list_albums_by_artist(artist):
"""
List albums by artist (using LIKE operator)
Use '%' as wildcard
"""
# connect to database
engine = create_engine("sqlite:///musicdb.db")
Session = sessionmaker(bind=engine)
session = Session()
Base.metadata.create_all(engine)
# ask user for artist
click.echo(f"Search for albums by artist (using LIKE '{artist}')\n")
results = (
session.query(Album, Artist, Genre)
.join(Artist)
.join(Genre)
.filter(Artist.name.like(artist))
.order_by(Artist.name)
.order_by(Album.date)
.order_by(Album.title)
.all()
)
if results:
catalog = [
[
r.Album.id,
textwrap.shorten(r.Artist.name, 20, placeholder="..."),
r.Album.date,
textwrap.shorten(r.Album.title, 50, placeholder="..."),
]
for r in results
]
headers = ["Id", "Artist", "Date", "Title"]
print(tabulate(catalog, headers))
else:
print("No albums found")
session.close()
if __name__ == "__main__":
list_albums_by_artist()