Package: patata
PatataEasy parallel and concurrent requestsThe idea of this package is to wrapmultiprocessingandasyncconcurrency and allow the user to perform thousands of requests in parallel and concurrently without having to worry about pools of processes and async event loops.It only supports GET and POST requests. More methods will be implemented in later versions.The input is an iterable and the output is a generator. As soon as the requests get their response they are yielded until all the requests of the input are done.Each element of the iterable is a patata.Request object withid_,urlanddata.
Each element yielded is a patata.Response with the sameid_,status_codeanddatawhich is the json response. With theid_you can map the responses to the input requests.This is useful for cases where you have a huge amount of requests to perform to an API and you
need to do them as fast as possible.The client by default detects the number of CPUs available and starts one process per each CPU.
Then chunks the input iterator to provide requests to all the processes.
Each process for each task opens an event loop and performs all those requests concurrently. Once
all requests are awaited, the chunk with all the responses is returned back to the main process.
This is why we can see that our generator is receiving the responses un bulks.Install:From PyPi:pip install patataUsage:Use always context manager, for example for GET:>>>frompatata.modelsimportRequest>>>fromcollectionsimportdeque>>>>>>defmygen():...foriinrange(10_000):...yieldRequest(id_=i,url="http://localhost:12345/")...>>>withPatata()asclient:...responses=client.http("get",mygen())..._=deque(responses)...patataINFOStartprocessingrequestswithPatataparameters:patataINFOmethod:GETpatataINFOnum_workers:8patataINFOmultiprocessing:TruepatataINFOqueue_max_size:100000patataINFOinput_chunk_size:10000patataINFOpool_submit_size:1000patataINFOAllrequestsprocessed:patataINFOTotalrequests:10000patataINFOTotaltime(s):5.00patataINFORequests/s:1998.37>>>_.pop()Response(id_=9000,status_code=200,data={'message':'Hello world!'})In this example are providing a generator as input but you can provide any kind of iterable.You can also provide callbacks to process the responses in each process before being yielded, so you can add your own post-processing of the responses taking benefit of multiprocessing. Example:>>>frompatataimportPatata>>>frompatata.modelsimportRequest>>>fromcollectionsimportdeque>>>>>>defmycallback(response):...response.id_=1337...returnresponse...>>>defmygen():...foriinrange(10_000):...yieldRequest(id_=i,url="http://localhost:12345/")...>>>withPatata()asclient:...responses=client.http("get",mygen(),callbacks=[mycallback])..._=deque(responses)...patataINFOStartprocessingrequestswithPatataparameters:patataINFOmethod:GETpatataINFOnum_workers:8patataINFOmultiprocessing:TruepatataINFOqueue_max_size:100000patataINFOinput_chunk_size:10000patataINFOpool_submit_size:1000patataINFOAllrequestsprocessed:patataINFOTotalrequests:10000patataINFOTotaltime(s):4.89patataINFORequests/s:2046.95>>>_.pop()Response(id_=1337,status_code=200,data={'message':'Hello world!'})For doing a POST:Let's imagine we have this FastAPI endpoint:@app.post("/")asyncdefroot(data:dict):returndataWe can consume the POST endpoint like this:>>>frompatataimportPatata>>>frompatata.modelsimportRequest>>>>>>requests=[...Request(id_=1,url="http://localhost:12345/",data={"hello":"POST 1"}),...Request(id_=2,url="http://localhost:12345/",data={"hello":"POST 2"}),...]>>>withPatata(verbose=False)asclient:...responses=client.http("post",requests)...forresponseinresponses:...print(response)...id_=2status_code=200data={'hello':'POST 2'}id_=1status_code=200data={'hello':'POST 1'}ParametersYou can configure some parameters:patata.Patataparameters:num_workers:type: intrequired: Falsedefault: os.cpu_count()description: Number of processes to open with multiprocessingqueue_max_size:type: intrequired: Falsedefault: 100.000description: Maximum number of items that can be enqueued. This default number proved to not blow up the memory and to have enough items in the queue to have always work to do with 8 processes. Feel free to adjust it, just watch out the memory usage.input_chunk_size:type: intrequired: Falsedefault: 10.000description: This is the size of the chunks for the input. We will be reading the input iterator in chunks of this size up toqueue_max_size.pool_submit_size:type: intrequired: Falsedefault: 1.000description: Each chunk ofinput_chunk_sizewill also be chunked to minor chunks of this size before being submited to the pool. The workers will be consuming chunks of this size and each of these chunks will be requested in an event loop.verbose_level:type: intrequired: Falsedefault: 1description: Configure the level of logging. Possible values:0: "mute" means not a single line of log will appear1: "info" means that only the start params + num of processed lines + end summary will be logged2: "debug" means that all exceptions will be logged, this includes error responses from the remote serverpatata.Patata.httpParameters:method:type: strrequired: Truedescription: Specify the method of the requests. Valid values: GET, POST.requests:type: Iterable[Tuple[int, str]]required: Truedescription: Provide the tuples containing the ID of the request and the URL to be requested.callbacks:type: Iterable[Tuple[int, str]]required: Falsedefault: []description: Callables that will be executed for each response, they must expect receiving a Response and must return another Responseretries:type: Optional[int]required: Falsedefault: 1description: Total amount of requests to perform if the response is an error. Default is 1 which means doing the request only once, so no retries.Response: Generator[Tuple[int, str], None, None]. For each input tuple an output tuple will be returned containing the same ID + the JSON of the response.TODO:testsadd flag to specify how many requests can fail, this will need to specify also which codes are "ok" or which are "not ok" do decide when to increment this count and decide to stopinclude the missing methods like PUT, DELETE, etc