从循环中并行调用python方法

2024-03-29 11:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个方法1,其中循环正在运行并调用另一个方法2 但我想知道,我如何能并行调用方法2,因为它正在执行一些连续的步骤,方法2的call-1应该与方法2的call-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

Tags: the方法imageimgdatatimeresponselocation
1条回答
网友
1楼 · 发布于 2024-03-29 11:28:20

正如您在自己的评论中所建议的,多处理确实是异步上传的一种有效方法

如果您有兴趣深入研究Python中更现代的异步编程,那么您的问题是一个很好且简单的用例,用于尝试asyncio或其他异步事件循环实现之一。参见例如awesome-asyncio获取资源

相关问题 更多 >