【问题标题】:Calling API multiple times - Python多次调用 API - Python
【发布时间】:2022-01-01 01:05:57
【问题描述】:

我正在尝试使用转换日期的 API。我从包含完整日期的文件中检索数据,使用拆分和切片分别获取日、月和年。我需要发送每个日期并将转换返回给用户。

我目前拥有的是:

def convert(day, month, year):
        gr_to_hb_url = 'https://www.hebcal.com/converter?cfg=json&gy='+ year+ '&gm='+ month+ '&gd='+ day+'&g2h=1'
        with urllib.request.urlopen(gr_to_hb_url) as response:
            data = response.read()
            obj = json.loads(data)
            
            results = [(result['hd'], result['hm'],result['hy']) for result in obj]
            return results
hby, hbm, hbd=convert(prep_day, prep_month, prep_year)
print(hby,hbm,hbd)

prep_day/month/year 是如上所述我分别从每一天检索到的日、月和年。

我得到 TypeError 的错误:字符串索引必须是整数。

感谢任何帮助。谢谢!

【问题讨论】:

  • 我打赌结果的内容是字符串类型
  • 你确定obj中的每个结果都是dict吗?从错误跟踪来看,它们看起来像是lists,而您正尝试使用键将它们索引为dict
  • @Shandron 为什么不使用requests?这样会容易一些

标签: python json api


【解决方案1】:

查看请求的输出:

{"gy":2020,"gm":1,"gd":1,"afterSunset":false,"hy":5780,"hm":"Tevet","hd":4,"hebrew":"ד׳ בְּטֵבֵת תש״פ","events":["Parashat Vayigash"]}

我认为您可能想要以下内容:

def convert(day, month, year):
        gr_to_hb_url = 'https://www.hebcal.com/converter?cfg=json&gy='+ year+ '&gm='+ month+ '&gd='+ day+'&g2h=1'
        with urllib.request.urlopen(gr_to_hb_url) as response:
            data = response.read()
            obj = json.loads(data)
            
            results = (obj['hd'], obj['hm'],obj['hy'])
            return results

您看到错误的原因是,当您遍历字典类型时,您只会得到值。 在这种情况下,将类似于以下内容(尽管在遍历字典时不能保证顺序) [2020,1,1,假,...] 我想你迭代的第一个元素是“Tevet”之类的东西。 如果结果的值为“Tevet”,则运行"Tevet"["hd"] 会导致您看到的错误。

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2020-10-05
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多