在Python中同时对URL发出多个POST请求

时间:2019-10-18 16:45:49

标签: python django python-3.x multithreading multiprocessing

我正在使用Django和Django Rest Framework。在我的urls.py中,我定义了以下端点/payments/。它支持POST个请求。

背景信息:不久前,我们有一个用户向该服务器发送多个请求,同时触发了竞争状况,因此偷钱。

问题:

  1. 如何编写测试以将100-1000个请求发送到此URL API端点?

这是我当前在测试文件中发送POST“测试”请求的方式:

class PaymentViewTestCase(BaseTestCase):
    def setUp(self):
        super(PaymentViewTestCase, self).setUp()
        self.client = APIClient()
        self.client.force_authenticate(user=self.profile)

    def test_post_create_payment(self):
        amount = 1000
        request_data = {
            'amount': amount,
        }
        res = self.client.post(
            '/payment/',
            ujson.dumps(request_data),
            content_type='application/json',
            secure=True
        )

但是,我想同时恰好触发此POST请求1000。

1 个答案:

答案 0 :(得分:0)

from concurrent.futures import ProcessPoolExecutor
import os

def task():
    print("Executing our Task on Process {}".format(os.getpid()))

def main():
    executor = ProcessPoolExecutor(max_workers=3)
    task1 = executor.submit(task)
    task2 = executor.submit(task)

if __name__ == '__main__':
    main()