Table of Contents
Multiple threads requesting multiple interfaces with parameters
How to use python to request the interface
Home Backend Development Python Tutorial How to solve the problem of python multi-thread requesting multiple interfaces with parameters

How to solve the problem of python multi-thread requesting multiple interfaces with parameters

Apr 24, 2023 pm 03:10 PM
python

Multiple threads requesting multiple interfaces with parameters

For process/thread/Ctrip/asynchronous content, I have time to prepare and write it. I have been using for to loop so slowly that I doubt the scenarios that need to be used in life. There will be a lot, so I will summarize it in a little bit.

Let’s go to the code first and take a look at the content. Multi-threaded request interface

imoprt threading # 首先运用到threading模块


class BrushGifts:
    # 以下是两个相同的接口 send_gift_room_one()是送礼的接口
    # 也就是说我想完成的状态是A送B B送A 两个用户同时想对方赠送礼物
    def giftt(self, uid, recvUid, giftId):
        """
        送礼接口
        :param uid: 送礼用户
        :param recvUid: 收礼用户
        :param giftId: 礼物道具id
        :return: 
        """
        VoiceRoom().send_gift_room_one(uid, recvUid, giftId)

    def giftt_a(self, uid, recvUid, giftId):
        # 与上面的接口相同 不多做叙述
        # 没什么区别 就是写着好理解俩接口的概念
        VoiceRoom().send_gift_room_one(recvUid, uid, giftId)


if __name__ == '__main__':
    # 因为我的账号是储存在yaml文件内 所以需要先倒出需要用户的uid列表
    # 送礼人与收礼人分别倒出
    uid_list = YamlHandler(YamlThePath().voice_room_cpNew).get_uid_list(10)
    rUid_list = YamlHandler(YamlThePath().number_old).get_scope_uid(1500, 10)
    # 这里暂时先展示最简单的AB同时互送~
    for (i, j) in zip(uid_list, rUid_list):
        # target内需要传入方法名 不要带()因为带括号就等于去调用了该方法 会直接开始执行
        # args内传入输入带入的参数 可以按顺序来 也可以整理成元组或字典接收
        t1 = threading.Thread(target=BrushGifts().giftt, args=(i, j, 51620))
        # 两个threading.Thread就是我请求并发两个接口
        t2 = threading.Thread(target=BrushGifts().giftt, args=(j, i, 51620))
        # t1.start()为执行
        t1.start()
        t2.start()
Copy after login

Main thread:

Main thread The concept is to execute the py file from scratch. When I finish executing the last line of code t2.start(), the main thread will enter the waiting state. The main thread will not end until the child thread ends.

子Thread:

The concept of sub-thread is that during the execution of the main thread, I executed it here. Of course, it is called through the t1.start() method

t1 = threading.Thread(target=BrushGifts().giftt, args=(i, j, 51620))
Copy after login

At this time The system will create another sub-thread to execute and call the BrushGifts().giftt method

The main thread will execute t1.start() and t2.start() but it will not wait for them. When the execution ends, the main thread will continue, so t1.start() and t2.start() are requested at the same time. The main thread will not end until both sub-processes t1.start() and t2.start() end. ~

Because the main thread executes t1.start() and t2.start() line by line and python cannot achieve concurrency in the exact sense, this method is not suitable if the data speed requirements are very high. Applicable

How to use python to request the interface

Function: used to repeatedly insert data

1. First download python and then enter python in cmd to determine whether the global installation is successful

2. Download PcIdea

3. Download the libraries you need

How to solve the problem of python multi-thread requesting multiple interfaces with parameters

4. Check the request network

  • Press F12

  • Make a request to the interface

  • First verify the required header request header data

How to solve the problem of python multi-thread requesting multiple interfaces with parameters

  • View text request

5. Give you a template and experience it slowly

 import requests                         #导入requests包
import random
import json
import time
 
