简体   繁体   中英

The fastest way to send http requests in python

I am making a minecraft name sniping bot. I have a list of tokens and minecrafts api lets you send three requests for each token, before blocking them. A request to it looks something like this:

requests.put(f'https://api.minecraftservices.com/minecraft/profile/name/{name}',
             headers={"Authorization": "Bearer " + token,
             "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0",
             "Content-Type": "application/json"})

Now I could just use a simple for loop and send all the requests that way, but it seems to be really slow and I am pretty sure there are ways to speed it up. I've heard of multithreading, multiproccessing and asyncio, but I am not really sure which one of them would be the fastest one and how to use them in the most efficient way. I would really appreciate it if someone could help me to figure this out.

I believe Python: How can i send multiple http requests at the same time? (like fork) answers your question, You're right to solve this problem with multithreading, try usingconcurrent.futures .

If you want to send 3 requests at a time, then make a thread pool with 3 workers as follows:

def send_mc_request(token):
   ...

from concurrent.futures import ThreadPoolExecutor

tokens = [token1, token2, ...]
num_requests_to_send = 3

with ThreadPoolExecutor(max_workers=num_requests_to_send) as executor:
  for token in tokens:
    for _ in range(num_requests_to_send):
      executor.submit(send_mc_request, token)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM