简体   繁体   English

如何从 python 字典中获取键/值到 get 方法的请求中

[英]How to get the key/value from python dict into requests for get method

I'm trying to get the specific values from dict and use in the requests module to make the get requests.我正在尝试从 dict 获取特定值并在请求模块中使用以发出获取请求。

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

Code:代码:

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()

Am I doing it right?我做对了吗?

Also final step is to print the clusters key into output csv using below code.最后一步是使用以下代码将集群密钥打印到 output 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)

But seems not working, any guidance will be appreciated.但似乎不起作用,任何指导将不胜感激。

The function getCsv is screwed up. function getCsv搞砸了。 You're passing multiple urls to requests.get by passing i.values() and you're returning in the first iteration of the for loop.您通过传递i.values()将多个 url 传递给requests.get并且您将在 for 循环的第一次迭代中返回。

Try extracting the loop from the function and reformulating the function like this:尝试从 function 中提取循环并重新制定 function,如下所示:

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)

You will end up with a dictionary dfs which will look like:你最终会得到一个字典dfs ,它看起来像:

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

To get the key/value pairs from a Python dictionary and use them in a GET request using the requests module, you can use the params parameter of the requests.get() function. This parameter takes a dictionary of key/value pairs and encodes them as query parameters in the URL.要从 Python 字典中获取键/值对并在使用请求模块的 GET 请求中使用它们,您可以使用requests.get() function 的 params 参数。此参数采用键/值对字典并进行编码它们作为 URL 中的查询参数。

Here is an example of how you can do this: import requests这是您如何执行此操作的示例:导入请求

Set up the dictionary of key/value pairs设置键/值对的字典

params = {'key1': 'value1', 'key2': 'value2'}

Make the GET request using the params parameter使用params参数发出 GET 请求

response = requests.get('http://httpbin.org/get', params=params)

Print the response text打印响应文本

print(response.text)

This will send a GET request to the URL http://httpbin.org/get?key1=value1&key2=value2 , with the key/value pairs encoded as query parameters.这将向 URL http://httpbin.org/get?key1=value1&key2=value2发送 GET 请求,并将键/值对编码为查询参数。

You can also use the json parameter of the requests.get() function to send a JSON object as the request body.您还可以使用requests.get() function 的 json 参数发送一个 JSON object 作为请求体。 This is useful if you want to send a complex data structure as part of the request, rather than encoding it as query parameters in the URL.如果您想将复杂的数据结构作为请求的一部分发送,而不是将其编码为 URL 中的查询参数,这将很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM