>我有一个方法1,其中循环正在运行并调用另一个方法2 但是我想知道,在执行一些顺序步骤时,我如何并行调用方法 2,并且方法 1 的 call-2 应该与方法 2 的调用 2 分开......所以这是我的代码 方法 2
def upload_image(img):
sess = requests.Session()
sess.verify = False
start_upload_response = requests.post('https://awsimgproc.com/start_upload', data={"album_id36": 1}, verify=False)
start_upload_response.raise_for_status()
result = start_upload_response.json()
our_upload = result['upload_id36']
url = 'https://awsimgproc.com/uploadImage'
files = {'file': open(img, 'rb')}
data = {'upload_id36':our_upload}
# This makes the post requests async
global api_response
api_response.append(grequests.post(url,data=data,files=files))
方法 1
def image_generator():
# Change here the location of iamge file
image_file_location = "/home/gaurav/Pictures/sofa-3"
extension = ".jpg"
i=1
img = Image.open(image_file_location + extension)
start_time = datetime.now()
# can change minutes as per need i.e for how much you need run
test suite
end_time = start_time + timedelta(minutes=1)
while start_time < end_time:
# change current image and randomly roating the image
rotated_image = img.rotate(random.randint(1,1000))
new_image_loaction = image_file_location+str(i)+extension
rotated_image.save(new_image_loaction)
# upload the newly rotated image
upload_image(new_image_loaction)
# uncomment this line to add sleep to your method
# time.sleep(random.randint(1,5))
start_time = datetime.now()
i += 1
正如您在自己的评论中所建议的那样,多处理确实是异步上传的一种有效方法。
如果你有兴趣深入研究 Python 中更现代的异步编程,你的问题是一个很好的简单用例来尝试 asyncio 或其他异步事件循环实现之一。参见例如 awesome-asyncio 以获取资源。