发送无预定义任务列表的异步请求

0 投票
1 回答
26 浏览
提问于 2025-04-12 01:33

我需要不断发送请求,而且要在特定的时间间隔内发送。我有一个使用线程的脚本,但这样会给服务器带来很大的负担。另外,我希望这些请求不是在同一个会话中进行,并且想避免使用缓存的响应。

我想用asyncio重新写这个程序,但遇到了一个问题,就是我需要提前定义一个任务列表,而且在调用'gather'的时候会有很大的延迟。

1 个回答

0

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这种时候,我们可以去一些技术论坛,比如StackOverflow,寻求帮助。在这些论坛上,很多人会分享他们的经验和解决方案。

当你在这些论坛上提问时,记得把你的问题描述清楚,包括你遇到的错误信息和你尝试过的解决方法。这样,其他人才能更好地理解你的问题,并给出有效的建议。

另外,查看别人提问和回答的问题也是一个很好的学习方式。你可以从中学到很多实用的知识和技巧,帮助你更好地解决自己的编程问题。

总之,利用好这些技术社区,可以让你的编程之路更加顺利。

import sys
sys.path.insert(0, "../")

import time
from loguru import logger
from auth import Auth
import requests
import threading
import orjson
from utils import retry_on_exception


logger.add("logs.log", filter=lambda record: record["extra"].get("logs") == True)


# URLS constants
URL = "https:....."
# .....


CONST1 = "..."

CONST2 = "..."

data_list = []
locker = threading.Lock()


@retry_on_exception
def func1(acc, info):
    data = {
        # data CONST1
    }

    resp = requests.post(url=URL,
                         headers=acc.get_headers(),
                         cookies=acc.get_cookies(),
                         json=data)


@retry_on_exception
def func2(acc, info1, info2):
    data = {
        # info1 info2 CONST2
    }
    resp = requests.post(URL,
                         headers=acc.get_headers(),
                         cookies=acc.get_cookies(),
                         json=data)
    if resp.json()["code"] == "..." and resp.json().get("error"):
        logger.info("...", logs=True)
        return

    logger.debug("{resp}", resp=resp, resp_text=resp.text)
    info = resp.json()["..."]
    func1(info=info, acc=acc)


def exception_execute(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as ex:
            logger.exception("{ex}", ex=ex, console=True)

    return wrapper


@exception_execute
def func3(acc, cookies, proxy):
    resp = requests.get(URL, cookies=cookies, proxies=proxy)
    print(resp, time.time()) # use print because logs loads more cpu

    resp_json = orjson.loads(resp.text)
    infos = resp_json["..."]
    goods_infos = resp_json["..."]

    for i in infos:
        info1 = i["..."]
        info2 = i["..."]
        info3 = i["..."]

        if True or False: # if with received information
            with locker:
                if info1 not in data_list:
                    data_list.append(info1)
                else:
                    continue

            func2(info1=info1,
                  info2=info2,
                  acc=acc)

            logger.info("...", console=True, logs=True)
            logger.info("{info1}", info1=info1, console=True, logs=True)
            logger.info("{info2}", info2=info2, console=True, logs=True)



def get_acc():
    acc_paths = [
        # acc path list
    ]

    acc_list = [Auth(path).get_cookies() for path in acc_paths]

    while True:
        for acc in acc_list:
            yield acc


def main():
    proxy_list = [
        {}
    ]

    main_acc = Auth(r"accounts/..")
    main_acc.ensure_auth()

    acc_gen = get_acc()

    while True:
        for proxy in proxy_list:
            time.sleep(0.04)
            t = threading.Thread(target=func3, args=(acc, next(acc_gen), proxy))
            t.start()


if __name__ == '__main__':
    main()

撰写回答