SoFunction
Updated on 2024-12-19

python multithreaded request for multiple interfaces with parameters problem

Multi-threaded request for multiple interfaces with parameters

For the process/thread/crip/asynchronous content have time to prepare to write really have been using for to loop slow to doubt life need to apply the scenario will also be a lot of so a little bit of a summary of the separate

Let's start with the code to see the content, the multithreaded request interface

imoprt threading # First use the threading module


class BrushGifts:
    # Here are two identical interfaces send_gift_room_one() is the interface for sending a gift
    # That means the state I want to accomplish is that A sends B, B sends A, and both users want to give each other a gift at the same time #
    def giftt(self, uid, recvUid, giftId):
        """
        gift giving interface
        :param uid: gift-giving user
        :param recvUid: gift recipient
        :param giftId: propid
        :return:
        """
        VoiceRoom().send_gift_room_one(uid, recvUid, giftId)

    def giftt_a(self, uid, recvUid, giftId):
        # Same interface as above without further ado #
        # There's no difference, it's just written so you can understand the concept of the two interfaces #
        VoiceRoom().send_gift_room_one(recvUid, uid, giftId)


if __name__ == '__main__':
    # Since my accounts are stored in a yaml file, I need to dump out the list of uid's for the users I need first.
    # The giver and the receiver pour out separately
    uid_list = YamlHandler(YamlThePath().voice_room_cpNew).get_uid_list(10)
    rUid_list = YamlHandler(YamlThePath().number_old).get_scope_uid(1500, 10)
    # For now, let's show the simplest way to send ABs to each other at the same time. #
    for (i, j) in zip(uid_list, rUid_list):
        # target needs to be passed the name of the method, not the (), because with parentheses you're calling the method, and it'll just start executing.
        # args pass in the input bring in arguments can be sequential or organized into tuples or dictionaries to be received
        t1 = (target=BrushGifts().giftt, args=(i, j, 51620))
        # Two is two interfaces that I'm requesting concurrently
        t2 = (target=BrushGifts().giftt, args=(j, i, 51620))
        # () for the implementation of
        ()
        ()

Main thread:

The concept of the main thread is the execution from scratch within this py file When I finish executing the last line of code () the main thread goes into a wait state and waits for the child thread to finish before the main thread will finish

Subthread:

The concept of a subthread is that I'm executing here while the main thread is executing, and of course it's being called through the () method.

t1 = (target=BrushGifts().giftt, args=(i, j, 51620))

At this point the system will open another sub-thread for the execution and call of the BrushGifts().gift method

The main thread will execute () and () as it proceeds but he won't wait for them to finish executing, the main thread will continue on down the line, so () and () are requested at the same time, and the main thread will end when both the () and () subprocesses are finished~

Because the main thread executes () and () line by line and python can't do concurrency in the exact sense, this method is not suitable if the data speed is very important.

How to request an interface in python

Role: Used for repeated insertion of data

1, first download python and then cmd input python to determine whether the global installation is successful.

2. Download PcIdea

3、Download the library you need

4. Viewing the request network

  • Press F12.
  • Make a request to the interface
  • First validate the required header request header data

  • View Body Request

5, to give you a template for their own slow experience

 
import requests                         # Import the requests package
import random
import json
import time
 
