


How to solve the problem of python multi-thread requesting multiple interfaces with parameters
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()
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))
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
4. Check the request network
-
Press F12
Make a request to the interface
First verify the required header request header data
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)
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!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.