# response = requests.get('http://www.baidu.com')
# print(response.status_code)  # 打印状态码
# print(response.url)          # 打印请求url
# print(response.headers)      # 打印头信息
# print(response.cookies)      # 打印cookie信息
# print(response.text)  #以文本形式打印网页源码
# print(response.content) #以字节流形式打印
# print(response.json())
 
 
AddCarURL = "http://localhost:10086/jeecg-boot/cable/insurance/add"
AddCarCookies = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjkwOTUyNzcsInVzZXJuYW1lIjoiYWRtaW4ifQ.Kn1jB5gUkCdnszSVxnjVVKtRMbx_WJSVZW6G-yJaid8"
randomStr = "ABCDEFGHIJKLMNOPQRST"
randomInsurance = ["泰康人寿","阳光保险","新华保险","太平人寿","同方全球人寿","友邦保险"," 招商仁和","平安保险"]
randomBox = ["石鲜仓储","明顺仓储","雄星仓储","金盛仓储","旺恒仓储","中豹仓储","飞翔仓储","速发仓储","春天仓储"]
sess = requests.session()
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)              #设置开始日期时间元组(1976-01-01 00:00:00)
a2=(2019,3,16,23,59,59,0,0,0)    #设置结束日期时间元组(1990-12-31 23:59:59)
 
a3=(2019,3,16,0,0,0,0,0,0)              #设置开始日期时间元组(1976-01-01 00:00:00)
a4=(2021,8,16,23,59,59,0,0,0)    #设置结束日期时间元组(1990-12-31 23:59:59)
 
start=time.mktime(a1)    #生成开始时间戳
end=time.mktime(a2)      #生成结束时间戳
 
start1=time.mktime(a3)    #生成开始时间戳
end2=time.mktime(a4)      #生成结束时间戳
 
# for i in range(10):
#     t=random.randint(start,end)    #在开始和结束时间戳中随机取出一个
#     date_touple=time.localtime(t)          #将时间戳生成时间元组
#     date=time.strftime("%Y-%m-%d",date_touple)  #将时间元组转成格式化字符串(1976-05-21)
#
#     t1 = random.randint(start1,end2)
#     date_touplen=time.localtime(t1)          #将时间戳生成时间元组
#     dateOne=time.strftime("%Y-%m-%d",date_touplen)  #将时间元组转成格式化字符串(1976-05-21)
#     print(date + " " +dateOne)
 
 
 
 
 
def addCar(num:int):
    # {"type": "2", "carryingCapacity": "3吨", "license": "粤A888", "engineNumber": "123456", "state": 0}
 
    # {"vehicleId": "2", "insuraName": "人寿保险", "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 = random.randint(start, end)  # 在开始和结束时间戳中随机取出一个
        date_touple = time.localtime(t)  # 将时间戳生成时间元组
        date = time.strftime("%Y-%m-%d", date_touple)  # 将时间元组转成格式化字符串(1976-05-21)
 
        t1 = random.randint(start1, end2)
        date_touplen = time.localtime(t1)  # 将时间戳生成时间元组
        dateOne = time.strftime("%Y-%m-%d", date_touplen)  # 将时间元组转成格式化字符串(1976-05-21)
 
        datas = {}
        datas["vehicleId"] = "2"
        datas["insuraName"] = random.choice(randomInsurance)
        datas["insurancePolicy"] = random.choice(randomStr) + str(random.randint(10000, 99999)) + random.choice(randomStr) + str(random.randint(10000, 99999));
        datas["insuranceDateBegin"] = date
        datas["insuranceDateEnd"] = dateOne
        datas["strongPolicy"] = random.choice(randomStr) + str(random.randint(10000, 99999)) + random.choice(randomStr) + str(random.randint(10000, 99999));
        datas["strongDateBegin"] = date
        datas["strongDateEnd"] = dateOne
        datas["license"] = i
 
        print(datas)
        res=requests.post(url=AddCarURL, data=json.dumps(datas), headers=headers)
        print(res.text)
 
 
addCar(100)
Copy after login

Remember to pass token verification and convert the data to json.

The above is the detailed content of How to solve the problem of python multi-thread requesting multiple interfaces with parameters. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles