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和exception,它将无法正常工作。

最佳答案

不知道是否也可以在没有服务器端实现的情况下按需恢复,但是可以从客户端恢复。这是一个简单的阻止示例,但您可能希望将其放入线程中。

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/

10-12 22:05