当 JSON 返回的“avatarUrl”结果为 null 时,是否可以在此代码中添加默认图像?
@staticmethod
def score_to_mod(score):
return floor((score - 10) / 2)
def __init__(self, character_id):
self.character_id = character_id
self.character_data = self.get_character_data()
self.character_image = self.character_data.get("decorations", {}).get("avatarUrl", "")[:-51]
#print(self.character_url)
def update(self):
self.character_data = self.get_character_data()
def get_character_data(self):
req = requests.get(f"https://character-service.dndbeyond.com/character/v5/character/{self.character_id}")
#print("hello")
if req.status_code != 200:
return None
try:
j = req.json()
if not "success" in j or not "data" in j:
return None
return j["data"]
except ValueError:
return None
这是脚本的结尾,其中数据由我的主脚本使用
return {
"max": max_hp,
"current": max_hp - self.character_data["removedHitPoints"],
"temp": self.character_data["temporaryHitPoints"],
"image": self.character_image,
"char_id": self.character_id
}
我尝试添加“if”语句,但结果并不理想。
我尝试将以下代码添加到INIT,当这不起作用时,我尝试将其添加到“get_character_data”
if self.character_image is None:
self.character_image = "https://www.dndbeyond.com/avatars/39102/30/1581111423-110222058.jpeg"
您可以围绕一些指导原则来进行设计。
__init__
函数执行尽可能少的操作。从长远来看,当您脱掉手套并拥抱编写测试时,这将对您有所帮助。越早,你就会越快乐。这么麻烦还是值得的。import requests
Class NoCharacterError(Exception):
pass
class CharacterData:
def __init__(self, image: str):
self.image = image
@staticmethod
def parse_data(data: requests.models.Response):
try:
image = data.json()["data"]["decorations"]["avatarUrl"][:-51]
return CharacterData(image=image)
except (KeyError, ValueError) as err:
raise NoCharacterError(f"Failed to parse data into CharacterData. Error {err}. Data {data}.")
class Character:
@staticmethod
def score_to_mod(score):
return floor((score - 10) / 2)
def __init__(self, character_id, character_data=None):
self.character_id = character_id
self.character_data = character_data
@property
def character_image(self):
if self.character_data is None:
self.update()
return self.character_data.image
def update(self):
try:
self.character_data = CharacterData.parse_data(self.get_character_data())
except NoCharacterError as err:
print(f"Falling back to default CharacterData because {err}.")
self.character_data = CharacterData(image="https://www.dndbeyond.com/avatars/39102/30/1581111423-110222058.jpeg")
def get_character_data(self):
return requests.get(f"https://character-service.dndbeyond.com/character/v5/character/{self.character_id}")
奖励:粗略地说,
是一个动态吸气剂/属性。@property
将隐式调用该函数。my_character.character_image