pandas 如何将python dict中的键/值获取到get方法的请求中

hec6srdp  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(90)

我尝试从dict获取特定的值,并在requests模块中使用这些值来发出get请求。

clusters = {
    'cluster_1':'https://cluster_1.something.com/api',
    'cluster_2':'https://cluster_2.something.com/api'
}

代码:

def getCsv():
    for i in clusters:
        r = requests.get(i.values(), headers=headers, params=params)
        with open("input.csv", "w") as f:
            f.writelines(r.text.splitlines(True))
        df = pd.read_csv("input.csv")
        return df

getCsv()

我做得对吗?
最后一步是使用下面的代码将clusters键打印到输出csv中。

with open(rb'output.csv', 'w', newline='') as out_file:
        timestamp = datetime.now()        
        df = getCsv()
        if 'Name' in df.columns:
            df.rename(columns = {"Name": "team", "Total": "cost"}, inplace = True)
        df.insert(0, 'date',timestamp)
        df.insert(1, 'resource_type', "pod")
        df.insert(2, 'resource_name', "kubernetes")
        df.insert(3, 'cluster_name', i.keys)
        df.drop(["CPU", "GPU", "RAM", "PV", "Network", "LoadBalancer", "External", "Shared", "Efficiency"], axis=1, inplace=True)
        df['team'] = df['team'].map(squads).fillna(df['team'])
        df.groupby(["date","resource_type","resource_name","cluster_name","team"]).agg({"cost": sum}).reset_index().to_csv(out_file, index=False)

但似乎不起作用,任何指导将不胜感激。

bbuxkriu

bbuxkriu1#

函数getCsv搞砸了,你通过传递i.values()requests.get传递了多个url,并且你在for循环的第一次迭代中返回。
试着从函数中提取循环,并像这样重新表达函数:

def get_cluster_df(url, **kwargs):
    r = requests.get(url, **kwargs)
    with open("input.csv", "w") as f:
        f.writelines(r.text.splitlines(True))
    return pd.read_csv("input.csv")

headers = ...
params = ...

dfs = {}
for name, url in clusters.items():
    dfs[name] = get_cluster_df(url, headers=headers, params=params)

您最终将得到一个字典dfs,如下所示:

{
    'cluster_1': pd.DataFrame(),
    'cluster_2': pd.DataFrame()
}

相关问题