gpt4 book ai didi

python - 断网后如何继续请求发帖

转载 作者:太空宇宙 更新时间:2023-11-03 21:04:25 25 4
gpt4 key购买 nike

with open("student.csv", "r") as csv_ledger:
r = csv.DictReader(csv_ledger)
data = [dict(d) for d in r ]
groups = {}

for k, g in groupby(data, lambda r: (r['name'])):
items = []
for i in g:
#data processing
try:
post_api = requests.post(ENDPOINT_URL, json=groups, headers=headers)
except requests.ConnectionError:
print("Something went wrong")
finally:
print("resume post request")

目前,当互联网连接断开时,我的代码将无法恢复发布请求。如果我使用 try 和异常,它就不起作用。

最佳答案

不确定您是否可以在没有服务器端实现的情况下按照您想要的方式恢复,但您可以从客户端恢复。这是一个简单的阻塞示例,但您可能希望将其放入线程中。

import csv
import socket
from time import sleep

import requests


def is_internet_on():
try:
socket.setdefaulttimeout(3)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(('1.1.1.1', '8080'))
return True
except:
return False


def do_call_later(url, headers, body):
while not is_internet_on():
sleep(5)
requests.post(url, headers=headers, body=body)


with open("student.csv", "r") as csv_ledger:
r = csv.DictReader(csv_ledger)
data = [dict(d) for d in r]
groups = {}

for k, g in groupby(data, lambda r: (r['name'])):
items = []
for i in g:
# data processing
pass
try:
timeout_arg = (
# first tuple value is the connection timeout,
# how long to wait before initial connection is established
1.0,
# second tuple value is the read timeout, this is how long
# the client will wait after the initial connection
# before dropping the connection because no response was sent
1.0
)
post_api = requests.post(ENDPOINT_URL, json=groups, headers=headers, timeout=timeout_arg)
except requests.ConnectionError:
do_call_later(ENDPOINT_URL, headers, groups)
finally:
print("resume post request")

编辑:超时调用的文档:https://github.com/kennethreitz/requests/blob/master/requests/api.py#L34

关于python - 断网后如何继续请求发帖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55519658/

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