# response = ('')
# print(response.status_code) # print the status code
# print() # Print the request url
# print() # Print header information
# print() # print cookie information
# print() #Print the web page source code as text
# print() #Print as a stream of bytes
# print(())
 
 
AddCarURL = "http://localhost:10086/jeecg-boot/cable/insurance/add"
AddCarCookies = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjkwOTUyNzcsInVzZXJuYW1lIjoiYWRtaW4ifQ.Kn1jB5gUkCdnszSVxnjVVKtRMbx_WJSVZW6G-yJaid8"
randomStr = "ABCDEFGHIJKLMNOPQRST"
randomInsurance = ["Taikang Life.","Sunshine Insurance","Xinhua Insurance","Pacific Life.","Tongfang Global Life","AIA.","Merchants Renhe","Peace Insurance."]
randomBox = ["Stone Fresh Storage","Myung Soon Warehouse","Star Storage.","Jinsheng Warehouse","Wang Heng Warehouse","Central Panther Warehouse.","Flying Storage.","Speedy Storage","Spring Storage."]
sess = ()
headers = {
    "X-Access-Token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjkxMDUyMjUsInVzZXJuYW1lIjoiYWRtaW4ifQ.EUAjJYACel8QHFw4AFERIaDjXZJTwOOyp8uncqx3Jps",
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19041",
    "Referer":"http://localhost:3000/cable/VehicleList",
    "Origin":"http://localhost:3000",
    "Host":"localhost:10086",
    "Content-Type":"application/json; charset=utf-8"
}
 
a1=(2017,1,1,0,0,0,0,0,0)              #Set start date time tuple (1976-01-01 00:00:00)
a2=(2019,3,16,23,59,59,0,0,0)    # Set end date time tuple (1990-12-31 23:59:59)
 
a3=(2019,3,16,0,0,0,0,0,0)              #Set start date time tuple (1976-01-01 00:00:00)
a4=(2021,8,16,23,59,59,0,0,0)    # Set end date time tuple (1990-12-31 23:59:59)
 
start=(a1)    # Generate start timestamps
end=(a2)      # Generate end timestamps
 
start1=(a3)    # Generate start timestamps
end2=(a4)      # Generate end timestamps
 
# for i in range(10):
# t=(start,end) # randomize one of the start and end timestamps
# date_touple=(t) #Generate time tuples from timestamps
# date=("%Y-%m-%d",date_touple) #convert time tuple to formatted string (1976-05-21)
#
#     t1 = (start1,end2)
# date_touplen=(t1) #Generate timestamps into time tuples
# dateOne=("%Y-%m-%d",date_touplen) #convert time tuple to formatted string (1976-05-21)
#     print(date + " " +dateOne)
 
 
 
 
 
def addCar(num:int):
    # {"type": "2", "carryingCapacity": "3 tons.", "license": "Guangdong A888", "engineNumber": "123456", "state": 0}
 
    # {"vehicleId": "2", "insuraName": "lifeInsurance", "insurancePolicy": "UY1254SD5492W", "insuranceDateBegin": "2021-08-16".
    #  "insuranceDateEnd": "2021-08-31", "strongPolicy": "UY1254SD5492E", "strongDateBegin": "2021-07-01",
    #  "strongDateEnd": "2021-08-28", "license": "2"}
    for i in range(num):
 
 
        t = (start, end)  # Take a random start and end timestamp out of the
        date_touple = (t)  # Generate time tuples from timestamps
        date = ("%Y-%m-%d", date_touple)  # Conversion of time tuples to formatted strings (1976-05-21)
 
        t1 = (start1, end2)
        date_touplen = (t1)  # Generate time tuples from timestamps
        dateOne = ("%Y-%m-%d", date_touplen)  # Conversion of time tuples to formatted strings (1976-05-21)
 
        datas = {}
        datas["vehicleId"] = "2"
        datas["insuraName"] = (randomInsurance)
        datas["insurancePolicy"] = (randomStr) + str((10000, 99999)) + (randomStr) + str((10000, 99999));
        datas["insuranceDateBegin"] = date
        datas["insuranceDateEnd"] = dateOne
        datas["strongPolicy"] = (randomStr) + str((10000, 99999)) + (randomStr) + str((10000, 99999));
        datas["strongDateBegin"] = date
        datas["strongDateEnd"] = dateOne
        datas["license"] = i
 
        print(datas)
        res=(url=AddCarURL, data=(datas), headers=headers)
        print()
 
 
addCar(100)
 
 

Remember to pass the token authentication, as well as according to the data to json can be

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.