如何使用Python限制API端点中字符串值的数量?

问题描述 投票:0回答:2

在这里,在代码中。我在下面的 API 中一次最多只能使用 5 个值(API 限制)。

import requests
import json
import datetime
from datetime import date, datetime
import itertools
from sentimeterdb import dbconnect

from dotenv import load_dotenv   #for python-dotenv method
load_dotenv()                    #for python-dotenv method

import os

#Connection string pointing to the PROD db.
dbclient = dbconnect.process()
db = dbclient.abc
co_open = db.open_ab

myquery = {"bugs" : {"$ne" : {}, "$exists": True}}
mydoc = co_open.find(myquery)

lst = []
for x in mydoc:
    y = x.get('bugs')
    id_list = lst.append([*y.values()])
    cdets = list(itertools.chain(*lst))

cdets_split = cdets
string_cdets = ','.join(cdets_split[:5])

Access_URL = 'https://generating-token-from--here/oauth2/default/v1/token'

client_id = os.environ.get('CLIENT_ID')
client_secret = os.environ.get('CLIENT_SECRET')
grant_type = os.environ.get('GRANT_TYPE')
BASE_URL = f'https://google.com/{string_cdets}'

response = requests.post(Access_URL,
                     data={'grant_type': grant_type, 'client_id': client_id, 'client_secret': client_secret, 'content-type': 'application/x-www-form-urlencoded'})
json_response = response.json()

tokenvalue = (json_response['access_token'])

headers = {'Authorization': 'Bearer ' +
       tokenvalue, 'Content-Type': 'application/json'}

auth_response = requests.get(BASE_URL,  headers=headers)
auth_response_json = auth_response.json()

severity_list = []
for severity_5 in auth_response_json['bugs']:
    severity_list.append([severity_5['severity']])

print ("Severity ==> ", severity_list)

应给出所有 CDET 的严重性和状态。目前,仅赠送 5 件物品。 我怎样才能得到所有 CDET 的回复?

python json python-3.x generator
2个回答
0
投票

我不确定我是否明白这个问题,但使用生成器根本不会影响复杂性。

for
循环完全没问题。

如果值(“ABC”、“DEF”等)是即时生成的,则生成器将很有用。在这种情况下,您可以使用

for
循环来循环生成器。


0
投票

itertools 文档中显示了一个名为

batched
的函数的配方,可用于从可迭代对象中生成任意大小的“块”

from itertools import islice 


def batched(iterable, n):
    "Batch data into tuples of length n. The last batch may be shorter."
    # batched('ABCDEFG', 3) --> ABC DEF G
    if n < 1:
        raise ValueError('n must be at least one')
    it = iter(iterable)
    while batch := tuple(islice(it, n)):
        yield batch

此处给出的答案也可能有用。

无论如何,正如您已经猜到的那样,您最终会将这些块传递到

for
循环中以进行 API 调用。

for group in batched(values, 5):
    ...  # insert API call here

我不确定是否可以在无需多次 API 调用的情况下执行此操作。采用像这样对列表进行分块的方法本质上意味着您必须进行调用,直到列表用完为止。


编辑:以下OP更新

如果改变的是

BASE_URL
的值,您只需循环
cdets
中的“批次”,根据需要更新
BASE_URL
并将其传递给
requests.get(BASE_URL,  headers=headers)

auth_responses = []  # init an empty list to store responses


for batch in batched(cdets, 5):
    string_cdets = ','.join(batch)
    BASE_URL = f'https://google.com/{string_cdets}'
    # append responses to the list
    auth_responses.extend(requests.get(BASE_URL, headers=headers))

警告 - 这里做了一些猜测,因为我们不知道这些 CDET 是什么......

另外FWIW,

BASE_URL
确实应该被设计为
base_url
,因为它是一个值会变化的变量 - 所有大写通常用于暗示
CONSTANT
值,而
BASE_URL
绝对不是

© www.soinside.com 2019 - 2024. All rights reserved.