gpt4 book ai didi

python-3.x - 如何在Python中使用线程调用HTTP API

转载 作者:行者123 更新时间:2023-12-02 16:47:56 26 4
gpt4 key购买 nike

我有一个项目,其中我使用opencv显示来自USB摄像机的实时视频。在代码之间,有一个条件。当它变成True时,我必须调用一个API来获取一些我正在实时视频提要帧上显示的数据。调用API并获取响应会花费一些时间(2-3秒),在此期间冻结帧看起来不太好。下面是代码片段:

if config['ROIX1'] < f_startX and config['ROIX2']:
# Call the API and get the response
"""
OTHER CODE
"""

conn = http.client.HTTPSConnection('api.tive.com')
conn.request("POST", "/get_status", json_data, headers)
response = conn.getresponse()
rdata = response.read()
rdata = rdata.decode('utf8')
rdata = json.loads(rdata)

subject = rdata['subject']

txt = "SUBJECT: {}".format(subject)
cv2.putText(frame, txt, (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)

cv2.imshow(win_name, frame)

key = cv2.waitKey(1)
if key == ord('q'):
break

在上述代码中,如果if条件变为True,则代码将调用该API,并且响应 rdata需要花费一些时间,由于该原因应用程序冻结了一段时间。如何有效地处理API并从另一个线程获取API的响应,一旦获得结果,它就会显示在 frame上。我对 threads不太有经验。请帮忙。谢谢

最佳答案

我相信您正在寻找的逻辑是这样的:

1)启动线程以请求api

2)在请求未完成时执行其他任务(显示没有api数据的框架)

3)完成后中断,(显示带有api数据的框架)

我相信答案的关键是使用thread.is_alive,它检查线程是否处于 Activity 状态,并根据线程状态返回 bool(boolean) 值。 is_alive()方法通常在线程同步中使用。

我将通过执行类似于此伪代码的操作来完成您要查找的操作:

import sys
import trace
import threading
import time
def show_frame(subject=""):
if subject:
print(f"showing frame with {subject}")
else:
print(f"showing frame")

def request_api():
time.sleep(5)
return "data from api"

def show_frame_from_api():
subject_dataAPI=request_api()
show_frame(subject=subject_dataAPI)

t = threading.Thread(target=show_frame_from_api, args=())
t.start()

while t.is_alive():
show_frame()


在您的示例中应用它,我建议这样的事情:
import sys
import trace
import threading
import time
def show_frame(win_name, frame, apiText=""):
if apiText:
text=f'display with {apiText}'
cv2.putText(frame, text, (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
cv2.imshow(win_name, frame)
else
text=f'display without api text :('
cv2.putText(frame, text, (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
cv2.imshow(win_name, frame)

def show_frame_from_api(win_name, frame):
subject_dataAPI=request_api()
show_frame(win_name, frame, apiText=subject_dataAPI)


def request_api():
conn = http.client.HTTPSConnection('api.tive.com')
conn.request("POST", "/get_status", json_data, headers)
response = conn.getresponse()
rdata = response.read()
rdata = rdata.decode('utf8')
rdata = json.loads(rdata)

subject = rdata['subject']

txt = "SUBJECT: {}".format(subject)
return txt

if config['ROIX1'] < f_startX and config['ROIX2']:
# Call the API and get the response
"""
OTHER CODE
"""

t = threading.Thread(target=show_frame_from_api, args=(win_name, frame))
t.start()

while t.is_alive():
show_frame(win_name, frame)


key = cv2.waitKey(1)
if key == ord('q'):
break

关于python-3.x - 如何在Python中使用线程调用HTTP API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60653773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com