从python3请求生成http错误

2024-06-26 13:38:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python3requests包实现了一个简单的长轮询。它现在看起来像:

def longpoll():
    session = requests.Session()
    while True:
        try:
            fetched = session.get(MyURL)
            input = base64.b64decode(fetched.content)
            output = process(data) 
            session.put(MyURL, data=base64.b64encode(response))
        except Exception as e:
            print(e)
            time.sleep(10)

在这种情况下,我不想process调用输入和put调用结果,而是想引发一个http错误。有没有一种简单的方法可以从高级Session接口实现这一点?或者我必须向下钻取才能使用较低级别的对象?你知道吗


Tags: truedataputsessiondefrequestsprocesspython3
1条回答
网友
1楼 · 发布于 2024-06-26 13:38:15

因为你已经控制了服务器,所以你可能想取消第二次呼叫

下面是一个使用瓶子接收第二次投票的示例

def longpoll():
    session = requests.Session()
    while True: #I'm guessing that the server does not care that we call him a lot of times ...
        try: 
            session.post(MyURL, {"ip_address": my_ip_address}) # request work or I'm alive
            #input = base64.b64decode(fetched.content)
            #output = process(data) 
            #session.put(MyURL, data=base64.b64encode(response))
        except Exception as e:
            print(e)
            time.sleep(10)

@bottle.post("/process") 
def process_new_work():
    data = bottle.request.json()
    output = process(data) #if an error is thrown an HTTP error will be returned by the framework
    return output

这样服务器将获得输出或错误的HTTP状态

相关问题 更多 >