通过请求进行线程化的HTTP发布,而无需等待请求通过

问题描述

我的程序每250毫秒左右发送一次http帖子,我希望它在请求通过时继续运行。本质上,我正在寻找一个文件遗忘系统之类的东西,它只是发出请求(可能在另一个线程中),并且继续运行而无需等待服务器的响应。

程序看起来像:

while True:
    value_to_send = some_function()
    x = requests.post(url,json = myjson) # this json has the updated value_to_send in it 

解决方法

您可以使用线程,而不必等待它们完成:

from threading import Thread
import time

def request():
    # value_to_send = some_function()
    # x = requests.post(url,json = myjson)
    print('started')
    time.sleep(.5)
    print("request done!")


def main():
    while True:
        t = Thread(target=request)
        t.start()
        time.sleep(.25)

main()

输出:

started
started
request done!
started
request done!
started
request done!
...