【发布时间】:2021-12-26 14:37:06
【问题描述】:
在 Python 中,我正在编写一本异国食谱的网络版本,从各种 API 中获取食谱,以便将其发布到新网站。
如何将大约 100 个不同的 JSON 结构映射到我的?
我是否必须像我在本示例中展示的那样使用“get_content_from_api_1”、“...2”等手动操作,还是有更好的方法?
与原生 PostgreSql 相比,sqlAlchemy 有没有办法让事情变得更容易?
我面临的限制:
- 各种 API 根本不共享相同的结构
- 某些 API 将具有非扁平结构
- 将有大约 100 种不同的 API,因此有 100 种不同的结构和键名
我拥有的代码的工作示例:
from dataclasses import dataclass
import requests
@dataclass
class MyCookingData:
chocolate: str
cucumber: str = None
loaf: str = None
sample_obj_1 = {
"chocolate": "dark",
"cucumber": "long and green",
"loaf": "2 pounds",
}
sample_obj_2 = {
"choco": "milk",
"cuc": "5",
"meatloaf": "juicy",
}
def fetch_the_api(url):
'''Fetch a public url, but return sample objects for the example'''
'''
try:
response = requests.get(url, timeout=5)
except requests.exceptions.HTTPError as err:
print(err)
'''
response = url # sample_obj_ 1 and 2 for the example
return response
def get_content_from_api_1(url):
'''Get url or sample object 1'''
api_data = fetch_the_api(url)
new_data = MyCookingData(
chocolate=api_data['chocolate'],
cucumber=api_data['cucumber'],
loaf=api_data['loaf'],
)
populate_db(new_data)
def get_content_from_api_2(url):
'''Get url or sample object 2'''
api_data = fetch_the_api(url)
new_data = MyCookingData(
chocolate=api_data['choco'],
cucumber=api_data['cuc'],
loaf=api_data['meatloaf'],
)
populate_db(new_data)
def populate_db(data):
'''Store in db, but print for example'''
# print(data.__dict__)
for each_elem in data.__dict__:
print(each_elem, '=>', data.__dict__[each_elem])
def main():
print('Get content from API 1:')
get_content_from_api_1(sample_obj_1)
print('************')
print('Get content from API 2:')
get_content_from_api_2(sample_obj_2)
print('************')
main()
我运行这段代码得到的结果是:
Get content from API 1:
chocolate => dark
cucumber => long and green
loaf => 2 pounds
************
Get content from API 2:
chocolate => milk
cucumber => 5
loaf => juicy
************
【问题讨论】:
标签: python json api python-dataclasses