From 2a62f1312a9cd8438b2d96f5f9c330ac478a3e92 Mon Sep 17 00:00:00 2001 From: xtaodada Date: Sun, 25 Sep 2022 22:45:27 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20=E6=94=B9=E5=8F=98=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E4=BC=98=E5=85=88=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- defs.py | 4 +++- main.py | 3 ++- services/apple.py | 2 +- utils.py | 21 +++++++++++++++------ 4 files changed, 21 insertions(+), 9 deletions(-) diff --git a/defs.py b/defs.py index b74a817..2045d7a 100644 --- a/defs.py +++ b/defs.py @@ -1,4 +1,6 @@ class Music: - def __init__(self, name: str, album: str): + def __init__(self, name: str, album: str, artist: str = ""): self.name = name self.album = album + self.artist = artist + self.name = f"{self.artist} - {self.name}" if self.artist else self.name diff --git a/main.py b/main.py index 3364c57..f54b195 100644 --- a/main.py +++ b/main.py @@ -7,6 +7,7 @@ app = FastAPI() @app.get('/search') async def search( *, + service: str = "apple", keyword: str = Query(..., title="The name of a song") ): - return await get_music(keyword) + return await get_music(service, keyword) diff --git a/services/apple.py b/services/apple.py index e132fac..30706fe 100644 --- a/services/apple.py +++ b/services/apple.py @@ -22,5 +22,5 @@ class Apple: results = [] for i in req["results"]: with contextlib.suppress(Exception): - results.append(Music(i["trackName"], i["artworkUrl100"])) + results.append(Music(i["trackName"], i["artworkUrl100"], i["artistName"])) return results diff --git a/utils.py b/utils.py index e171868..7f146de 100644 --- a/utils.py +++ b/utils.py @@ -15,14 +15,23 @@ def parse_data(data: List[Music]) -> dict: return {"resultCount": length, "results": results} -async def get_music(keyword: str) -> dict: +async def get_music(service: str, keyword: str) -> dict: if not keyword: return default_data with contextlib.suppress(Exception): apple_result = await apple.Apple.get(keyword) - if apple_result: - return parse_data(apple_result) - netease_result = await netease.Netease.get(keyword) - if netease_result: - return parse_data(netease_result) + if service == "apple": + if apple_result: + return parse_data(apple_result) + netease_result = await netease.Netease.get(keyword) + if netease_result: + return parse_data(netease_result) + else: + if apple_result and apple_result[0].name == keyword: + return parse_data(apple_result) + netease_result = await netease.Netease.get(keyword) + if netease_result: + return parse_data(netease_result) + if apple_result: + return parse_data(apple_result) return default_data