发布文件,但端点限制每分钟50个帖子



下午好,我对编码完全不了解,我需要一些帮助,我将一个json文件拆分为~2800个较小的json文件,需要发布到某个端点,但是端点的限制是每分钟~50个文件。

目前我已经设置了python:

import requests
url = 'testtest'
headers = {'Authorization' : 'testtest', 'Accept' : '*/*', 'Content-Type' : 'application/json'}
r = requests.post(url, data=open('C:Accountmanagerjson1.json', 'rb'), headers=headers

文件名为json1 ->json2800

目前它只发布1个文件,我需要以每分钟50个的限制发布所有2800个文件,是否有人可以帮助:)?

如果您的代码对一个请求是正确的,那么您应该能够像这样执行所有请求:

import requests
from time import sleep
url = 'testtest'
headers = {'Authorization' : 'testtest', 'Accept' : '*/*', 'Content-Type' : 'application/json'}
for i in range(1, 2801): # for each file
r = requests.post(url, data=open('C:Accountmanagerjson'+ i +'.json', 'rb'), headers=headers
sleep(60/50) #for 50 requests per minute (60s)

我建议您将60/50(最后一行)替换为60/48之类的东西,以确保没有由于do滞后而产生的问题

我建议调用包含所有文件的目录,然后遍历每个文件并发布它。然后使用时间库来控制帖子发布的频率。

import os
import requests
url = 'test'
headers = {'Authorization' : 'testtest', 'Accept' : '*/*', 'Content-Type' : 'application/json'}
_, _, files = next(os.walk("C:Accountmanager"))
file_count = len(files)
for i in files:

#the value for the directory for *data=open* is the directory of the file + i which is the name of each file inside of your directory
r = requests.post(url, data=open('C:Accountmanager '.replace(" ", "") + i, 'rb'), headers=headers)
time.sleep(2)

现在在所有的诚实,我没有任何经验的请求库,所以我没有能够得到的代码运行,因为我得到一个错误有关的url变量,所以我假设你已经设置了那部分,希望我已经帮助你手头的问题。

所以你有一个大的JSON需要分割成更小的组件部分。每个部分都必须保存在本地自己的文件中。这些保存的文件必须被post到某个URL。你需要限制流量不超过50/分钟。

from json import load, dumps
from requests import post
from time import sleep
from os.path import join
URL = '...'
HEADERS = {'Authorization' : 'testtest', 'Accept' : '*/*', 'Content-Type' : 'application/json'}
BASEDIR = r'C:Accountmanager'
filelist = []
with open('filename.json') as json_file:
data = load(json_file)
for counter, dict_ in enumerate(data, 1):
new_json = dumps(dict_, sort_keys=True, indent=4)
filename = join(BASEDIR, f'json{counter}.json')
with open(filename, 'w') as new_file:
new_file.write(new_json)
filelist.append(filename)
for filename in filelist:
with open(filename, 'rb') as data:
post(URL, data=data, headers=HEADERS).raise_for_status()
time.sleep(1.2)

修改你的请求。Post将其放入一个带有睡眠计时器的循环中,以限制请求,如下所示:

import requests
import time
url = 'testtest'
headers = {'Authorization' : 'testtest', 'Accept' : '*/*', 'Content-Type' : 'application/json'}
for i in range(1, 2801):
filename = f"C:Accountmanagerjson{i}.json"
r = requests.post(url, data=open(filename, 'rb'), headers=headers
time.sleep(2)

你可以使用睡眠计时器来查看油门限制在哪里,或者它将每2秒发布1个,所以你将远远低于每分钟50个的限制。

最新更新